问:
C# Winforms: PropertyGrid not updated when item added to Collection
I've got a custom class which can be edited through the PropertyGrid. In that class I've got a custom Collection (with custom PropertyDescriptor and TypeConverter).

Items can be added to or removed from the Collection with the default Collection Editor. This all works fine. But - after closing the Collection Editor, the PropertyGrid is not updated. When I manual make a call to Refresh() on the PropertyGrid, the changes are reflected in the PropertyGrid.

How can I get the PropertyGrid to automatically refresh when the Collection Editor has been closed? I sought for a solution earlier where I should subclass CollectionEditor (which I can't seem to find).

Please help.

答:
I get solution in this situation.
There is a need to derive from CollectionEditor class and make custom editor like this:

```<code>public class MeasuredParamEditor : CollectionEditor
{

    public static EventHandler CollectionChanged;

    public MeasuredParamEditor(Type type)
        : base(type)
    { }

    protected override string GetDisplayText(object value)
    {
        if (value is MeasuredParam)
        {
            MeasuredParam param = (MeasuredParam)value;
            return string.Format("{0}: {1}", param.Name, param.Value);
        }
        else return base.GetDisplayText(value);
    }

    protected override CollectionForm CreateCollectionForm()
    {
        CollectionForm collectionForm = base.CreateCollectionForm();
        Form frm = collectionForm as Form;
        if (frm != null)
        {
            // Get OK button of the Collection Editor...
            Button button = frm.AcceptButton as Button;
            // Handle click event of the button
            button.Click += new EventHandler(OnCollectionChanged);
        }
        return collectionForm;
    }

    void OnCollectionChanged(object sender, EventArgs e)
    {
        if (CollectionChanged != null)
        {
            CollectionChanged(sender, e);
        }
    }
}
</code>```

In main form I subscribe to static event of my custom editor.

```<code>    private void MainForm_Load(object sender, EventArgs e)
    {
            MeasuredParamEditor.CollectionChanged += new EventHandler(OnMeasuredParamsChanged);
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        MeasuredParamEditor.CollectionChanged -= new EventHandler(OnMeasuredParamsChanged);

    }

    void OnMeasuredParamsChanged(object sender, EventArgs e)
    {
        this.myPropGrid.Refresh();
    }
</code>```

Regards, Artem

ContentLicense: CC BY-SA 2.5

Body:
I get solution in this situation.
There is a need to derive from CollectionEditor class and make custom editor like this:

public class MeasuredParamEditor : CollectionEditor
{

    public static EventHandler CollectionChanged;

    public MeasuredParamEditor(Type type)
        : base(type)
    { }

    protected override string GetDisplayText(object value)
    {
        if (value is MeasuredParam)
        {
            MeasuredParam param = (MeasuredParam)value;
            return string.Format("{0}: {1}", param.Name, param.Value);
        }
        else return base.GetDisplayText(value);
    }

    protected override CollectionForm CreateCollectionForm()
    {
        CollectionForm collectionForm = base.CreateCollectionForm();
        Form frm = collectionForm as Form;
        if (frm != null)
        {
            // Get OK button of the Collection Editor...
            Button button = frm.AcceptButton as Button;
            // Handle click event of the button
            button.Click += new EventHandler(OnCollectionChanged);
        }
        return collectionForm;
    }

    void OnCollectionChanged(object sender, EventArgs e)
    {
        if (CollectionChanged != null)
        {
            CollectionChanged(sender, e);
        }
    }
}

In main form I subscribe to static event of my custom editor.

    private void MainForm_Load(object sender, EventArgs e)
    {
            MeasuredParamEditor.CollectionChanged += new EventHandler(OnMeasuredParamsChanged);
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        MeasuredParamEditor.CollectionChanged -= new EventHandler(OnMeasuredParamsChanged);

    }

    void OnMeasuredParamsChanged(object sender, EventArgs e)
    {
        this.myPropGrid.Refresh();
    }

Regards, Artem


来源: stackexchange

问:
Extracting similar variables in three dataframes in R
So currently, i have three dataframes:

```<code>>df1

 Variable      Val
    a          0.9
    g          0.3
    e          0.1

>df2

 Variable       Val
   h            0.2
   a            0.7
   e            0.9

>df3

 Variable       Val
   z            0.5
   a            0.7
   e            0.9
</code>```

and I'm trying to extract the Variable which appears in all three dataframe, which is a and e in this case, since a and e appears in df1,df2,and df3.

Hence the output i wanted is:

```<code>[1] a  e
</code>```

Which is just the variable, without the val.

I tried something like:

```<code>similar <- subset(df1, Variable%in% df2$Variable)
</code>```

But it seemed like its only limited to two dataframes but not three?

答:
An option would be to place the datasets in a list, extract the 'variable' column and get the elements that are common with intersect

```<code>Reduce(intersect, lapply(mget(paste0("df", 1:3)), `[[`, "Variable"))
#[1] "a" "e"
</code>```

Or similar option with tidyverse

```<code>library(tidverse)
mget(paste0("df", 1:3)) %>%
      map(~ .x %>%
               pull(Variable)) %>%
      reduce(intersect)
#[1] "a" "e"
</code>```

Or we bind the datasets into a single one, grouped by 'Variable', filter the number of unique groups equal to 3 and extract he 'Variable'

```<code>bind_rows(df1, df2, df3, .id = 'grp') %>%
     group_by(Variable) %>%
     filter(n_distinct(grp) == 3) %>%
     distinct(Variable) %>%
     pull(Variable)
</code>```

[1] "a" "e"

data

```<code>df1 <- structure(list(Variable = c("a", "g", "e"), Val = c(0.9, 0.3,
0.1)), class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(Variable = c("h", "a", "e"), Val = c(0.2, 0.7,
0.9)), class = "data.frame", row.names = c(NA, -3L))

df3 <- structure(list(Variable = c("z", "a", "e"), Val = c(0.5, 0.7,
0.9)), class = "data.frame", row.names = c(NA, -3L))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So currently, i have three dataframes:

>df1

 Variable      Val
    a          0.9
    g          0.3
    e          0.1

>df2

 Variable       Val
   h            0.2
   a            0.7
   e            0.9

>df3

 Variable       Val
   z            0.5
   a            0.7
   e            0.9

and I'm trying to extract the Variable which appears in all three dataframe, which is a and e in this case, since a and e appears in df1,df2,and df3.

Hence the output i wanted is:

[1] a  e

Which is just the variable, without the val.

I tried something like:

similar <- subset(df1, Variable%in% df2$Variable)

But it seemed like its only limited to two dataframes but not three?

Body:
An option would be to place the datasets in a list, extract the 'variable' column and get the elements that are common with intersect

Reduce(intersect, lapply(mget(paste0("df", 1:3)), `[[`, "Variable"))
#[1] "a" "e"

Or similar option with tidyverse

library(tidverse)
mget(paste0("df", 1:3)) %>%
      map(~ .x %>%
               pull(Variable)) %>%
      reduce(intersect)
#[1] "a" "e"

Or we bind the datasets into a single one, grouped by 'Variable', filter the number of unique groups equal to 3 and extract he 'Variable'

bind_rows(df1, df2, df3, .id = 'grp') %>%
     group_by(Variable) %>%
     filter(n_distinct(grp) == 3) %>%
     distinct(Variable) %>%
     pull(Variable)

[1] "a" "e"

data

df1 <- structure(list(Variable = c("a", "g", "e"), Val = c(0.9, 0.3,
0.1)), class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(Variable = c("h", "a", "e"), Val = c(0.2, 0.7,
0.9)), class = "data.frame", row.names = c(NA, -3L))

df3 <- structure(list(Variable = c("z", "a", "e"), Val = c(0.5, 0.7,
0.9)), class = "data.frame", row.names = c(NA, -3L))


问:
How do I add a required field using mongoose and mongodb?
Let's say I have an existing Schema:

```<code>var OrderSchema = new Schema({
    field1: {type: String, required; true},
})
</code>```

but I want to add another field, field2 of type Boolean, to this schema and make it required. I also want all existing documents to have the field2 value set to false. How would one go about doing this using a node server and mongoose?

I'm thinking that I might be able to have a prestart script that sets all existing documents' field2 to false and that way all the existing documents will have the field, and any new documents would be required to have a field2 set while saving because the schema will have been updated when the server starts. Is there a standard practice for this kind of stuff?

I am not asking how to create a default field in a mongoose schema. I was asking how to ensure that previous documents have a default and required field and how people normally go about populating previous documents in a collection. Please do not mark as duplicate.

@Fanpark, none of these questions answer my question. Please remove them.

答:
```<code>var OrderSchema = new Schema({
    field1: {type: String, required: true},
    field2: {
        type: Boolean,
        default: false,
        required: true
    }
})
</code>```

this will add field2 to false at the creation of the object with .save, but will not modify the old documents. In the other hand, the method .find will add the field if it is not there and set it to false (just in query’s result, that will not update the document)

Body:
Let's say I have an existing Schema:

var OrderSchema = new Schema({
    field1: {type: String, required; true},
})

but I want to add another field, field2 of type Boolean, to this schema and make it required. I also want all existing documents to have the field2 value set to false. How would one go about doing this using a node server and mongoose?

I'm thinking that I might be able to have a prestart script that sets all existing documents' field2 to false and that way all the existing documents will have the field, and any new documents would be required to have a field2 set while saving because the schema will have been updated when the server starts. Is there a standard practice for this kind of stuff?

I am not asking how to create a default field in a mongoose schema. I was asking how to ensure that previous documents have a default and required field and how people normally go about populating previous documents in a collection. Please do not mark as duplicate.

@Fanpark, none of these questions answer my question. Please remove them.

Body:
var OrderSchema = new Schema({
    field1: {type: String, required: true},
    field2: {
        type: Boolean,
        default: false,
        required: true
    }
})

this will add field2 to false at the creation of the object with .save, but will not modify the old documents. In the other hand, the method .find will add the field if it is not there and set it to false (just in query’s result, that will not update the document)


问:
How to use Collapsing Toolbar with TabLayout using Material and AndroidX components?
I'm trying to use both Toolbar and TabLayout with CollapsingToolbarLayout but I'm getting a very strange behavior with the tab layout. The idea is to have the TabLayout with a transparent background when the Toolbar is expanded, and when collapsed, to be under the Toolbar like any other Activity with both Toolbar and TabLayout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <com.google.android.material.appbar.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:theme="@style/Theme.MaterialComponents.Light.NoActionBar"
    android:layout_width="match_parent"
    android:layout_height="250dp">

    <com.google.android.material.appbar.CollapsingToolbarLayout
      android:id="@+id/collapsing_toolbar_layout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_scrollFlags="scroll|exitUntilCollapsed"
      app:contentScrim="@color/primary"
      app:expandedTitleTextAppearance="@style/CollapsingToolbarExpandedTitleTheme">

      <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        app:layout_collapseMode="parallax"/>

      <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_height"
        app:titleTextAppearance="@style/ToolbarTitleTheme"
        app:layout_collapseMode="pin"/>

      <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_height"
        android:layout_gravity="bottom">

        <com.google.android.material.tabs.TabItem
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>

        <com.google.android.material.tabs.TabItem
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>

      </com.google.android.material.tabs.TabLayout>

    </com.google.android.material.appbar.CollapsingToolbarLayout>

  </com.google.android.material.appbar.AppBarLayout>

  <androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.viewpager.widget.ViewPager
      android:id="@+id/view_pager"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

  </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

UPDATE: Following the example mentioned by @ ismail alaoui (https://android.jlelse.eu/parallax-scrolling-header-tabs-android-tutorial-2cc6e40aa257), the layout better, but the TabLayout is still WHITE. There's no Style associated with it.

UPDATE: Adding android:background="transparent" to the TabLayout, as @ismail suggested, solves this issue. I also added an style to the TabLayout (Widget.MaterialComponents.TabLayout.Colored) just to improve the layout.

答:
i suggest you to follow this tutorial , it explain how to do what you are exactly looking for , it's not using androidx component , but you can use it the same way  , enjoy !

edit :

add this to appBarLayout and TabLayout attribute :

```<code>android:background="@android:color/transparent"
</code>```

Body:
I'm trying to use both Toolbar and TabLayout with CollapsingToolbarLayout but I'm getting a very strange behavior with the tab layout. The idea is to have the TabLayout with a transparent background when the Toolbar is expanded, and when collapsed, to be under the Toolbar like any other Activity with both Toolbar and TabLayout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <com.google.android.material.appbar.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:theme="@style/Theme.MaterialComponents.Light.NoActionBar"
    android:layout_width="match_parent"
    android:layout_height="250dp">

    <com.google.android.material.appbar.CollapsingToolbarLayout
      android:id="@+id/collapsing_toolbar_layout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_scrollFlags="scroll|exitUntilCollapsed"
      app:contentScrim="@color/primary"
      app:expandedTitleTextAppearance="@style/CollapsingToolbarExpandedTitleTheme">

      <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        app:layout_collapseMode="parallax"/>

      <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_height"
        app:titleTextAppearance="@style/ToolbarTitleTheme"
        app:layout_collapseMode="pin"/>

      <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_height"
        android:layout_gravity="bottom">

        <com.google.android.material.tabs.TabItem
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>

        <com.google.android.material.tabs.TabItem
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>

      </com.google.android.material.tabs.TabLayout>

    </com.google.android.material.appbar.CollapsingToolbarLayout>

  </com.google.android.material.appbar.AppBarLayout>

  <androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.viewpager.widget.ViewPager
      android:id="@+id/view_pager"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

  </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

UPDATE: Following the example mentioned by @ ismail alaoui (https://android.jlelse.eu/parallax-scrolling-header-tabs-android-tutorial-2cc6e40aa257), the layout better, but the TabLayout is still WHITE. There's no Style associated with it.

UPDATE: Adding android:background="transparent" to the TabLayout, as @ismail suggested, solves this issue. I also added an style to the TabLayout (Widget.MaterialComponents.TabLayout.Colored) just to improve the layout.

Body:
i suggest you to follow this tutorial , it explain how to do what you are exactly looking for , it's not using androidx component , but you can use it the same way  , enjoy !

edit :

add this to appBarLayout and TabLayout attribute :

android:background="@android:color/transparent"


问:
Vary the command/pathmap run in a rake rule based on which target is running
I'm trying to write a Rakefile that both builds my code normally when I run rake compile but puts the targets in a different directory and builds with -DTEST when I run rake test.  I cannot for the life of me figure out how to do it, though.  I've got something like this at the moment:

```<code>SRC = FileList['src/*.erl']
OBJ = SRC.pathmap("%{src,ebin}/X.beam")

rule ".beam" => ["%{ebin,src}X.erl"] do |t|
  sh "erlc ... -o ebin #{t.source}"
end

task :compile => OBJ
</code>```

What I'd like is a task :test that put the compiler output into ebin_test (basically changed all instances of ebin into ebin_test in the above code) and added a -DTEST to the sh call.  Anyone got any ideas?

答:
Well, that wasn't a positive first question... no answers.

For the record, I solved the problem by having a task for both build and test that defined the compilation rules differently, and then had the public task call that task before doing the actual build/test run.  A couple of scoping issues, but nothing exciting.  I won't bother pasting the full resulting rakefile, but let me know if you're interested in taking a look.

OwnerDisplayName: womble

Body:
I'm trying to write a Rakefile that both builds my code normally when I run rake compile but puts the targets in a different directory and builds with -DTEST when I run rake test.  I cannot for the life of me figure out how to do it, though.  I've got something like this at the moment:

SRC = FileList['src/*.erl']
OBJ = SRC.pathmap("%{src,ebin}/X.beam")

rule ".beam" => ["%{ebin,src}X.erl"] do |t|
  sh "erlc ... -o ebin #{t.source}"
end

task :compile => OBJ

What I'd like is a task :test that put the compiler output into ebin_test (basically changed all instances of ebin into ebin_test in the above code) and added a -DTEST to the sh call.  Anyone got any ideas?


问:
How to draw shapes continuously on a panel?
I've been trying to draw shapes continuously without erasing the previous shape, but I'm always stuck on this.

I've also tried DrawOnImage based on this site
https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/

That's why the code below is mostly similar to that example:

```<code>public class exo {
static class DrawingArea extends JPanel {

        private final static int AREA_SIZE = 600;
        private BufferedImage image = new BufferedImage(AREA_SIZE, AREA_SIZE, BufferedImage.TYPE_INT_ARGB);
        public CustomShape shape;
        public Shape s1;

    public DrawingArea() {
        setBackground(Color.WHITE);
        MyMouseListener ml = new MyMouseListener();
        addMouseListener(ml);
        addMouseMotionListener(ml);

    }

    class MyMouseListener extends MouseInputAdapter {

        private Point pointStart;
        private Point pointEnd;

        public void mousePressed(MouseEvent e) {
            pointStart = e.getPoint();
            s1 = null;
            shape = new CustomShape();
            //System.out.println(pointStart);
        }

        public void mouseDragged(MouseEvent e) {
            pointEnd = e.getPoint();
            shape.setX1(pointStart.x);
            shape.setX2(pointEnd.x);
            shape.setY1(pointStart.y);
            shape.setY2(pointEnd.y);

            s1 = drawInductor(shape.getX1(), shape.getX2(), shape.getY1(), shape.getY2());
            repaint();
        }

        public void mouseReleased(MouseEvent e) {
            //pointEnd = e.getPoint();
            if (shape.getX1() != shape.getX2()) {
                addShape(s1, e.getComponent().getForeground());
            }
            //s1 = null;
            //System.out.println(pointEnd);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return isPreferredSizeSet()
                ? super.getPreferredSize() : new Dimension(AREA_SIZE, AREA_SIZE);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //  Custom code to support painting from the BufferedImage
        if (image != null) {
            g.drawImage(image, 0, 0, null);
        }

        //  Paint the Rectangle as the mouse is being dragged
        if (shape != null) {
            Graphics2D g2d = (Graphics2D) g;

            g2d.draw(s1);
        }
    }

    public void addShape(Shape s, Color color) {
        //  Draw the Rectangle onto the BufferedImage

        Graphics2D g2d = (Graphics2D) image.getGraphics();
        g2d.draw(s);
        repaint();
    }

}
public static Shape drawInductor(double X1, double X2, double Y1, double Y2) {
    int count = 0;
    final int dx = 7;
    final int dy = 8;
    float x1, y1, x2, y2, x3, y3;
    final double alpha = Math.toRadians(75.0);
    double phi = Math.atan2((Y2 - Y1), (X2 - X1));
    double dist = Math.sqrt(Math.pow((X1 - X2), 2) + Math.pow((Y1 - Y2), 2));

    GeneralPath path = new GeneralPath();
    double x = X1;
    double y = Y1;

    path.moveTo(x, y);
    x += (float) (0.3 * dist);
    y = Y1;
    path.lineTo(x, y);

    do {
        path.curveTo(x - dx / 2, y + dy, x + dx + dx / 2, y + dy, x + dx, y);
        x += dx;
        y = Y1;
        count++;
    } while (x < X1 + 0.7 * dist && count < 35);

    x = X1 + (float) dist;
    y = Y1;
    path.lineTo(x, y);

    AffineTransform at = new AffineTransform();
    at.rotate(phi, X1, Y1);
    Shape resShape = at.createTransformedShape(path);
    return (resShape);
}
public static void main(String args[]) throws Exception {
    JFrame f = new JFrame("Run MTFK");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(
            600, 600);
    f.setLocation(
            300, 300);
    f.setResizable(
            false);
    DrawingArea drawingArea = new DrawingArea();
    f.getContentPane().add(drawingArea);

    f.setVisible(true);

}
}
</code>```

I'd like to know where are my problems and how to deal with them.
Thank you very much!

答:
In order to continuously draw components on in the panel, you need to always draw the previous ones before you draw the most recent.  So if you as you add them to say a List you would call repaint after each one assuming that is when you wanted to display them.

Assume each image is represented by a number.

```<code>Create image 1, add it to list and repaint
This draws 1.
Create image 2, add it to the list and repaint
This redraws 1 and now draws 2
Create image 3, add it to the list and repaint
This redraws 1,2 and now draws 3.
</code>```

So if you have  a List called shapes, your paintComponent method would have
something like this in it.

for (Shape s : shapes) {
   g.draw(s); // notice the casting Graphics g to Graphics2D gives you access to draw()
}
```

And painting as well as event processing is done on the EDT so keep activity there do a minimum.  Do as many of your calculations as possible outside of that thread.

Body:
I've been trying to draw shapes continuously without erasing the previous shape, but I'm always stuck on this.

I've also tried DrawOnImage based on this site
https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/

That's why the code below is mostly similar to that example:

public class exo {
static class DrawingArea extends JPanel {

        private final static int AREA_SIZE = 600;
        private BufferedImage image = new BufferedImage(AREA_SIZE, AREA_SIZE, BufferedImage.TYPE_INT_ARGB);
        public CustomShape shape;
        public Shape s1;

    public DrawingArea() {
        setBackground(Color.WHITE);
        MyMouseListener ml = new MyMouseListener();
        addMouseListener(ml);
        addMouseMotionListener(ml);

    }

    class MyMouseListener extends MouseInputAdapter {

        private Point pointStart;
        private Point pointEnd;

        public void mousePressed(MouseEvent e) {
            pointStart = e.getPoint();
            s1 = null;
            shape = new CustomShape();
            //System.out.println(pointStart);
        }

        public void mouseDragged(MouseEvent e) {
            pointEnd = e.getPoint();
            shape.setX1(pointStart.x);
            shape.setX2(pointEnd.x);
            shape.setY1(pointStart.y);
            shape.setY2(pointEnd.y);

            s1 = drawInductor(shape.getX1(), shape.getX2(), shape.getY1(), shape.getY2());
            repaint();
        }

        public void mouseReleased(MouseEvent e) {
            //pointEnd = e.getPoint();
            if (shape.getX1() != shape.getX2()) {
                addShape(s1, e.getComponent().getForeground());
            }
            //s1 = null;
            //System.out.println(pointEnd);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return isPreferredSizeSet()
                ? super.getPreferredSize() : new Dimension(AREA_SIZE, AREA_SIZE);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //  Custom code to support painting from the BufferedImage
        if (image != null) {
            g.drawImage(image, 0, 0, null);
        }

        //  Paint the Rectangle as the mouse is being dragged
        if (shape != null) {
            Graphics2D g2d = (Graphics2D) g;

            g2d.draw(s1);
        }
    }

    public void addShape(Shape s, Color color) {
        //  Draw the Rectangle onto the BufferedImage

        Graphics2D g2d = (Graphics2D) image.getGraphics();
        g2d.draw(s);
        repaint();
    }

}
public static Shape drawInductor(double X1, double X2, double Y1, double Y2) {
    int count = 0;
    final int dx = 7;
    final int dy = 8;
    float x1, y1, x2, y2, x3, y3;
    final double alpha = Math.toRadians(75.0);
    double phi = Math.atan2((Y2 - Y1), (X2 - X1));
    double dist = Math.sqrt(Math.pow((X1 - X2), 2) + Math.pow((Y1 - Y2), 2));

    GeneralPath path = new GeneralPath();
    double x = X1;
    double y = Y1;

    path.moveTo(x, y);
    x += (float) (0.3 * dist);
    y = Y1;
    path.lineTo(x, y);

    do {
        path.curveTo(x - dx / 2, y + dy, x + dx + dx / 2, y + dy, x + dx, y);
        x += dx;
        y = Y1;
        count++;
    } while (x < X1 + 0.7 * dist && count < 35);

    x = X1 + (float) dist;
    y = Y1;
    path.lineTo(x, y);

    AffineTransform at = new AffineTransform();
    at.rotate(phi, X1, Y1);
    Shape resShape = at.createTransformedShape(path);
    return (resShape);
}
public static void main(String args[]) throws Exception {
    JFrame f = new JFrame("Run MTFK");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(
            600, 600);
    f.setLocation(
            300, 300);
    f.setResizable(
            false);
    DrawingArea drawingArea = new DrawingArea();
    f.getContentPane().add(drawingArea);

    f.setVisible(true);

}
}

I'd like to know where are my problems and how to deal with them.
Thank you very much!

Body:
In order to continuously draw components on in the panel, you need to always draw the previous ones before you draw the most recent.  So if you as you add them to say a List you would call repaint after each one assuming that is when you wanted to display them.

Assume each image is represented by a number.

Create image 1, add it to list and repaint
This draws 1.
Create image 2, add it to the list and repaint
This redraws 1 and now draws 2
Create image 3, add it to the list and repaint
This redraws 1,2 and now draws 3.

So if you have  a List called shapes, your paintComponent method would have
something like this in it.

for (Shape s : shapes) {
   g.draw(s); // notice the casting Graphics g to Graphics2D gives you access to draw()
}

And painting as well as event processing is done on the EDT so keep activity there do a minimum.  Do as many of your calculations as possible outside of that thread.


问:
Packages: question about order of with statements
I have a short question: It is safe to sort with clauses in package specifications and bodies in ascending order for easier readability of the source code?

A simple example:

Not sorted:

with D;
with A;
with C.X;
with B; use B;
```

<p>Sorted:</p>

<pre class="lang-ada prettyprint-override"><code>with A;
with B; use B;
with C.X;
with D;
</code>```

答:
I think 10.1.4 and 10.2.1 can gave you more information.

The compiler do the job of the order of units (when it can). In case where it didn't (or you want a specific order) you can use pragmas (see 10.2.1).

Body:
I have a short question: It is safe to sort with clauses in package specifications and bodies in ascending order for easier readability of the source code?

A simple example:

Not sorted:

with D;
with A;
with C.X;
with B; use B;

Sorted:

with A;
with B; use B;
with C.X;
with D;


问:
What does "String[]::new" mean?
I'm learning how to use stream, and I get a problem with this method.

```<code>public static String[] inArray(String[] array1, String[] array2) {
   return Arrays.stream(array1)
  .filter(str -> Arrays.stream(array2).anyMatch(s -> s.contains(str)))
  .distinct().sorted().toArray(**String[]::new**);
}
</code>```

I'm so confused about String[]::new, could you give me a hint?

答:
I would say the existing answers provide some insight but none of them yet talk about IntFunction<R>.

To add to them explain, what it means in the context of Stream.toArray(String[]::new) is that it represents an IntFunction implementation such as :

```<code>new IntFunction<String[]>() {
    @Override
    public String[] apply(int value) {
        return new String[value];
    }
}
</code>```

where the code creates a newly allocated String[] of size value and produces the array of that size as an output.

ContentLicense: CC BY-SA 3.0

Title: What does "String[]::new" mean?

Body:
I'm learning how to use stream, and I get a problem with this method.

public static String[] inArray(String[] array1, String[] array2) {
   return Arrays.stream(array1)
  .filter(str -> Arrays.stream(array2).anyMatch(s -> s.contains(str)))
  .distinct().sorted().toArray(**String[]::new**);
}

I'm so confused about String[]::new, could you give me a hint?

Body:
I would say the existing answers provide some insight but none of them yet talk about IntFunction<R>.

To add to them explain, what it means in the context of Stream.toArray(String[]::new) is that it represents an IntFunction implementation such as :

new IntFunction<String[]>() {
    @Override
    public String[] apply(int value) {
        return new String[value];
    }
}

where the code creates a newly allocated String[] of size value and produces the array of that size as an output.


问:
Aligning two HTML objects side by side
I have a color box and some text. I'm trying to align the box exactly left of the text. I'm having issues trying to align it correctly.

I've tried looking at other posts on stack overflow and tried using the float property but couldn't align them correctly because the text goes too far to the right when using the float property. Here is the jsfiddle link if someone wants to run the code : https://jsfiddle.net/1qgep5tn/4/

```<code><!DOCTYPE html>

<html>
<head>

<style>

  .box {
    width: 20px;
    height: 20px;
   }

  .boxColor {
      background: #1c5a7d;
  }

    #right{
      float: right;
    }

    #left{
      float: left;
    }

</style>

</head>
<body>

<div class="box boxColor" ></div>
   Header:
     <br>
          <input type="text" name="firstname"  value="">
     <br>

</body>
</html>
</code>```

I'm expecting the box to be aligned left of the text but it is appearing above the text. Here is an image of what it looks like right now:

答:
The JSFiddle looks different than how you have it unless its edited. change the Heading
 to a
 and make sure its next to the box like this:

```<code><div class="google_map">
    <div class="box blueish"></div>
    <p class="paragraph">Header:</p>
  </div>
</code>```

and use display: inline-block in both the classes paragraph and box.

Title: Aligning two HTML objects side by side

Body:
I have a color box and some text. I'm trying to align the box exactly left of the text. I'm having issues trying to align it correctly.

I've tried looking at other posts on stack overflow and tried using the float property but couldn't align them correctly because the text goes too far to the right when using the float property. Here is the jsfiddle link if someone wants to run the code : https://jsfiddle.net/1qgep5tn/4/

<!DOCTYPE html>

   Header:

          <input type="text" name="firstname"  value="">

I'm expecting the box to be aligned left of the text but it is appearing above the text. Here is an image of what it looks like right now:

Body:
The JSFiddle looks different than how you have it unless its edited. change the Heading <div> to a <p> and make sure its next to the box like this:

<div class="google_map">
    <div class="box blueish"></div>
    <p class="paragraph">Header:</p>
  </div>

and use display: inline-block in both the classes paragraph and box.


问:
MongoDB: "Unrecognized option: systemLog"
guys.

I have a problem with the configuration files of MongoDB. It seem that use the YAML syntax.

I follow the instruction on the official website. I read something about YAML and I tried to figure out what is wrong, but I don't got any result.This is the mongod.conf file

```<code># mongod.conf

systemLog:
  verbosity=5
  traceAllExceptions=true
  path="/var/log/mongodb/mongod.log"
  destination=file
  timeStampFormat=iso8601-utc
  pidFilePath="/run/mongod.pid"

net:
  port=[8040,8041,8042]
  wiredObjectCheck=true
  ssl.mode=preferSSL
  ssl.PEMKeyFile="/var/lib/mongodb/mongo.pem"
  serviceExecutor=adaptive

storage:
  dbPath="/home/juny/nodeBox/data/db"

operationProfiling.mode=slowOp
</code>```

It's suppose to work well, when you execute the following command:

```<code>service mongod start
</code>```

But when you type following command:

```<code>service mongod status
</code>```

The terminal display this:

```<code>● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Sat 2019-05-25 20:12:24 AST; 2min 21s ago
 Docs: https://docs.mongodb.org/manual
Process: 5093 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=2)
Main PID: 5093 (code=exited, status=2)

May 25 20:12:24 systemd[1]: Started MongoDB Database Server.
May 25 20:12:24 systemd[1]: mongod.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
May 25 20:12:24 systemd[1]: mongod.service: Unit entered failed state.
May 25 20:12:24 systemd[1]: mongod.service: Failed with result 'exit-code'.
</code>```

I type the following command

```<code>sudo mongod --config=/etc/mongod.conf
</code>```

and this is the result

```<code>Unrecognized option: systemLog
try 'mongod --help' for more information
</code>```

答: Ok , I found the error. The configuration file its must be look like the same above, but changing the equal symbol '=' by a colon ':'. Also, some words in the configuration are wrong. I had to verify the manual to realize the failure.</p>

Body:
guys.

I have a problem with the configuration files of MongoDB. It seem that use the YAML syntax.

I follow the instruction on the official website. I read something about YAML and I tried to figure out what is wrong, but I don't got any result.This is the mongod.conf file

# mongod.conf

systemLog:
  verbosity=5
  traceAllExceptions=true
  path="/var/log/mongodb/mongod.log"
  destination=file
  timeStampFormat=iso8601-utc
  pidFilePath="/run/mongod.pid"

net:
  port=[8040,8041,8042]
  wiredObjectCheck=true
  ssl.mode=preferSSL
  ssl.PEMKeyFile="/var/lib/mongodb/mongo.pem"
  serviceExecutor=adaptive

storage:
  dbPath="/home/juny/nodeBox/data/db"

operationProfiling.mode=slowOp

It's suppose to work well, when you execute the following command:

service mongod start

But when you type following command:

service mongod status

The terminal display this:

● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Sat 2019-05-25 20:12:24 AST; 2min 21s ago
 Docs: https://docs.mongodb.org/manual
Process: 5093 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=2)
Main PID: 5093 (code=exited, status=2)

May 25 20:12:24 systemd[1]: Started MongoDB Database Server.
May 25 20:12:24 systemd[1]: mongod.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
May 25 20:12:24 systemd[1]: mongod.service: Unit entered failed state.
May 25 20:12:24 systemd[1]: mongod.service: Failed with result 'exit-code'.

I type the following command

sudo mongod --config=/etc/mongod.conf

and this is the result

Unrecognized option: systemLog
try 'mongod --help' for more information


问:
Deserializing JSON array with Unity JsonUtility fails to get serialized values
I'm trying to deserialize card information from a JSON to be used in a Unity game, but it's not working quite right. I've tested the classes I'm trying to deserialize to, and I can manually create objects for them, but the deserializer doesn't create them correctly.

When I run the deserializing logic, the resulting array is the correct size, but none of the Cost or Name fields of the cards fill in and I'm left with an array of uninitialized Card objects.

The relevant code I have is as follows:

The file where we deserialize, Game.cs:

```<code>using System.IO;
using UnityEngine;
public class Game {

    private CardsCollection allCards;

    private void LoadJson()
    {
        ...
        // Find the path to our JSON file
        // Save the path as "path"

        // I have verified this line gets the correct json data as a string
        string json = File.ReadAllText(path);

        // Convert the json string into a deserialized array of objects
        // using the CardsCollection wrapper
        allCards = JsonUtility.FromJson<CardsCollection>(json);
    }

}
</code>```

The Card object file, Card.cs:

```<code>using System;
[Serializable]
public class Card
{
    public string Name { get; set; }
    public int Cost    { get; set; }

    public Card(string Name, int Cost)
    {
        this.Name = Name;
        this.Cost = Cost;
    }
}

[Serializable]
public class CardsCollection
{
    public Card[] cards;
}

</code>```

And finally the JSON itself:

```<code>{
    "cards": [
        {
            "Name": "copper",
            "Cost": 0
        },
        {
            "Name": "silver",
            "Cost": 3
        },
        {
            "Name": "gold",
            "Cost": 6
        },
        {
            "Name": "curse",
            "Cost": 0
        },
        {
            "Name": "estate",
            "Cost": 2
        },
        {
            "Name": "duchy",
            "Cost": 5
        },
        {
            "Name": "province",
            "Cost": 8
        }
    ]
}
</code>```

答:
The Json serialization can only handle fields (see supported types https://docs.unity3d.com/Manual/JSONSerialization.html) but your Name and Cost look like properties What is the difference between a field and a property?

Since they are marked public and can be accessed directly anyway I would just remove the {get; set}

Body:
I'm trying to deserialize card information from a JSON to be used in a Unity game, but it's not working quite right. I've tested the classes I'm trying to deserialize to, and I can manually create objects for them, but the deserializer doesn't create them correctly.

When I run the deserializing logic, the resulting array is the correct size, but none of the Cost or Name fields of the cards fill in and I'm left with an array of uninitialized Card objects.

The relevant code I have is as follows:

The file where we deserialize, Game.cs:

using System.IO;
using UnityEngine;
public class Game {

    private CardsCollection allCards;

    private void LoadJson()
    {
        ...
        // Find the path to our JSON file
        // Save the path as "path"

        // I have verified this line gets the correct json data as a string
        string json = File.ReadAllText(path);

        // Convert the json string into a deserialized array of objects
        // using the CardsCollection wrapper
        allCards = JsonUtility.FromJson<CardsCollection>(json);
    }

}

The Card object file, Card.cs:

using System;
[Serializable]
public class Card
{
    public string Name { get; set; }
    public int Cost    { get; set; }

    public Card(string Name, int Cost)
    {
        this.Name = Name;
        this.Cost = Cost;
    }
}

[Serializable]
public class CardsCollection
{
    public Card[] cards;
}

And finally the JSON itself:

{
    "cards": [
        {
            "Name": "copper",
            "Cost": 0
        },
        {
            "Name": "silver",
            "Cost": 3
        },
        {
            "Name": "gold",
            "Cost": 6
        },
        {
            "Name": "curse",
            "Cost": 0
        },
        {
            "Name": "estate",
            "Cost": 2
        },
        {
            "Name": "duchy",
            "Cost": 5
        },
        {
            "Name": "province",
            "Cost": 8
        }
    ]
}


问:
How do I get a button to run a function in a fragment?
I have a fragment and I want a button to run the function Calculate() when I press it. My fragment is also based from one of the templates.

I've tried the XML android:onClick thing, though I assume its looking inside MainActivity instead of the Fragment so it throws an error.
I've also followed trying to use an OnClickListener from another post, though setting it up (as in code inside OnCreateCiew) gave errors, though it might just be my amateur knowledge of how it works.

This is my calculate function (the function I'm trying to get to run when my button is clicked), which is inside the fragment activity:

    public void Calculate(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }
```

<p>If needed, heres the whole fragment activity</p>

<p>When using the XML onclick, my app just crashes when the button is pressed.
When using OnClickListener, I can't even compile because of errors.
I don't have much coding expertise to know what the template fragment code is doing, but I assume its conflicting with however I'm setting up the OnClickListener.</p>

<p>Here's how I tried to set up my OnClickListener:</p>

```    Button calculatebutton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
        calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
        calculatebutton.setOnClickListener(this);
        return kinematicsCalculatorView;
        // Inflate the layout for this fragment
       // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

    }

    public void onClick(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }
```

However, the this in calculatebutton.setOnClickListener(this); shows up as an error, (setOnClickListener(android.view.View.OnClickListener) in View cannot be applied to (com.example.myApp.FragmentCalculatorKinematics)). onClick method is shown as never being used.

答:
I've found somewhat of a solution...
Instead of putting my method inside the FragmentActivity, I just placed it into MainActivity and set android:OnClick="Calculate" in the fragment's XML file. Though I'm not sure if theres any repurcussions from doing this.</p>

Body:
I have a fragment and I want a button to run the function Calculate() when I press it. My fragment is also based from one of the templates.

I've tried the XML android:onClick thing, though I assume its looking inside MainActivity instead of the Fragment so it throws an error.
I've also followed trying to use an OnClickListener from another post, though setting it up (as in code inside OnCreateCiew) gave errors, though it might just be my amateur knowledge of how it works.

This is my calculate function (the function I'm trying to get to run when my button is clicked), which is inside the fragment activity:

    public void Calculate(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }

If needed, heres the whole fragment activity

When using the XML onclick, my app just crashes when the button is pressed.
When using OnClickListener, I can't even compile because of errors.
I don't have much coding expertise to know what the template fragment code is doing, but I assume its conflicting with however I'm setting up the OnClickListener.

Here's how I tried to set up my OnClickListener:

    Button calculatebutton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
        calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
        calculatebutton.setOnClickListener(this);
        return kinematicsCalculatorView;
        // Inflate the layout for this fragment
       // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

    }

    public void onClick(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }

However, the this in calculatebutton.setOnClickListener(this); shows up as an error, (setOnClickListener(android.view.View.OnClickListener) in View cannot be applied to (com.example.myApp.FragmentCalculatorKinematics)). onClick method is shown as never being used.


问:
Reuse function to delete an item
I want to make a button that adds and removes items.
The 'Delete form' button changes to 'Add form' after click it.
But after I've deleted and added forms, I want to delete forms again, but for reasons I don't understand, it doesn't happen.

I'm using the latest chrome browser version.

```<code><!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

    <title>Task 1</title>
</head>
<body style="height: 100%">
    <div class="container h-100">
        <div class="row h-100 justify-content-center align-content-center">
            <div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
            <div class=""><button type="button" class="btn btn-danger" id="danger">Delete form</button></div>
            <div class="breaker w-100" style="height:10%;"></div>
            <form id="form">
                <div class="form-group">
                    <label for="formGroupExampleInput">Example label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
                </div>
                <div class="form-group">
                    <label for="formGroupExampleInput2">Another label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
                </div>
            </form>
        </div>
    </div>
    <script src="./index.js"></script>
</body>
</html>
</code>```

```<code>document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
document.getElementsByClassName('btn-danger')[0].addEventListener("click", delete_function);

let inner_form = document.getElementById('form').innerHTML;

function open_google() {
    window.open('http://google.com', '_blank');
}

let buttons;

function button_change(button) {
    switch(button) {
        case "success":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Add form';
            buttons[1].className = 'btn btn-success';
            document.getElementsByClassName('btn-success')[0].addEventListener("click", add_function);
            break;
        case "danger":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Delete form';
            buttons[1].className = 'btn btn-danger';
            break;
        default:
            break;
    }
}

function delete_function() {
    let element = document.getElementById('form');
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    button_change("success");
}

function add_function() {
    document.getElementById('form').innerHTML = inner_form;
    button_change("danger");
}
</code>```

Example code: https://codepen.io/anon/pen/xNjPYj

答:
The main issue with your code was that the event listeners kept getting added but not removed, this caused them to pile up and run unpredictably. I added a function that determines what state the button is in and performs the correct function add_function or remove_function.

I also changed a few minor things

Now usesinnerHTML to textContent where possible for security

Button classes are updated using button.classList.add and button.classList.remove

The button is found using an ID instead of an unreliable classname

The button is held in a variable instead of continuing the look for it

Removed the button_change function because it was difficult to refactor

https://codepen.io/anon/pen/BexJZW

JavaScript:

```<code>document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);

let inner_form = document.getElementById('form').innerHTML;

let add_delete_button = document.querySelector('#add-delete-button');
add_delete_button.addEventListener("click", on_add_delete_clicked);

function open_google() {
    window.open('http://google.com', '_blank');
}

function on_add_delete_clicked() {
    let is_adding = add_delete_button.classList.contains("btn-success");
    if (is_adding) {
        add_function();
    } else {
        delete_function();
    }
}

function add_function() {
    const button = add_delete_button;
    document.getElementById('form').innerHTML = inner_form;

    // Update button
    button.textContent = 'Delete form';
    button.classList.remove("btn-success");
    button.classList.add("btn-danger");
}

function delete_function() {
    let element = document.getElementById('form');
    while (element.firstChild) {
        element.removeChild(element.firstChild);
    }

    // Update button
    const button = add_delete_button;
    button.textContent = 'Add form';
    button.classList.remove("btn-danger");
    button.classList.add("btn-success");
}
</code>```

HTML:

```<code><!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

  <title>Task 1</title>
</head>
<body style="height: 100%">
    <div class="container h-100">
        <div class="row h-100 justify-content-center align-content-center">
            <div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
            <div class=""><button type="button" class="btn btn-danger" id="add-delete-button">Delete form</button></div>
            <div class="breaker w-100" style="height:10%;"></div>
            <form id="form">
                <div class="form-group">
                    <label for="formGroupExampleInput">Example label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
                </div>
                <div class="form-group">
                    <label for="formGroupExampleInput2">Another label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
                </div>
            </form>
        </div>
    </div>
    <script src="./index.js"></script>
</body>
</html>
</code>```

Title: Reuse function to delete an item

Body:
I want to make a button that adds and removes items.
The 'Delete form' button changes to 'Add form' after click it.
But after I've deleted and added forms, I want to delete forms again, but for reasons I don't understand, it doesn't happen.

I'm using the latest chrome browser version.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Task 1</title>

<button type="button" class="btn btn-primary">Open Google</button>

<button type="button" class="btn btn-danger" id="danger">Delete form</button>

            <form id="form">

                    Example label
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

                    Another label
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

            </form>

document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
document.getElementsByClassName('btn-danger')[0].addEventListener("click", delete_function);

let inner_form = document.getElementById('form').innerHTML;

function open_google() {
    window.open('http://google.com', '_blank');
}

let buttons;

function button_change(button) {
    switch(button) {
        case "success":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Add form';
            buttons[1].className = 'btn btn-success';
            document.getElementsByClassName('btn-success')[0].addEventListener("click", add_function);
            break;
        case "danger":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Delete form';
            buttons[1].className = 'btn btn-danger';
            break;
        default:
            break;
    }
}

function delete_function() {
    let element = document.getElementById('form');
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    button_change("success");
}

function add_function() {
    document.getElementById('form').innerHTML = inner_form;
    button_change("danger");
}

Example code: https://codepen.io/anon/pen/xNjPYj

Body:
The main issue with your code was that the event listeners kept getting added but not removed, this caused them to pile up and run unpredictably. I added a function that determines what state the button is in and performs the correct function add_function or remove_function.

I also changed a few minor things

Now usesinnerHTML to textContent where possible for security

Button classes are updated using button.classList.add and button.classList.remove

The button is found using an ID instead of an unreliable classname

The button is held in a variable instead of continuing the look for it

Removed the button_change function because it was difficult to refactor

https://codepen.io/anon/pen/BexJZW

JavaScript:

document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);

let inner_form = document.getElementById('form').innerHTML;

let add_delete_button = document.querySelector('#add-delete-button');
add_delete_button.addEventListener("click", on_add_delete_clicked);

function open_google() {
    window.open('http://google.com', '_blank');
}

function on_add_delete_clicked() {
    let is_adding = add_delete_button.classList.contains("btn-success");
    if (is_adding) {
        add_function();
    } else {
        delete_function();
    }
}

function add_function() {
    const button = add_delete_button;
    document.getElementById('form').innerHTML = inner_form;

    // Update button
    button.textContent = 'Delete form';
    button.classList.remove("btn-success");
    button.classList.add("btn-danger");
}

function delete_function() {
    let element = document.getElementById('form');
    while (element.firstChild) {
        element.removeChild(element.firstChild);
    }

    // Update button
    const button = add_delete_button;
    button.textContent = 'Add form';
    button.classList.remove("btn-danger");
    button.classList.add("btn-success");
}

HTML:

<!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

  <title>Task 1</title>
</head>
<body style="height: 100%">
    <div class="container h-100">
        <div class="row h-100 justify-content-center align-content-center">
            <div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
            <div class=""><button type="button" class="btn btn-danger" id="add-delete-button">Delete form</button></div>
            <div class="breaker w-100" style="height:10%;"></div>
            <form id="form">
                <div class="form-group">
                    <label for="formGroupExampleInput">Example label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
                </div>
                <div class="form-group">
                    <label for="formGroupExampleInput2">Another label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
                </div>
            </form>
        </div>
    </div>
    <script src="./index.js"></script>
</body>
</html>


问:
Laravel Socialite InvalidStateException in AbstractProvider.php line 200
I'm building a web app in my local system (Ubuntu-14.04 64Bit) using laravel 5.3. I used Socialite to signin from social networks. I configured G+, Facebook, GitHug. I'm using Chromium as my default browser. Finally the problem is i'm getting

InvalidStateException in AbstractProvider.php line 200

frequently. i tried

php artisan cache:clear

php artisan config:clear

composer dump-autoload

these are helping to solve the issue temporarily, again the problem raising.

please help me in this issue..

答:
I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.

I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.

I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.

I had set header security in my apache2 configs. One of the settings was

```<code>Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"
</code>```

This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.

After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:

```<code>SESSION_SECURE_COOKIE=true
</code>```

in my .env file

'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)

in my config/session.php file.

Now it is back to testing security and tweaking things back if need be.

Body:
I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.

I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.

I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.

I had set header security in my apache2 configs. One of the settings was

Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"

This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.

After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:

SESSION_SECURE_COOKIE=true

in my .env file

'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)

in my config/session.php file.

Now it is back to testing security and tweaking things back if need be.


问:
Google Assistant expose incoming webhook
Is it possible to create a webhook on the google assistant that I can http post data to for it to broadcast?

I want to make a real simple application where I can send tweets from specific users to the assistant to read out loud.

答:
That is a "yes, but" question. The Actions platform allows you to send notifications to users whom you have previously queried for permission and who have consented. When they pull down the notification and tap on it, your Action runs a special intent whose name was specified at the time you ask for permission. Details are here:

https://developers.google.com/actions/assistant/updates/notifications


问:
SELECT multiple columns using mySQL prepared statement
This successfully retrieves the data from table, but this does not use a mySQL prepared statement.

```<code>$sql = "SELECT email, created_at, firstname, lastname FROM users WHERE id ='" . $_SESSION['id'] . "'";
$result = mysqli_query($link, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $email_address = $row["email"];
        $creatiom_time = $row["created_at"];
        $fname = $row["firstname"];
        $lname = $row["lastname"];
    }
}
</code>```

How can I convert this into a prepared statement as to prevent SQL injection? My attempt at converting it does not retrieve the data.

```<code>$stmt = mysqli_prepare($link, "SELECT email, created_at, firstname, lastname FROM users WHERE id=?");
$stmt->bind_param("i", $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($email_address, $creatiom_time, $fname, $lname);
$stmt->close();
</code>```

What am I doing wrong? The email is unique, so this should only return one row; however, nothing is returned when I use the above prepared statement. Thank you.

答:
You need to actually store the row data into the bound result variables with fetch:

```<code>$stmt = mysqli_prepare($link, "SELECT email, created_at, firstname, lastname FROM users WHERE id=?");
$stmt->bind_param("i", $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($email_address, $creatiom_time, $fname, $lname);
$stmt->fetch();
$stmt->close();
echo $email_address; // etc.
</code>```

Note that you really should be checking the return status from these calls, particularly the prepare, execute and fetch.

Body:
This successfully retrieves the data from table, but this does not use a mySQL prepared statement.

$sql = "SELECT email, created_at, firstname, lastname FROM users WHERE id ='" . $_SESSION['id'] . "'";
$result = mysqli_query($link, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $email_address = $row["email"];
        $creatiom_time = $row["created_at"];
        $fname = $row["firstname"];
        $lname = $row["lastname"];
    }
}

How can I convert this into a prepared statement as to prevent SQL injection? My attempt at converting it does not retrieve the data.

$stmt = mysqli_prepare($link, "SELECT email, created_at, firstname, lastname FROM users WHERE id=?");
$stmt->bind_param("i", $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($email_address, $creatiom_time, $fname, $lname);
$stmt->close();

What am I doing wrong? The email is unique, so this should only return one row; however, nothing is returned when I use the above prepared statement. Thank you.

Body:
You need to actually store the row data into the bound result variables with fetch:

$stmt = mysqli_prepare($link, "SELECT email, created_at, firstname, lastname FROM users WHERE id=?");
$stmt->bind_param("i", $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($email_address, $creatiom_time, $fname, $lname);
$stmt->fetch();
$stmt->close();
echo $email_address; // etc.

Note that you really should be checking the return status from these calls, particularly the prepare, execute and fetch.


问:
Redirect user if url matches certain conditions
I'd like the user to be redirected to a new webpage if the url contains certain conditions. I can't seem to get the OR condition to work. Any thoughts?</p>

```<code>if (
    document.location.href.indexOf("https://www.oct.ca/") > -1 &&
    document.location.href.indexOf("professionally_speaking") > -1 &&
    document.location.href.includes("2019-03" || "2018-12")
  ) {
    window.location = window.location.href.replace("https://www.oct.ca/", "http://professionallyspeaking.oct.ca/")

  }
</code>```

答:
You can't do it like that - add another condition:</p>

```<code>&& (document.location.href.includes("2019-03") || document.location.href.includes("2018-12"))
</code>```

Body:
I'd like the user to be redirected to a new webpage if the url contains certain conditions. I can't seem to get the OR condition to work. Any thoughts?

if (
    document.location.href.indexOf("https://www.oct.ca/") > -1 &&
    document.location.href.indexOf("professionally_speaking") > -1 &&
    document.location.href.includes("2019-03" || "2018-12")
  ) {
    window.location = window.location.href.replace("https://www.oct.ca/", "http://professionallyspeaking.oct.ca/")

  }

Body:
You can't do it like that - add another condition:

&& (document.location.href.includes("2019-03") || document.location.href.includes("2018-12"))


问:
java.lang.NoSuchMethodException: <init> [class android.view.View]. getting this error while trying to use button in recycleview
I am trying to make a sample app using the FirebaseRecyclerAdapter but keep getting the error java.lang.NoSuchMethodException:  [class android.view.View]

I am fetching the data from firebase real time database. I but in the recycleview, i can't use any navigation button.

Here is my Activity code:

```<code>
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.location_tracking.Users.Employee;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class AdminPanelActivity extends AppCompatActivity {

    private RecyclerView mEmployeeList;

    private DatabaseReference mEmployeeDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_panel);

        mEmployeeDatabase = FirebaseDatabase.getInstance().getReference().child("Employee");

        mEmployeeList = (RecyclerView) findViewById(R.id.recyclerViewEmplyeeList);
        mEmployeeList.setHasFixedSize(true);
        mEmployeeList.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(
                Employee.class,
                R.layout.recycle_list_single_user,
                EmployeeViewHolder.class,
                mEmployeeDatabase
        ) {
            @Override
            protected void populateViewHolder(EmployeeViewHolder viewHolder, Employee model, int position) {

                viewHolder.setName(model.getName());
                viewHolder.setEmployeeImage(model.getImage(), getApplicationContext());
                final String user_id = getRef(position).getKey();
                viewHolder.attendanceButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(AdminPanelActivity.this,AttenadnceActivity.class));
                    }
                });

            }
        };

        mEmployeeList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EmployeeViewHolder extends RecyclerView.ViewHolder {

        View mView;

        View attendanceButton;

        public EmployeeViewHolder(@NonNull View itemView,View button) {
            super(itemView);
            mView = itemView;
            attendanceButton = (Button) button.findViewById(R.id.button_attendance);
        }

        public void setName(String name) {
            TextView EmployeeNameView = mView.findViewById(R.id.textViewSingleListName);
            EmployeeNameView.setText(name);
        }

        public void setEmployeeImage(String image, Context ctx) {
            CircleImageView EmployeeImageView = (CircleImageView) mView.findViewById(R.id.circleImageViewUserImage);

            Picasso.with(ctx).load(image).placeholder(R.drawable.user_img).into(EmployeeImageView);
        }

    }

}
</code>```

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.firebaseui:firebase-ui-database:1.2.0'

    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    implementation 'id.zelory:compressor:2.1.0'

    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'org.greenrobot:eventbus:3.0.0'

    implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
    implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

</code>```

My XMl code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ccc"
    android:layout_margin="5dp"
    android:padding="10dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/circleImageViewUserImage"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginTop="16dp"
        android:src="@drawable/user_img"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textViewSingleListName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:text="Employee Name"
        android:textColor="#000000"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/circleImageViewUserImage"
        app:layout_constraintTop_toTopOf="@+id/circleImageViewUserImage" />

    <Button
        android:id="@+id/button_attendance"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="228dp"
        android:layout_marginTop="44dp"
        android:background="@color/red"
        android:padding="7dp"
        android:text="Attendence"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="72dp"
        android:layout_marginTop="44dp"
        android:background="@color/colorButton"
        android:padding="7dp"
        android:text="Show location"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Recycleview

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AdminPanelActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerViewEmplyeeList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5sp">
    </android.support.v7.widget.RecyclerView>

</LinearLayout>
</code>```

the ERROR:

```<code>    Process: com.example.location_tracking, PID: 8939
    java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:171)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
     Caused by: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at java.lang.Class.getConstructor0(Class.java:2320)
        at java.lang.Class.getConstructor(Class.java:1725)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:168)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
2019-05-26 07:08:46.529 8939-8949/com.example.location_tracking I/zygote64: Do partial code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: After code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: Increasing code cache capacity to 128KB
2019-05-26 07:08:46.619 8939-8939/com.example.location_tracking I/Process: Sending signal. PID: 8939 SIG: 9
</code>```

答:
Most likely your custom ViewHolder subclass is:

missing a constructor public MyViewHolder(View itemView) {... }

you should get your button this way :

```<code>attendanceButton = (Button) itemView.findViewById(R.id.button_attendance);
</code>```

instead of this :

```<code>attendanceButton = (Button) button.findViewById(R.id.button_attendance);
</code>```

Body:
I am trying to make a sample app using the FirebaseRecyclerAdapter but keep getting the error java.lang.NoSuchMethodException:  [class android.view.View]

I am fetching the data from firebase real time database. I but in the recycleview, i can't use any navigation button.

Here is my Activity code:

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.location_tracking.Users.Employee;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class AdminPanelActivity extends AppCompatActivity {

    private RecyclerView mEmployeeList;

    private DatabaseReference mEmployeeDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_panel);

        mEmployeeDatabase = FirebaseDatabase.getInstance().getReference().child("Employee");

        mEmployeeList = (RecyclerView) findViewById(R.id.recyclerViewEmplyeeList);
        mEmployeeList.setHasFixedSize(true);
        mEmployeeList.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(
                Employee.class,
                R.layout.recycle_list_single_user,
                EmployeeViewHolder.class,
                mEmployeeDatabase
        ) {
            @Override
            protected void populateViewHolder(EmployeeViewHolder viewHolder, Employee model, int position) {

                viewHolder.setName(model.getName());
                viewHolder.setEmployeeImage(model.getImage(), getApplicationContext());
                final String user_id = getRef(position).getKey();
                viewHolder.attendanceButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(AdminPanelActivity.this,AttenadnceActivity.class));
                    }
                });

            }
        };

        mEmployeeList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EmployeeViewHolder extends RecyclerView.ViewHolder {

        View mView;

        View attendanceButton;

        public EmployeeViewHolder(@NonNull View itemView,View button) {
            super(itemView);
            mView = itemView;
            attendanceButton = (Button) button.findViewById(R.id.button_attendance);
        }

        public void setName(String name) {
            TextView EmployeeNameView = mView.findViewById(R.id.textViewSingleListName);
            EmployeeNameView.setText(name);
        }

        public void setEmployeeImage(String image, Context ctx) {
            CircleImageView EmployeeImageView = (CircleImageView) mView.findViewById(R.id.circleImageViewUserImage);

            Picasso.with(ctx).load(image).placeholder(R.drawable.user_img).into(EmployeeImageView);
        }

    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.firebaseui:firebase-ui-database:1.2.0'

    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    implementation 'id.zelory:compressor:2.1.0'

    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'org.greenrobot:eventbus:3.0.0'

    implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
    implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

My XMl code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ccc"
    android:layout_margin="5dp"
    android:padding="10dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/circleImageViewUserImage"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginTop="16dp"
        android:src="@drawable/user_img"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textViewSingleListName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:text="Employee Name"
        android:textColor="#000000"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/circleImageViewUserImage"
        app:layout_constraintTop_toTopOf="@+id/circleImageViewUserImage" />

    <Button
        android:id="@+id/button_attendance"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="228dp"
        android:layout_marginTop="44dp"
        android:background="@color/red"
        android:padding="7dp"
        android:text="Attendence"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="72dp"
        android:layout_marginTop="44dp"
        android:background="@color/colorButton"
        android:padding="7dp"
        android:text="Show location"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Recycleview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AdminPanelActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerViewEmplyeeList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5sp">
    </android.support.v7.widget.RecyclerView>

</LinearLayout>

the ERROR:

    Process: com.example.location_tracking, PID: 8939
    java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:171)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
     Caused by: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at java.lang.Class.getConstructor0(Class.java:2320)
        at java.lang.Class.getConstructor(Class.java:1725)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:168)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
2019-05-26 07:08:46.529 8939-8949/com.example.location_tracking I/zygote64: Do partial code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: After code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: Increasing code cache capacity to 128KB
2019-05-26 07:08:46.619 8939-8939/com.example.location_tracking I/Process: Sending signal. PID: 8939 SIG: 9

Body:
Most likely your custom ViewHolder subclass is:

missing a constructor public MyViewHolder(View itemView) {... }

you should get your button this way :

attendanceButton = (Button) itemView.findViewById(R.id.button_attendance);

instead of this :

attendanceButton = (Button) button.findViewById(R.id.button_attendance);