问:
Display laravel retrun result in html table using jquery- Ajax
In Laravel Blade I have a script for searching

```<code> <script type="text/javascript">
    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        url: "{{ URL::asset('upload-panel/search')}}",
        data: dataString,
        dataType:"JSON",
        cache: false,
        success: function(result) {
        var FinalResult=result.CallDetails
        num_rows = result.length;
        console.log(result)

        },error:function(x,e) {
            setTimeout(function() {searchPhoneCalls();}, 2000);
        }
    })
</script>
</code>```

search function in controller returns is below

return  json_encode($users);

In console am getting the result as an array like below

```<code>0: {Short_name: "GO120762", Date: "21-01-2020"}
1: {Short_name: "GO120764", Date: "21-01-2020"}
2: {Short_name: "GO120766", Date: "21-01-2020"}
</code>```

I want to display those result in a HTML  table  like below

```<code>+----------+------------+
| Name     | Date       |
+----------+------------+
| GO120762 | 21-01-2020 |
+----------+------------+
| GO120764 | 21-01-2020 |
+----------+------------+
| GO120766 | 21-01-2020 |
+----------+------------+

</code>```

答:
In your blade:

```<code><table>
    <thead>
        <th>Name</th>
        <th>Date</th>
    </thead>
    <tbody class="tbody">

    </tbody>
</table>
</code>```

IN ajax script:

```<code>success: function(result) {
    var FinalResult=result.CallDetails
    num_rows = result.length;
    console.log(result)

    $.each(FinalResult, function(index, value){
        $('tbody').append('<tr><td>'+value.Short_name+'</td><td>'+value.Date+'</td></tr>');
    });

 }
</code>```

Body:
In Laravel Blade I have a script for searching

search function in controller returns is below

return  json_encode($users);

In console am getting the result as an array like below

0: {Short_name: "GO120762", Date: "21-01-2020"}
1: {Short_name: "GO120764", Date: "21-01-2020"}
2: {Short_name: "GO120766", Date: "21-01-2020"}

I want to display those result in a HTML  table  like below

+----------+------------+
| Name     | Date       |
+----------+------------+
| GO120762 | 21-01-2020 |
+----------+------------+
| GO120764 | 21-01-2020 |
+----------+------------+
| GO120766 | 21-01-2020 |
+----------+------------+

Body:
In your blade:

<table>
    <thead>
        <th>Name</th>
        <th>Date</th>
    </thead>
    <tbody class="tbody">

    </tbody>
</table>

IN ajax script:

success: function(result) {
    var FinalResult=result.CallDetails
    num_rows = result.length;
    console.log(result)

    $.each(FinalResult, function(index, value){
        $('tbody').append('<tr><td>'+value.Short_name+'</td><td>'+value.Date+'</td></tr>');
    });

 }


来源: stackexchange

问:
react-router (v4) how to go back?
Trying to figure out how can I go back to the previous page. I am using [react-router-v4][1]

This is the code I have configured in my first landing page:

```<code><Router>
  <div>
    <Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
    <Route exact path="/" component={Page1}/>
    <Route path="/Page2" component={Page2}/>
    <Route path="/Page3" component={Page3}/>
  </div>
</Router>
</code>```

In order to forward to subsequent pages, I simply do:

```<code>this.props.history.push('/Page2');
</code>```

However, how can I go back to previous page?
Tried few things like mentioned below but no luck:
1. this.props.history.goBack();

Gives error:

TypeError: null is not an object (evaluating 'this.props')

this.context.router.goBack();

Gives error:

TypeError: null is not an object (evaluating 'this.context')

this.props.history.push('/');

Gives error:

TypeError: null is not an object (evaluating 'this.props')

Posting the Page1 code here below:

```<code>import React, {Component} from 'react';
import {Button} from 'react-bootstrap';

class Page1 extends Component {
  constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
  }

  handleNext() {
    this.props.history.push('/page2');
  }

  handleBack() {
    this.props.history.push('/');
  }

  /*
   * Main render method of this class
   */
  render() {
    return (
      <div>
        {/* some component code */}

        <div className="navigationButtonsLeft">
          <Button onClick={this.handleBack} bsStyle="success">< Back</Button>
        </div>
        <div className="navigationButtonsRight">
          <Button onClick={this.handleNext} bsStyle="success">Next ></Button>
        </div>

      </div>
    );
  }

export default Page1;
</code>```

答:
Here is the cleanest and simplest way you can handle this problem, which also nullifies the probable pitfalls of the this keyword. Use functional components:

import { withRouter } from "react-router-dom";
wrap your component or better App.js with the withRouter() HOC this makes history to be available "app-wide". wrapping your component only makes history available for that specific component``` your choice.</p>
<p>So you have:</p>
<ol>
<li><p><code>export default withRouter(App);</code></p>
</li>
<li><p>In a Redux environment <code> export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), );</code> you should even be able to user <code>history</code> from your action creators this way.</p>
</li>
</ol>
<p>in your <code>component</code> do the following:</p>
<p><code>import {useHistory} from "react-router-dom";</code></p>
<p><code>const history = useHistory();  // do this inside the component</code></p>
<p><code>goBack = () => history.goBack();</code></p>
<p><code><btn btn-sm btn-primary onclick={goBack}>Go Back</btn></code></p>
<p><code>export default DemoComponent;</code></p>
<p>Gottcha <code>useHistory</code> is only exported from the latest v5.1 <code>react-router-dom</code> so be sure to update the package. However, you should not have to worry.
about the many snags of the <code>this keyword</code>.</p>
<p>You can also make this a reusable component to use across your app.</p>
```
function BackButton({ children }) {
  let history = useHistory()
  return (
    <button type="button" onClick={() => history.goBack()}>
      {children}
    </button>
  )
}```
Cheers.

</code>```

ContentLicense: CC BY-SA 3.0

Title: react-router (v4) how to go back?

Body:
Trying to figure out how can I go back to the previous page. I am using [react-router-v4][1]

This is the code I have configured in my first landing page:

<Router>

    <Link to="/">
<Glyphicon glyph="home" />
</Link>
    <Route exact path="/" component={Page1}/>
    <Route path="/Page2" component={Page2}/>
    <Route path="/Page3" component={Page3}/>

</Router>

In order to forward to subsequent pages, I simply do:

this.props.history.push('/Page2');

However, how can I go back to previous page?
Tried few things like mentioned below but no luck:
1. this.props.history.goBack();

Gives error:

TypeError: null is not an object (evaluating 'this.props')

this.context.router.goBack();

Gives error:

TypeError: null is not an object (evaluating 'this.context')

this.props.history.push('/');

Gives error:

TypeError: null is not an object (evaluating 'this.props')

Posting the Page1 code here below:

import React, {Component} from 'react';
import {Button} from 'react-bootstrap';

class Page1 extends Component {
  constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
  }

  handleNext() {
    this.props.history.push('/page2');
  }

  handleBack() {
    this.props.history.push('/');
  }

  /*
   * Main render method of this class
   */
  render() {
    return (

        {/* some component code */}

          <Button onClick={this.handleBack} bsStyle="success">< Back</Button>

          <Button onClick={this.handleNext} bsStyle="success">Next ></Button>

    );
  }

export default Page1;

Body:
Here is the cleanest and simplest way you can handle this problem, which also nullifies the probable pitfalls of the this keyword. Use functional components:

import { withRouter } from "react-router-dom";
wrap your component or better App.js with the withRouter() HOC this makes history to be available "app-wide". wrapping your component only makes history available for that specific component``` your choice.</p>
<p>So you have:</p>
<ol>
<li><p><code>export default withRouter(App);</code></p>
</li>
<li><p>In a Redux environment <code> export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), );</code> you should even be able to user <code>history</code> from your action creators this way.</p>
</li>
</ol>
<p>in your <code>component</code> do the following:</p>
<p><code>import {useHistory} from "react-router-dom";</code></p>
<p><code>const history = useHistory();  // do this inside the component</code></p>
<p><code>goBack = () => history.goBack();</code></p>
<p><code><btn btn-sm btn-primary onclick={goBack}>Go Back</btn></code></p>
<p><code>export default DemoComponent;</code></p>
<p>Gottcha <code>useHistory</code> is only exported from the latest v5.1 <code>react-router-dom</code> so be sure to update the package. However, you should not have to worry.
about the many snags of the <code>this keyword</code>.</p>
<p>You can also make this a reusable component to use across your app.</p>
<pre><code>
function BackButton({ children }) {
  let history = useHistory()
  return (
    <button type="button" onClick={() => history.goBack()}>
      {children}
    </button>
  )
}```
Cheers.

ContentLicense: CC BY-SA 4.0


问:
Remove array item if it has a duplicate id
I have an array with the following values:

```<code>expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}
</code>```

I want to filter out any array items with a duplicate componentId.

```<code>this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }
</code>```

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?

答:
Try using set.

function removeDuplicates() {

            // Create an array of objects
            books = [
                { title: "C++", author: "Bjarne" },
                { title: "Java", author: "James" },
                { title: "Python", author: "Guido" },
                { title: "Java", author: "James" },
            ];

            jsonObject = books.map(JSON.stringify);

            console.log(jsonObject);

            uniqueSet = new Set(jsonObject);
            uniqueArray = Array.from(uniqueSet).map(JSON.parse);

            console.log(uniqueArray);
        } ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="removeDuplicates()">
        Click here
    </button> </code>```

Body:
I have an array with the following values:

expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}

I want to filter out any array items with a duplicate componentId.

this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?

Body:
Try using set.

function removeDuplicates() {

            // Create an array of objects
            books = [
                { title: "C++", author: "Bjarne" },
                { title: "Java", author: "James" },
                { title: "Python", author: "Guido" },
                { title: "Java", author: "James" },
            ];

            jsonObject = books.map(JSON.stringify);

            console.log(jsonObject);

            uniqueSet = new Set(jsonObject);
            uniqueArray = Array.from(uniqueSet).map(JSON.parse);

            console.log(uniqueArray);
        }

<button onclick="removeDuplicates()">
        Click here
    </button>


问:
How do I perform an IF...THEN in an SQL SELECT?
How do I perform an IF...THEN in an SQL SELECT statement?

For example:

```<code>SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
</code>```

答:
Using SQL CASE is just like normal If / Else statements.
In the below query, if obsolete value = 'N' or if InStock value = 'Y' then the output will be 1. Otherwise the output will be 0.
Then we put that 0 or 1 value under the Salable Column.</p>
```<code>SELECT
      CASE
           WHEN obsolete = 'N' OR InStock = 'Y'
          THEN 1
        ELSE 0
      END AS Salable
      , *
FROM PRODUCT
</code>```

OwnerDisplayName: Eric Labashosky

Body:
How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

Body:
Using SQL CASE is just like normal If / Else statements.
In the below query, if obsolete value = 'N' or if InStock value = 'Y' then the output will be 1. Otherwise the output will be 0.
Then we put that 0 or 1 value under the Salable Column.

SELECT
      CASE
           WHEN obsolete = 'N' OR InStock = 'Y'
          THEN 1
        ELSE 0
      END AS Salable
      , *
FROM PRODUCT


问:
How to implement draggable tab using Java Swing?
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.

EDIT: The Java Tutorials - Drag and Drop and Data Transfer.

答:
Found this code out there on the tubes:</p>

```<code>class DnDTabbedPane extends JTabbedPane {
  private static final int LINEWIDTH = 3;
  private static final String NAME = "test";
  private final GhostGlassPane glassPane = new GhostGlassPane();
  private final Rectangle2D lineRect   = new Rectangle2D.Double();
  private final Color     lineColor  = new Color(0, 100, 255);
  //private final DragSource dragSource  = new DragSource();
  //private final DropTarget dropTarget;
  private int dragTabIndex = -1;

  public DnDTabbedPane() {
    super();
    final DragSourceListener dsl = new DragSourceListener() {
      public void dragEnter(DragSourceDragEvent e) {
        e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
      }
      public void dragExit(DragSourceEvent e) {
        e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
        lineRect.setRect(0,0,0,0);
        glassPane.setPoint(new Point(-1000,-1000));
        glassPane.repaint();
      }
      public void dragOver(DragSourceDragEvent e) {
        //e.getLocation()
        //This method returns a Point indicating the cursor location in screen coordinates at the moment
        Point tabPt = e.getLocation();
        SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
        Point glassPt = e.getLocation();
        SwingUtilities.convertPointFromScreen(glassPt, glassPane);
        int targetIdx = getTargetTabIndex(glassPt);
        if(getTabAreaBound().contains(tabPt) && targetIdx>=0 &&
           targetIdx!=dragTabIndex && targetIdx!=dragTabIndex+1) {
          e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
        }else{
          e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
        }
      }
      public void dragDropEnd(DragSourceDropEvent e) {
        lineRect.setRect(0,0,0,0);
        dragTabIndex = -1;
        if(hasGhost()) {
          glassPane.setVisible(false);
          glassPane.setImage(null);
        }
      }
      public void dropActionChanged(DragSourceDragEvent e) {}
    };
    final Transferable t = new Transferable() {
      private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);
      public Object getTransferData(DataFlavor flavor) {
        return DnDTabbedPane.this;
      }
      public DataFlavor[] getTransferDataFlavors() {
        DataFlavor[] f = new DataFlavor[1];
        f[0] = this.FLAVOR;
        return f;
      }
      public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavor.getHumanPresentableName().equals(NAME);
      }
    };
    final DragGestureListener dgl = new DragGestureListener() {
      public void dragGestureRecognized(DragGestureEvent e) {
        Point tabPt = e.getDragOrigin();
        dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
        if(dragTabIndex<0) return;
        initGlassPane(e.getComponent(), e.getDragOrigin());
        try{
          e.startDrag(DragSource.DefaultMoveDrop, t, dsl);
        }catch(InvalidDnDOperationException idoe) {
          idoe.printStackTrace();
        }
      }
    };
    //dropTarget =
    new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);
    new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);
  }

  class CDropTargetListener implements DropTargetListener{
    public void dragEnter(DropTargetDragEvent e) {
      if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());
      else e.rejectDrag();
    }
    public void dragExit(DropTargetEvent e) {}
    public void dropActionChanged(DropTargetDragEvent e) {}
    public void dragOver(final DropTargetDragEvent e) {
      if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {
        initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));
      }else{
        initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));
      }
      repaint();
      if(hasGhost()) {
        glassPane.setPoint(e.getLocation());
        glassPane.repaint();
      }
    }

    public void drop(DropTargetDropEvent e) {
      if(isDropAcceptable(e)) {
        convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));
        e.dropComplete(true);
      }else{
        e.dropComplete(false);
      }
      repaint();
    }
    public boolean isDragAcceptable(DropTargetDragEvent e) {
      Transferable t = e.getTransferable();
      if(t==null) return false;
      DataFlavor[] f = e.getCurrentDataFlavors();
      if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
        return true;
      }
      return false;
    }
    public boolean isDropAcceptable(DropTargetDropEvent e) {
      Transferable t = e.getTransferable();
      if(t==null) return false;
      DataFlavor[] f = t.getTransferDataFlavors();
      if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
        return true;
      }
      return false;
    }
  }

  private boolean hasGhost = true;
  public void setPaintGhost(boolean flag) {
    hasGhost = flag;
  }
  public boolean hasGhost() {
    return hasGhost;
  }
  private int getTargetTabIndex(Point glassPt) {
    Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);
    boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;
    for(int i=0;i<getTabCount();i++) {
      Rectangle r = getBoundsAt(i);
      if(isTB) r.setRect(r.x-r.width/2, r.y,  r.width, r.height);
      else   r.setRect(r.x, r.y-r.height/2, r.width, r.height);
      if(r.contains(tabPt)) return i;
    }
    Rectangle r = getBoundsAt(getTabCount()-1);
    if(isTB) r.setRect(r.x+r.width/2, r.y,  r.width, r.height);
    else   r.setRect(r.x, r.y+r.height/2, r.width, r.height);
    return   r.contains(tabPt)?getTabCount():-1;
  }
  private void convertTab(int prev, int next) {
    if(next<0 || prev==next) {
      //System.out.println("press="+prev+" next="+next);
      return;
    }
    Component cmp = getComponentAt(prev);
    String str = getTitleAt(prev);
    if(next==getTabCount()) {
      //System.out.println("last: press="+prev+" next="+next);
      remove(prev);
      addTab(str, cmp);
      setSelectedIndex(getTabCount()-1);
    }else if(prev>next) {
      //System.out.println("   >: press="+prev+" next="+next);
      remove(prev);
      insertTab(str, null, cmp, null, next);
      setSelectedIndex(next);
    }else{
      //System.out.println("   <: press="+prev+" next="+next);
      remove(prev);
      insertTab(str, null, cmp, null, next-1);
      setSelectedIndex(next-1);
    }
  }

  private void initTargetLeftRightLine(int next) {
    if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
      lineRect.setRect(0,0,0,0);
    }else if(next==getTabCount()) {
      Rectangle rect = getBoundsAt(getTabCount()-1);
      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }else if(next==0) {
      Rectangle rect = getBoundsAt(0);
      lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }else{
      Rectangle rect = getBoundsAt(next-1);
      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }
  }
  private void initTargetTopBottomLine(int next) {
    if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
      lineRect.setRect(0,0,0,0);
    }else if(next==getTabCount()) {
      Rectangle rect = getBoundsAt(getTabCount()-1);
      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
    }else if(next==0) {
      Rectangle rect = getBoundsAt(0);
      lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);
    }else{
      Rectangle rect = getBoundsAt(next-1);
      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
    }
  }

  private void initGlassPane(Component c, Point tabPt) {
    //Point p = (Point) pt.clone();
    getRootPane().setGlassPane(glassPane);
    if(hasGhost()) {
      Rectangle rect = getBoundsAt(dragTabIndex);
      BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
      Graphics g = image.getGraphics();
      c.paint(g);
      image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);
      glassPane.setImage(image);
    }
    Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);
    glassPane.setPoint(glassPt);
    glassPane.setVisible(true);
  }

  private Rectangle getTabAreaBound() {
    Rectangle lastTab  = getUI().getTabBounds(this, getTabCount()-1);
    return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if(dragTabIndex>=0) {
      Graphics2D g2 = (Graphics2D)g;
      g2.setPaint(lineColor);
      g2.fill(lineRect);
    }
  }
}

class GhostGlassPane extends JPanel {
  private final AlphaComposite composite;
  private Point location = new Point(0, 0);
  private BufferedImage draggingGhost = null;
  public GhostGlassPane() {
    setOpaque(false);
    composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
  }
  public void setImage(BufferedImage draggingGhost) {
    this.draggingGhost = draggingGhost;
  }
  public void setPoint(Point location) {
    this.location = location;
  }
  public void paintComponent(Graphics g) {
    if(draggingGhost == null) return;
    Graphics2D g2 = (Graphics2D) g;
    g2.setComposite(composite);
    double xx = location.getX() - (draggingGhost.getWidth(this) /2d);
    double yy = location.getY() - (draggingGhost.getHeight(this)/2d);
    g2.drawImage(draggingGhost, (int)xx, (int)yy , null);
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Found this code out there on the tubes:

class DnDTabbedPane extends JTabbedPane {
  private static final int LINEWIDTH = 3;
  private static final String NAME = "test";
  private final GhostGlassPane glassPane = new GhostGlassPane();
  private final Rectangle2D lineRect   = new Rectangle2D.Double();
  private final Color     lineColor  = new Color(0, 100, 255);
  //private final DragSource dragSource  = new DragSource();
  //private final DropTarget dropTarget;
  private int dragTabIndex = -1;

  public DnDTabbedPane() {
    super();
    final DragSourceListener dsl = new DragSourceListener() {
      public void dragEnter(DragSourceDragEvent e) {
        e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
      }
      public void dragExit(DragSourceEvent e) {
        e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
        lineRect.setRect(0,0,0,0);
        glassPane.setPoint(new Point(-1000,-1000));
        glassPane.repaint();
      }
      public void dragOver(DragSourceDragEvent e) {
        //e.getLocation()
        //This method returns a Point indicating the cursor location in screen coordinates at the moment
        Point tabPt = e.getLocation();
        SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
        Point glassPt = e.getLocation();
        SwingUtilities.convertPointFromScreen(glassPt, glassPane);
        int targetIdx = getTargetTabIndex(glassPt);
        if(getTabAreaBound().contains(tabPt) && targetIdx>=0 &&
           targetIdx!=dragTabIndex && targetIdx!=dragTabIndex+1) {
          e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
        }else{
          e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
        }
      }
      public void dragDropEnd(DragSourceDropEvent e) {
        lineRect.setRect(0,0,0,0);
        dragTabIndex = -1;
        if(hasGhost()) {
          glassPane.setVisible(false);
          glassPane.setImage(null);
        }
      }
      public void dropActionChanged(DragSourceDragEvent e) {}
    };
    final Transferable t = new Transferable() {
      private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);
      public Object getTransferData(DataFlavor flavor) {
        return DnDTabbedPane.this;
      }
      public DataFlavor[] getTransferDataFlavors() {
        DataFlavor[] f = new DataFlavor[1];
        f[0] = this.FLAVOR;
        return f;
      }
      public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavor.getHumanPresentableName().equals(NAME);
      }
    };
    final DragGestureListener dgl = new DragGestureListener() {
      public void dragGestureRecognized(DragGestureEvent e) {
        Point tabPt = e.getDragOrigin();
        dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
        if(dragTabIndex<0) return;
        initGlassPane(e.getComponent(), e.getDragOrigin());
        try{
          e.startDrag(DragSource.DefaultMoveDrop, t, dsl);
        }catch(InvalidDnDOperationException idoe) {
          idoe.printStackTrace();
        }
      }
    };
    //dropTarget =
    new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);
    new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);
  }

  class CDropTargetListener implements DropTargetListener{
    public void dragEnter(DropTargetDragEvent e) {
      if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());
      else e.rejectDrag();
    }
    public void dragExit(DropTargetEvent e) {}
    public void dropActionChanged(DropTargetDragEvent e) {}
    public void dragOver(final DropTargetDragEvent e) {
      if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {
        initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));
      }else{
        initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));
      }
      repaint();
      if(hasGhost()) {
        glassPane.setPoint(e.getLocation());
        glassPane.repaint();
      }
    }

    public void drop(DropTargetDropEvent e) {
      if(isDropAcceptable(e)) {
        convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));
        e.dropComplete(true);
      }else{
        e.dropComplete(false);
      }
      repaint();
    }
    public boolean isDragAcceptable(DropTargetDragEvent e) {
      Transferable t = e.getTransferable();
      if(t==null) return false;
      DataFlavor[] f = e.getCurrentDataFlavors();
      if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
        return true;
      }
      return false;
    }
    public boolean isDropAcceptable(DropTargetDropEvent e) {
      Transferable t = e.getTransferable();
      if(t==null) return false;
      DataFlavor[] f = t.getTransferDataFlavors();
      if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
        return true;
      }
      return false;
    }
  }

  private boolean hasGhost = true;
  public void setPaintGhost(boolean flag) {
    hasGhost = flag;
  }
  public boolean hasGhost() {
    return hasGhost;
  }
  private int getTargetTabIndex(Point glassPt) {
    Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);
    boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;
    for(int i=0;i<getTabCount();i++) {
      Rectangle r = getBoundsAt(i);
      if(isTB) r.setRect(r.x-r.width/2, r.y,  r.width, r.height);
      else   r.setRect(r.x, r.y-r.height/2, r.width, r.height);
      if(r.contains(tabPt)) return i;
    }
    Rectangle r = getBoundsAt(getTabCount()-1);
    if(isTB) r.setRect(r.x+r.width/2, r.y,  r.width, r.height);
    else   r.setRect(r.x, r.y+r.height/2, r.width, r.height);
    return   r.contains(tabPt)?getTabCount():-1;
  }
  private void convertTab(int prev, int next) {
    if(next<0 || prev==next) {
      //System.out.println("press="+prev+" next="+next);
      return;
    }
    Component cmp = getComponentAt(prev);
    String str = getTitleAt(prev);
    if(next==getTabCount()) {
      //System.out.println("last: press="+prev+" next="+next);
      remove(prev);
      addTab(str, cmp);
      setSelectedIndex(getTabCount()-1);
    }else if(prev>next) {
      //System.out.println("   >: press="+prev+" next="+next);
      remove(prev);
      insertTab(str, null, cmp, null, next);
      setSelectedIndex(next);
    }else{
      //System.out.println("   <: press="+prev+" next="+next);
      remove(prev);
      insertTab(str, null, cmp, null, next-1);
      setSelectedIndex(next-1);
    }
  }

  private void initTargetLeftRightLine(int next) {
    if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
      lineRect.setRect(0,0,0,0);
    }else if(next==getTabCount()) {
      Rectangle rect = getBoundsAt(getTabCount()-1);
      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }else if(next==0) {
      Rectangle rect = getBoundsAt(0);
      lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }else{
      Rectangle rect = getBoundsAt(next-1);
      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }
  }
  private void initTargetTopBottomLine(int next) {
    if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
      lineRect.setRect(0,0,0,0);
    }else if(next==getTabCount()) {
      Rectangle rect = getBoundsAt(getTabCount()-1);
      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
    }else if(next==0) {
      Rectangle rect = getBoundsAt(0);
      lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);
    }else{
      Rectangle rect = getBoundsAt(next-1);
      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
    }
  }

  private void initGlassPane(Component c, Point tabPt) {
    //Point p = (Point) pt.clone();
    getRootPane().setGlassPane(glassPane);
    if(hasGhost()) {
      Rectangle rect = getBoundsAt(dragTabIndex);
      BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
      Graphics g = image.getGraphics();
      c.paint(g);
      image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);
      glassPane.setImage(image);
    }
    Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);
    glassPane.setPoint(glassPt);
    glassPane.setVisible(true);
  }

  private Rectangle getTabAreaBound() {
    Rectangle lastTab  = getUI().getTabBounds(this, getTabCount()-1);
    return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if(dragTabIndex>=0) {
      Graphics2D g2 = (Graphics2D)g;
      g2.setPaint(lineColor);
      g2.fill(lineRect);
    }
  }
}

class GhostGlassPane extends JPanel {
  private final AlphaComposite composite;
  private Point location = new Point(0, 0);
  private BufferedImage draggingGhost = null;
  public GhostGlassPane() {
    setOpaque(false);
    composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
  }
  public void setImage(BufferedImage draggingGhost) {
    this.draggingGhost = draggingGhost;
  }
  public void setPoint(Point location) {
    this.location = location;
  }
  public void paintComponent(Graphics g) {
    if(draggingGhost == null) return;
    Graphics2D g2 = (Graphics2D) g;
    g2.setComposite(composite);
    double xx = location.getX() - (draggingGhost.getWidth(this) /2d);
    double yy = location.getY() - (draggingGhost.getHeight(this)/2d);
    g2.drawImage(draggingGhost, (int)xx, (int)yy , null);
  }
}

OwnerDisplayName: jodonnell


问:
A better way to submit a form for Django
This is what I am doing at the moment:

views.py

```<code>def activation_signupcount(request):

    if request.method == 'POST':

        return render_to_response('activation_signupcount.html',
                                {   'datestart': request.POST['datestart'],
                                    'dateend': request.POST['dateend'],
                                    'usersegment': request.POST['usersegment'],
                                    'segment_form': SegmentForm(request.POST),
                                    'date_form': DateSelectForm(request.POST)    })
    else:

        return render_to_response('activation_signupcount.html',
                                {'segment_form': SegmentForm(), 'date_form': DateSelectForm()})
</code>```

template

```<code>{% extends "base_activation.html" %}

{% block content %}
    <h2>Sign ups</h2>
    <p>Number of users who have registered to the site between the dates entered</p>
{% endblock %}

{% block graph %}
    {% if datestart %}
    <p>This counts the number of <strong>{{ usersegment }}</strong> users who have successfully registered to the site (verified their email)
    who joined between <strong>{{ datestart }}</strong> and <strong>{{ dateend }}</strong></p>
    <img src="./activation_signupcount.png?usersegment={{ usersegment }}&datestart={{ datestart }}&dateend={{ dateend }}" />
    {% endif %}
{% endblock %}
</code>```

So I am returning the same page when a user submits the SegmentForm and DateSelectForms. To check if I should return the output (a graph), I am checking for the existence of datestart as seen in my template {% if datestart %} if it was submitted.

Is this a Djangoic way of doing it? I feel I ought to be checking for response == 'POST' rather than forcing the check variable to datestart.

Thanks

答:
That's the most strange way to submit a form I've ever seen. :-) First of all, you pass segment_form and date_form to your template but don't use them at all. Why? Second, you have no validation, what if datestart will be 'adhbsadfbsrbv'? Or some XSS statement? Third, what if there will be no datestart in POST at all? You will get KeyError.

May be you should read the docs first. Your code can be rewritten somehow like this (even simplier edited version):

```<code>def activation_signupcount(request):
    return render_to_response('activation_signupcount.html',
                          {'segment_form': SegmentForm(request.POST or None), 'date_form': DateSelectForm(request.POST or None)})
</code>```

And in template you can access the variables like {{ date_form.cleaned_data.datestart }} And don't forget to use escape filter when outputting urls.

Body:
This is what I am doing at the moment:

views.py

def activation_signupcount(request):

    if request.method == 'POST':

        return render_to_response('activation_signupcount.html',
                                {   'datestart': request.POST['datestart'],
                                    'dateend': request.POST['dateend'],
                                    'usersegment': request.POST['usersegment'],
                                    'segment_form': SegmentForm(request.POST),
                                    'date_form': DateSelectForm(request.POST)    })
    else:

        return render_to_response('activation_signupcount.html',
                                {'segment_form': SegmentForm(), 'date_form': DateSelectForm()})

template

{% extends "base_activation.html" %}

{% block content %}

Sign ups

Number of users who have registered to the site between the dates entered

{% endblock %}

{% block graph %}
    {% if datestart %}

This counts the number of {{ usersegment }} users who have successfully registered to the site (verified their email)
    who joined between {{ datestart }} and {{ dateend }}

    {% endif %}
{% endblock %}

So I am returning the same page when a user submits the SegmentForm and DateSelectForms. To check if I should return the output (a graph), I am checking for the existence of datestart as seen in my template {% if datestart %} if it was submitted.

Is this a Djangoic way of doing it? I feel I ought to be checking for response == 'POST' rather than forcing the check variable to datestart.

Thanks

Body:
That's the most strange way to submit a form I've ever seen. :-) First of all, you pass segment_form and date_form to your template but don't use them at all. Why? Second, you have no validation, what if datestart will be 'adhbsadfbsrbv'? Or some XSS statement? Third, what if there will be no datestart in POST at all? You will get KeyError.

May be you should read the docs first. Your code can be rewritten somehow like this (even simplier edited version):

def activation_signupcount(request):
    return render_to_response('activation_signupcount.html',
                          {'segment_form': SegmentForm(request.POST or None), 'date_form': DateSelectForm(request.POST or None)})

And in template you can access the variables like {{ date_form.cleaned_data.datestart }} And don't forget to use escape filter when outputting urls.


问:
ListView items gone off screen

The problem is when I run the program the view cuts like what shown in the picture above
I don't know what the exact sort of problem, so if you need anything to show just ask
I am using kotlin by the way

EDIT 1:
result_row.xml this is the XML for the row that shows in the ListView

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/itemName"
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Name"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView2"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemWeight"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Item Weight"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView1"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemPrice"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Price"
            android:textColor="#000000"
            android:textSize="16sp" />

    </LinearLayout>

</FrameLayout>
</code>```

答:
Your TextViews have fixed widths that total greater than the width of the screen:

```<code>android:layout_width="200dp"
...
android:layout_width="100dp"
...
android:layout_width="100dp"
</code>```

Android phones can be as narrow as 320dp, so it'll get cut off.  You need to modify your layout to use the available space, not hardcode fixed widths.  Or, if you really want to use fixed widths, they need to be smaller (shouldn't add up to more than 320dp).

Title: ListView items gone off screen

Body:
The problem is when I run the program the view cuts like what shown in the picture above
I don't know what the exact sort of problem, so if you need anything to show just ask
I am using kotlin by the way

EDIT 1:
result_row.xml this is the XML for the row that shows in the ListView

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/itemName"
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Name"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView2"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemWeight"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Item Weight"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView1"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemPrice"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Price"
            android:textColor="#000000"
            android:textSize="16sp" />

    </LinearLayout>

</FrameLayout>

Body:
Your TextViews have fixed widths that total greater than the width of the screen:

android:layout_width="200dp"
...
android:layout_width="100dp"
...
android:layout_width="100dp"

Android phones can be as narrow as 320dp, so it'll get cut off.  You need to modify your layout to use the available space, not hardcode fixed widths.  Or, if you really want to use fixed widths, they need to be smaller (shouldn't add up to more than 320dp).


问:
Does async pipe unsubscribes from an observable defined in a service and pointed to from a component variable?
I have a BehaviourSubject defined in a service, and i point to that subject with a variable i define in another component, in that component's view i subscribe to the subject using that variable, example:

service:

```<code>public exampleSubjebt$ = new BehaviorSubject<boolean>(true);
</code>```

component.ts:

```<code>ngOninit() {
let someVariable = this.service.exampleSubject$;
}
</code>```

component's view:

```<code><app-something [options]="someVariable | async"></app-something>
</code>```

My question is, does the fact the the observable sits in the service and I call it directly from there using the variable, make it so that the async pipe will not unsubscribe on the component's destruction?

答:
Yes it does unsubscribe. The async pipe is an angular directive, so it has all the lifecycles a component has. In the implementation i have found the following:

```<code>class ObservableStrategy implements SubscriptionStrategy {
  createSubscription(async: Observable<any>, updateLatestValue: any): SubscriptionLike {
    return async.subscribe({next: updateLatestValue, error: (e: any) => { throw e; }});
  }

  dispose(subscription: SubscriptionLike): void { subscription.unsubscribe(); }

  onDestroy(subscription: SubscriptionLike): void { subscription.unsubscribe(); }
}
</code>```

In the ngOnDestroy they call the dispose

```<code>ngOnDestroy(): void {
  if (this._subscription) {
    this._dispose();
  }
}
</code>```

Body:
I have a BehaviourSubject defined in a service, and i point to that subject with a variable i define in another component, in that component's view i subscribe to the subject using that variable, example:

service:

public exampleSubjebt$ = new BehaviorSubject<boolean>(true);

component.ts:

ngOninit() {
let someVariable = this.service.exampleSubject$;
}

component's view:

<app-something [options]="someVariable | async"></app-something>

My question is, does the fact the the observable sits in the service and I call it directly from there using the variable, make it so that the async pipe will not unsubscribe on the component's destruction?

Body:
Yes it does unsubscribe. The async pipe is an angular directive, so it has all the lifecycles a component has. In the implementation i have found the following:

class ObservableStrategy implements SubscriptionStrategy {
  createSubscription(async: Observable<any>, updateLatestValue: any): SubscriptionLike {
    return async.subscribe({next: updateLatestValue, error: (e: any) => { throw e; }});
  }

  dispose(subscription: SubscriptionLike): void { subscription.unsubscribe(); }

  onDestroy(subscription: SubscriptionLike): void { subscription.unsubscribe(); }
}

In the ngOnDestroy they call the dispose

ngOnDestroy(): void {
  if (this._subscription) {
    this._dispose();
  }
}


问:
React Cannot read property 'lastName' of undefined
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}
</code>```

API2 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}
</code>```

Merged API look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}
</code>```

Fetched data:

```<code>const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});
</code>```

答:
```<code>useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name; //replaced but doesn't work
    });
    return {
      ...api1,
      name: `${d.name} - ${d.lastName}`
    }
  });
});
</code>```

Array.find return undefined if there is no matched item on array. so d could be undefind and therefore code throws error there is no 'lastname' property on d.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

```<code>useEffect(() => {
  const data = api1.map(getData => {
    ...
    if (d) {
      return {
        ...getData,
        name: `${d.name} - ${d.lastName}`
      }
    } else {
      // some code to handle if d is undefined
    }
  });
});
</code>```

Body:
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}

API2 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}

Merged API look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}

Fetched data:

const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});

Body:
useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name; //replaced but doesn't work
    });
    return {
      ...api1,
      name: `${d.name} - ${d.lastName}`
    }
  });
});

Array.find return undefined if there is no matched item on array. so d could be undefind and therefore code throws error there is no 'lastname' property on d.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

useEffect(() => {
  const data = api1.map(getData => {
    ...
    if (d) {
      return {
        ...getData,
        name: `${d.name} - ${d.lastName}`
      }
    } else {
      // some code to handle if d is undefined
    }
  });
});


问:
Graphviz straight lines
I am trying to get straight line edges that exit a node on the right and enter on the left.
I have tried to use splines='line but it does not appear to create straight lines. Code below, as executed in jupyter notebook.

```<code>from graphviz import Digraph
g = Digraph('G', filename='cluster.gv')

with g.subgraph(name='cluster_0') as c:
    c.attr(style='filled', color='lightgrey')
    c.node_attr.update(style='filled', color='white')
    c.edges([('a0', 'a1'), ('a1', 'a2'), ('a2', 'a3')])
    c.attr(label='process #1')

with g.subgraph(name='cluster_1') as c:
    c.attr(color='blue')
    c.node_attr['style'] = 'filled'
    c.edges([('b0', 'b1'), ('b1', 'b2'), ('b2', 'b3')])
    c.attr(label='process #2')

g.edge('a1', 'b3',splines='line',tailport="e", headport="w", constraint='false')
g.edge('a2', 'b0',splines='line',tailport="e", headport="w", constraint='false')

g.view()
</code>```

This is the graph that is produced by the code:
Graph

答:
I have solved this. The placement of splines='line' was incorrect. Correct code below in case any future users have the same problem.

```<code>g = Digraph('G', filename='cluster.gv')

with g.subgraph(name='cluster_0') as c:
    c.attr(style='filled', color='lightgrey')
    c.node_attr.update(style='filled', color='white')
    c.edges([('a0', 'a1'), ('a1', 'a2'), ('a2', 'a3')])
    c.attr(label='process #1')

with g.subgraph(name='cluster_1') as c:
    c.attr(color='blue')
    c.node_attr['style'] = 'filled'
    c.edges([('b0', 'b1'), ('b1', 'b2'), ('b2', 'b3')])
    c.attr(label='process #2')

g.attr(splines='false')
g.edge('a1', 'b3',tailport="e", headport="w", constraint='false')
g.edge('a2', 'b0',tailport="e", headport="w", constraint='false')

g.view()
</code>```

Title: Graphviz straight lines

Body:
I am trying to get straight line edges that exit a node on the right and enter on the left.
I have tried to use splines='line but it does not appear to create straight lines. Code below, as executed in jupyter notebook.

from graphviz import Digraph
g = Digraph('G', filename='cluster.gv')

with g.subgraph(name='cluster_0') as c:
    c.attr(style='filled', color='lightgrey')
    c.node_attr.update(style='filled', color='white')
    c.edges([('a0', 'a1'), ('a1', 'a2'), ('a2', 'a3')])
    c.attr(label='process #1')

with g.subgraph(name='cluster_1') as c:
    c.attr(color='blue')
    c.node_attr['style'] = 'filled'
    c.edges([('b0', 'b1'), ('b1', 'b2'), ('b2', 'b3')])
    c.attr(label='process #2')

g.edge('a1', 'b3',splines='line',tailport="e", headport="w", constraint='false')
g.edge('a2', 'b0',splines='line',tailport="e", headport="w", constraint='false')

g.view()

This is the graph that is produced by the code:
Graph

Body:
I have solved this. The placement of splines='line' was incorrect. Correct code below in case any future users have the same problem.

g = Digraph('G', filename='cluster.gv')

with g.subgraph(name='cluster_0') as c:
    c.attr(style='filled', color='lightgrey')
    c.node_attr.update(style='filled', color='white')
    c.edges([('a0', 'a1'), ('a1', 'a2'), ('a2', 'a3')])
    c.attr(label='process #1')

with g.subgraph(name='cluster_1') as c:
    c.attr(color='blue')
    c.node_attr['style'] = 'filled'
    c.edges([('b0', 'b1'), ('b1', 'b2'), ('b2', 'b3')])
    c.attr(label='process #2')

g.attr(splines='false')
g.edge('a1', 'b3',tailport="e", headport="w", constraint='false')
g.edge('a2', 'b0',tailport="e", headport="w", constraint='false')

g.view()


问:
Deprecated Vertx Bridge PermittedOptions
I already was able to expose the Vert.x EventBus through a socket regarding the official docs:

https://vertx.io/docs/vertx-sockjs-service-proxy/java/

The purpose is to interact with a NodeJS App. For initial tests, the messages are already working between normal Verticals and the Node App

However, I can see that the class  io.vertx.ext.web.handler.sockjs.PermittedOptions is already Deprecated.

This is the snippet

```<code>import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.sockjs.BridgeOptions;
import io.vertx.ext.web.handler.sockjs.PermittedOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;

.
.
.

Router router = Router.router(vertx);

BridgeOptions opts = new BridgeOptions()
                          .addInboundPermitted(new PermittedOptions().setAddress("nodetest"))
                          .addOutboundPermitted(new PermittedOptions().setAddress("nodetest"));

router.mountSubRouter("/eventbus", SockJSHandler.create(vertx).bridge(opts));

vertx.createHttpServer().requestHandler(router).listen(3000, res -> {
      if (res.succeeded())
        promise.complete();
      else
        promise.fail(res.cause());
    });
.
.
.
</code>```

¿What is the right way to proceed?

答:
the class you mention is duplicated across 2 repositories, the "fix" is just to update the import statement to the right one:

```<code>io.vertx.ext.bridge.PermittedOptions
</code>```

All the rest should work as expected.

Body:
I already was able to expose the Vert.x EventBus through a socket regarding the official docs:

https://vertx.io/docs/vertx-sockjs-service-proxy/java/

The purpose is to interact with a NodeJS App. For initial tests, the messages are already working between normal Verticals and the Node App

However, I can see that the class  io.vertx.ext.web.handler.sockjs.PermittedOptions is already Deprecated.

This is the snippet

import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.sockjs.BridgeOptions;
import io.vertx.ext.web.handler.sockjs.PermittedOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;

.
.
.

Router router = Router.router(vertx);

BridgeOptions opts = new BridgeOptions()
                          .addInboundPermitted(new PermittedOptions().setAddress("nodetest"))
                          .addOutboundPermitted(new PermittedOptions().setAddress("nodetest"));

router.mountSubRouter("/eventbus", SockJSHandler.create(vertx).bridge(opts));

vertx.createHttpServer().requestHandler(router).listen(3000, res -> {
      if (res.succeeded())
        promise.complete();
      else
        promise.fail(res.cause());
    });
.
.
.

¿What is the right way to proceed?

Body:
the class you mention is duplicated across 2 repositories, the "fix" is just to update the import statement to the right one:

io.vertx.ext.bridge.PermittedOptions

All the rest should work as expected.


问:
Caller id faker
I want to develop an android application to fake my mobile number to outgoing call. How to do this in android? I havent seen any api/control available to do this? Does android allow this? Is it legal for all the countries? Please give me some insight in this.</p>

答: I am not entirely sure, but as far as I know the only thing stored on your SIM-card that identifies it is the IMEI number. Your phone number is probably stored in a database server somewhere, which would make it a lot harder to fake than just writing a little android app.</p>

Title: Caller id faker


问:
How to bind ContextMenu that has Command to the attached property?
I have an external control named DockSite.
When displayed ContextMenu from the DockSite control, the MenuOpening event handler is called.

I wanted to add my ContextMenu to the default ContextMenu when the MenuOpening event is called and I created the attached property as below to extend the behavior of the DockSite.

```<code>    public static ContextMenu GetAddDocumentMenu(DependencyObject obj)
    {
        return (ContextMenu)obj.GetValue(AddDocumentMenuProperty);
    }

    public static void SetAddDocumentMenu(DependencyObject obj, ContextMenu value)
    {
        obj.SetValue(AddDocumentMenuProperty, value);
    }

    // Using a DependencyProperty as the backing store for AddDocumentMenu.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AddDocumentMenuProperty =
        DependencyProperty.RegisterAttached("AddDocumentMenu", typeof(ContextMenu), typeof(DockSiteHook), new PropertyMetadata(new ContextMenu(), OnDocumentMenuChanged));

    private static void OnDocumentMenuChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var dockSite = (sender as DockSite);
        if (dockSite == null) return;

        ContextMenu on = (ContextMenu)e.NewValue;
        if (on is null) dockSite.MenuOpening -= DockSite_MenuOpening;
        else dockSite.MenuOpening += DockSite_MenuOpening;
    }

    private static void DockSite_MenuOpening(object sender, DockingMenuEventArgs e)
    {
        e.Menu.Items.Add(DockSiteHook.GetAddDocumentMenu(sender as DockSite));
    }
</code>```

I used the code above in my MainWindow as below.

```<code><docking:DockSite Grid.Row="1" x:Name="dockSite">

    <ap:DockSiteHook.AddDocumentMenu>
        <ContextMenu>
            <MenuItem Command="{Binding TestCommand}"/>
        </ContextMenu>
    </ap:DockSiteHook.AddDocumentMenu>

<docking:DockSite/>
</code>```

But the Visual Studio throws an error as below image.

The error message is "It can't bind the default value for AddDocumentMenu to the specific thread".

I want to bind the ContextMenu to the specific attached property.

Could someone tell me why fired the error above? and how to solve this problem?

Thanks for reading.

答:
Set the default value to null (or default(ContextMenu)):

```<code>public static readonly DependencyProperty AddDocumentMenuProperty =
    DependencyProperty.RegisterAttached("AddDocumentMenu", typeof(ContextMenu),
        typeof(DockSiteHook), new PropertyMetadata(null, OnDocumentMenuChanged));
</code>```

Body:
I have an external control named DockSite.
When displayed ContextMenu from the DockSite control, the MenuOpening event handler is called.

I wanted to add my ContextMenu to the default ContextMenu when the MenuOpening event is called and I created the attached property as below to extend the behavior of the DockSite.

    public static ContextMenu GetAddDocumentMenu(DependencyObject obj)
    {
        return (ContextMenu)obj.GetValue(AddDocumentMenuProperty);
    }

    public static void SetAddDocumentMenu(DependencyObject obj, ContextMenu value)
    {
        obj.SetValue(AddDocumentMenuProperty, value);
    }

    // Using a DependencyProperty as the backing store for AddDocumentMenu.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AddDocumentMenuProperty =
        DependencyProperty.RegisterAttached("AddDocumentMenu", typeof(ContextMenu), typeof(DockSiteHook), new PropertyMetadata(new ContextMenu(), OnDocumentMenuChanged));

    private static void OnDocumentMenuChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var dockSite = (sender as DockSite);
        if (dockSite == null) return;

        ContextMenu on = (ContextMenu)e.NewValue;
        if (on is null) dockSite.MenuOpening -= DockSite_MenuOpening;
        else dockSite.MenuOpening += DockSite_MenuOpening;
    }

    private static void DockSite_MenuOpening(object sender, DockingMenuEventArgs e)
    {
        e.Menu.Items.Add(DockSiteHook.GetAddDocumentMenu(sender as DockSite));
    }

I used the code above in my MainWindow as below.

<docking:DockSite Grid.Row="1" x:Name="dockSite">

    <ap:DockSiteHook.AddDocumentMenu>
        <ContextMenu>
            <MenuItem Command="{Binding TestCommand}"/>
        </ContextMenu>
    </ap:DockSiteHook.AddDocumentMenu>

<docking:DockSite/>

But the Visual Studio throws an error as below image.

The error message is "It can't bind the default value for AddDocumentMenu to the specific thread".

I want to bind the ContextMenu to the specific attached property.

Could someone tell me why fired the error above? and how to solve this problem?

Thanks for reading.

Body:
Set the default value to null (or default(ContextMenu)):

public static readonly DependencyProperty AddDocumentMenuProperty =
    DependencyProperty.RegisterAttached("AddDocumentMenu", typeof(ContextMenu),
        typeof(DockSiteHook), new PropertyMetadata(null, OnDocumentMenuChanged));


答:
Try to do this. There could be a case when in your real data could be some name taht not exist in api2.

```<code>const data = api1.map(getData => {
  const d = api2.find((object) => {
    return  object.name === getData.name; // <---- NOTE THIS
  });

  if (!d) { // <---- NOTE THIS
    return getData
  }

  return {
    ...getData, // <---- NOTE THIS
    name: `${d.name} - ${d.lastName}`
  }
});
</code>```

idk if you really have id in objects, but I would compare by id, not by name.

```<code>return  object.id === getData.id;
</code>```

Title: React Cannot read property 'lastName' of undefined

Body:
Try to do this. There could be a case when in your real data could be some name taht not exist in api2.

const data = api1.map(getData => {
  const d = api2.find((object) => {
    return  object.name === getData.name; // <---- NOTE THIS
  });

  if (!d) { // <---- NOTE THIS
    return getData
  }

  return {
    ...getData, // <---- NOTE THIS
    name: `${d.name} - ${d.lastName}`
  }
});

idk if you really have id in objects, but I would compare by id, not by name.

return  object.id === getData.id;


问:
Can I extend Traefik in a way to open the request header check user identity and update request url?
I want to add a sort of custom middleware in Traefik, where I can check user identity and after validating from the database, I want to route users to different versions of the application? Is it possible with Traefik?</p>

答: For the time being, the only way to add a custom middleware to Traefik is to fork it and add your custom middleware into the source code and build it for yourself. Actually this is not too difficult but of course it comes with all the downsides of forking. There is an example here: https://github.com/negasus/traefik2-luascript. You need to edit it a bit because it is somewhat outdated but I was able to add my custom middleware by following it.</p>


问:
How do I keep the camera from changing its size?
I have attached two screenshots to my problem. Basically on resizing the Game view window the camera size also gets resized and the objects get moved when pressing play. How do I solve this?

答:
On your game view, you are in "Free Aspect" mode, which does exactly the behaviour you don't want.

You can use your standalone resolution, or define custom ones.


问:
Removing the displayModeButton in UISplitViewController in iOS
I want to remove the displayModeButton from the detailViewController's Navigation Bar in splitveiwconroller. I tried setting leftBarButtionItem.isEnable = false in AppDelegate.swift file(as below)

```<code>if let splitViewController = self.window!.rootViewController as? UISplitViewController {
            let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
            navigationController.topViewController!.navigationItem.leftBarButtonItem?.isEnabled = false
            }
</code>```

it hides the displaymodebutton intially when the application start. But when i swipt right to open the master view and then swipe left to dismiss the masterview controller the dispaly mode buttom reappars again. Please help me to hide the displayModeButton from detail view conroller.

答:
Alternate to Daljeet's answer we can also use navigationItem.setHidesBackButton  on the detailview controller or use this in the AppDelegate.swift's didFinishLaunchingWithOptions : </p>

```<code>if let splitViewController = appDelegate.window!.rootViewController as? UISplitViewController {

let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.setHidesBackButton(true, animated: true)
}
</code>```

Body:
I want to remove the displayModeButton from the detailViewController's Navigation Bar in splitveiwconroller. I tried setting leftBarButtionItem.isEnable = false in AppDelegate.swift file(as below)

if let splitViewController = self.window!.rootViewController as? UISplitViewController {
            let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
            navigationController.topViewController!.navigationItem.leftBarButtonItem?.isEnabled = false
            }

it hides the displaymodebutton intially when the application start. But when i swipt right to open the master view and then swipe left to dismiss the masterview controller the dispaly mode buttom reappars again. Please help me to hide the displayModeButton from detail view conroller.

Body:
Alternate to Daljeet's answer we can also use navigationItem.setHidesBackButton  on the detailview controller or use this in the AppDelegate.swift's didFinishLaunchingWithOptions :

if let splitViewController = appDelegate.window!.rootViewController as? UISplitViewController {

let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.setHidesBackButton(true, animated: true)
}


问:
Problem with dynamic table in ascx control
I have the following table in an ascx user controll:

        <asp:Button ID="btChangeSerNo" runat="server" Text="Update" OnClick="btChangeSerNo_onClick" />

```

I create the tblChangeSerNo dynamically with text boxes prefilled with the current values in the db. The idea of the control is to allow the user to update the values of the DB with new values. The problem is that when the btChangeSerNo_onClick method is called:

The table is not rendered, since I do it on pre-render

Even if I rendered the table on Page_Load I could not access updated values of the user because they are lost.

How can I solve this problem?

答:
The best practice way will be to use Grid control instead.

If you prefer to stick with your own code, follow those steps:

Store all the text boxes in global fields, e.g. public List<TextBox> m_tableTextboxes = new List<TextBox>(); and when creating add to that list.

Have the code creating the dynamic controls in the Page_Load but execute it only when not is PostBack: if (!Page.IsPostBack) { ... }

In the button click event, read the values from your global field.

Done something similar in the past, so the concept should work.

Body:
I have the following table in an ascx user controll:

        <asp:Button ID="btChangeSerNo" runat="server" Text="Update" OnClick="btChangeSerNo_onClick" />

I create the tblChangeSerNo dynamically with text boxes prefilled with the current values in the db. The idea of the control is to allow the user to update the values of the DB with new values. The problem is that when the btChangeSerNo_onClick method is called:

The table is not rendered, since I do it on pre-render

Even if I rendered the table on Page_Load I could not access updated values of the user because they are lost.

How can I solve this problem?


问:
How to feed a value from an output object as an input into another output object?
I'm working on a simulation-based app.  I have 2 initial numeric input objects, "max imp count" and "population size". Based on what is fed into these numeric input objects, the app generates 2 more input objects (really as output objects)- "select_proportion" and "select_probability". If the "max imp count" is 3, the app should generate 8 new input objects- 4 which ask for proportion (proportion0, proportion1, proportion2, proportion3), and 4 of which ask for probability0, probability1, probability2 and probability3. I want to feed these proportion and probability values into sample functions that work in the following manner:

1) sample(c(0,input$max_imp, 1), size=input$population, replace=TRUE, prob= these take the proportion values

sample for binary values for all proportion brackets:

2) sample(c(0,1), length(proportion_i), replace=TRUE, prob=these take the probability values)

Ideally, I would like to have this all in a dataframe where I have columns for which proportion bracket a record belongs to and whether they have 0 or 1.

Code:

```<code>library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Simulation"),
  dashboardSidebar(
    sidebarMenu(
      numericInput("max_imp", "max imp count", 0, min = 0, max = 15, step = 1),
      numericInput("population", "population size", 1, min = 0, max = 100000, step = 1),
      menuItemOutput("menuitem")
    )
  ),
  dashboardBody(
    uiOutput("select_proportion"),
    uiOutput("select_probability")
  ))

server <- function(input, output) {

    output$select_proportion = renderUI(
      lapply(0:(input$max_imp), function(i){
      numericInput(inputId = "i1", label = paste0("proportion",i), 0, min = 0, max = 1, step = 0.05)}))

    output$select_probability = renderUI(
    lapply(0:(input$max_imp), function(i){
      numericInput(inputId = "i2", label = paste0("probability",i), 0, min = 0, max = 1, step = 0.05)}))

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

答:
Your output elements are only UI container which are then filled with the input elements defined in the renderUI functions. You can easily access the values of these input elements as you do it with your other inputs.

The only thing here is that you have to set the IDs of the inputs in a dynamic way e.g. instead of id = "i2" for the second input use id = paste("input", i, "2", sep = "-"). This will create you input$max_imp + 1 different inputs. The values can then be accessed via input$input_1_2.

BR
Sebastian

Body:
I'm working on a simulation-based app.  I have 2 initial numeric input objects, "max imp count" and "population size". Based on what is fed into these numeric input objects, the app generates 2 more input objects (really as output objects)- "select_proportion" and "select_probability". If the "max imp count" is 3, the app should generate 8 new input objects- 4 which ask for proportion (proportion0, proportion1, proportion2, proportion3), and 4 of which ask for probability0, probability1, probability2 and probability3. I want to feed these proportion and probability values into sample functions that work in the following manner:

1) sample(c(0,input$max_imp, 1), size=input$population, replace=TRUE, prob= these take the proportion values

sample for binary values for all proportion brackets:

2) sample(c(0,1), length(proportion_i), replace=TRUE, prob=these take the probability values)

Ideally, I would like to have this all in a dataframe where I have columns for which proportion bracket a record belongs to and whether they have 0 or 1.

Code:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Simulation"),
  dashboardSidebar(
    sidebarMenu(
      numericInput("max_imp", "max imp count", 0, min = 0, max = 15, step = 1),
      numericInput("population", "population size", 1, min = 0, max = 100000, step = 1),
      menuItemOutput("menuitem")
    )
  ),
  dashboardBody(
    uiOutput("select_proportion"),
    uiOutput("select_probability")
  ))

server <- function(input, output) {

    output$select_proportion = renderUI(
      lapply(0:(input$max_imp), function(i){
      numericInput(inputId = "i1", label = paste0("proportion",i), 0, min = 0, max = 1, step = 0.05)}))

    output$select_probability = renderUI(
    lapply(0:(input$max_imp), function(i){
      numericInput(inputId = "i2", label = paste0("probability",i), 0, min = 0, max = 1, step = 0.05)}))

}

# Run the application
shinyApp(ui = ui, server = server)


问:
if I want Elasticsearch to be faster, do I just add more nodes to the cluster?
Seems that Kibana will take over 30 seconds for some of my queries and subsequently cancel the requests automatically.  Kinda a bummer because I was hoping that a single node, a dual Master/Data node would be enough.  It seems this might not be the case, and to improve the query speed I should add additional Nodes (Data I think) to help with processing things faster.

That being said, is this a natural thing for Kibana 7.6?  Will it auto Cancel requests after 30 seconds, or can this be disabled?  I was hoping to have a single node for the time being and was OK with nodes taking time to process as I really only query to monitor the throughput for the time being.

It seems that if I do want to improve query times, I should most certainly look into adding an additional data node (or 2) to improve query capabilities, but not necessarily the indexing, as it is still chugging along at a smooth 2m entries per 5 minutes.

答:
EDIT

You can cancel searches by calling task management API. Kibana does cancel query from 7.4, as documented:

In-progress search requests to Elasticsearch will now be cancelled
  when a new search is requested, or when a user navigates away from the
  page or removes a panel from a dashboard.

That's mainly a protection from multiple requests by a single kibana client, not a timeout cancel. If you keep waiting and perform no other operations, you can get search/aggregation results eventually.

ORIGIN POST

Will it auto Cancel requests after 30 seconds, or can this be disabled?

A query in ES will run, there is no timeout. Kibana just do not get responses that take too long to return. To configure this timeout, kibana.yaml has the following (default) settings:

```<code># Time in milliseconds to wait for responses from the back end or elasticsearch.
# This must be > 0
request_timeout: 300000
</code>```

Instead of kibana, you can write a java client for your requests or use curl to call ES REST API. Usually this can achieve a much longer timeout.

It seems that if I do want to improve query times, I should most certainly look into adding an additional data node (or 2) to improve query capabilities

Multiple factors influence ES query performance and it's more wise to focus on real bottleneck.
CPU usage, memory usage, disk throughput, network bandwidth, etc. It's better to make clear what's the bottleneck. Adding nodes, using SSD instead of SATA, or adding memory may also help.

Body:
EDIT

You can cancel searches by calling task management API. Kibana does cancel query from 7.4, as documented:

In-progress search requests to Elasticsearch will now be cancelled
  when a new search is requested, or when a user navigates away from the
  page or removes a panel from a dashboard.

That's mainly a protection from multiple requests by a single kibana client, not a timeout cancel. If you keep waiting and perform no other operations, you can get search/aggregation results eventually.

ORIGIN POST

Will it auto Cancel requests after 30 seconds, or can this be disabled?

A query in ES will run, there is no timeout. Kibana just do not get responses that take too long to return. To configure this timeout, kibana.yaml has the following (default) settings:

# Time in milliseconds to wait for responses from the back end or elasticsearch.
# This must be > 0
request_timeout: 300000

Instead of kibana, you can write a java client for your requests or use curl to call ES REST API. Usually this can achieve a much longer timeout.

It seems that if I do want to improve query times, I should most certainly look into adding an additional data node (or 2) to improve query capabilities

Multiple factors influence ES query performance and it's more wise to focus on real bottleneck.
CPU usage, memory usage, disk throughput, network bandwidth, etc. It's better to make clear what's the bottleneck. Adding nodes, using SSD instead of SATA, or adding memory may also help.


问:
vue.js loop option value in object
i have the object like this;

```<code>fluit:[
    {id:'001', name:"Apple"},
    {id:'002', name:"Banana"},
    {id:'003', name:"Mango"},
    {id:'004', name:"orange"},
    {id:'005', name:"papaya"},
  ]
</code>```

And code in vuejs like this

```<code><select >
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"{{item.name</option>
</select>
</code>```

and what i get from this tag it's like this

and what i want to ask is how can i get the value as the id of each option. like a when i select Mango and the value is 003.
if you know how to solve this please help me.
thank you.

答:
For Your Solution use this -

```<code><template>
    <select name="itemType" v-model="itemType" @change="onChange()" class="form-control">
         <option value="001">Apple</option>
         <option value="002">Banana</option>
    </select>
</template>

<script>
export default {
    data() {
        return {
            itemType: '',
        }
    },

    methods: {
        onChange() {
            console.log('The new value is: ', this.itemType)
        }
    }
}
</script>
</code>```

My advice use vuetify (v-select)component with vue for better performance.

```<code><template>
     <v-select
        v-model="select"
        :items="fluit"
        item-text="id"
        item-value="name"
        label="Select"
        @input="doSomething"
        return-object/>
</template>

<script>
  export default {
    data () {
      return {
        select: { id:'005', name:"papaya" },
        items: [
           {id:'001', name:"Apple"},
           {id:'002', name:"Banana"},
           {id:'003', name:"Mango"},
           {id:'004', name:"orange"},
           {id:'005', name:"papaya"},
        ],
      }
method:{
      doSomething(){
       console.log(this.select)
      }
    }

    },
  }
</script>
</code>```

I Hope it will help!

Title: vue.js loop option value in object

Body:
i have the object like this;

fluit:[
    {id:'001', name:"Apple"},
    {id:'002', name:"Banana"},
    {id:'003', name:"Mango"},
    {id:'004', name:"orange"},
    {id:'005', name:"papaya"},
  ]

And code in vuejs like this

<select >
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"{{item.name</option>
</select>

and what i get from this tag it's like this

and what i want to ask is how can i get the value as the id of each option. like a when i select Mango and the value is 003.
if you know how to solve this please help me.
thank you.

Body:
For Your Solution use this -

<template>
    <select name="itemType" v-model="itemType" @change="onChange()" class="form-control">
         <option value="001">Apple</option>
         <option value="002">Banana</option>
    </select>
</template>

<script>
export default {
    data() {
        return {
            itemType: '',
        }
    },

    methods: {
        onChange() {
            console.log('The new value is: ', this.itemType)
        }
    }
}
</script>

My advice use vuetify (v-select)component with vue for better performance.

<template>
     <v-select
        v-model="select"
        :items="fluit"
        item-text="id"
        item-value="name"
        label="Select"
        @input="doSomething"
        return-object/>
</template>

<script>
  export default {
    data () {
      return {
        select: { id:'005', name:"papaya" },
        items: [
           {id:'001', name:"Apple"},
           {id:'002', name:"Banana"},
           {id:'003', name:"Mango"},
           {id:'004', name:"orange"},
           {id:'005', name:"papaya"},
        ],
      }
method:{
      doSomething(){
       console.log(this.select)
      }
    }

    },
  }
</script>

I Hope it will help!


问:
FLUTTER scroll multiple widget
if i have two (or more) scrollable widgets (say, SingleChildScrollView),
how do i make them BOTH scroll at the same time?

because i will be Stacking them on top of each other,
so one is covered by the other's Container.

i'm fairly new, so i dont have a lot of option right now.
i tried ScrollController but its not working.
i have no idea how to properly implement it in my codes.

also, please attach a simple code example if possible.

Here's what i tried:

```<code>class _MyHomePageState extends State<MyHomePage> {

  final ScrollController _mycontroller = new ScrollController();

  @override
  Widget build(BuildContext context) {
    body:
      Container(
        height: 100,
        child:
          Stack( children: <Widget>[
            SingleChildScrollView(
              controller: _mycontroller,
              child: Column( children: <Widget>[
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
              ],)
            ),
            SingleChildScrollView(
              controller: _mycontroller,
              child: Column(children: <Widget>[
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
              ],)
            ),
          ])
      )
  }
}
</code>```

i want both to scroll together if i scroll either one.
but they still scroll independently even if they have the same controller.
im not sure if im using controller correctly.

please advise.

答:
In flutter there are 11 different types of widgets available to achieve scrolling functionality with a different task. To create a simple vertical ScrollView which can contain a different type of widgets with different behavior we would use SingleChildScrollView widget. This widget can show multiple widgets inside it.

Create Scaffold widget -> Safe Area widget in widget build area

```<code>class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return MaterialApp(
    home: Scaffold(
        body: SafeArea(
          child:
        )
       )
      );
   }
 }
</code>```

Create SingleChildScrollView widget in Safe Area widget. Now we would make a Column widget inside SingleChildScrollView and put all our multiple widgets inside Column widget. We are creating multiple container widget and image widgets inside SingleChildScrollView. The all will scroll easily here.

```<code>SingleChildScrollView(
  child: Column(
  children: <Widget>[

    Container(
      color: Colors.green, // Yellow
      height: 120.0,
    ),

    Image.network('https://flutter-examples.com/wp-content/uploads/2019/09/blossom.jpg',
       width: 300, height: 200, fit: BoxFit.contain),

    Image.network('https://flutter-examples.com/wp-content/uploads/2019/09/sample_img.png',
       width: 200, fit: BoxFit.contain),

    Container(
      color: Colors.pink, // Yellow
      height: 120.0,
    ),

    Text('Some Sample Text - 1', style: TextStyle(fontSize: 28)),

    Text('Some Sample Text - 2', style: TextStyle(fontSize: 28)),

    Text('Some Sample Text - 3', style: TextStyle(fontSize: 28)),

    Container(
      color: Colors.redAccent, // Yellow
      height: 120.0,
    ),

    Image.network('https://flutter-examples.com/wp-content/uploads/2019/09/blossom.jpg',
       width: 300, height: 200, fit: BoxFit.contain),

  ],
  ),
 ),
</code>```

Title: FLUTTER scroll multiple widget

Body:
if i have two (or more) scrollable widgets (say, SingleChildScrollView),
how do i make them BOTH scroll at the same time?

because i will be Stacking them on top of each other,
so one is covered by the other's Container.

i'm fairly new, so i dont have a lot of option right now.
i tried ScrollController but its not working.
i have no idea how to properly implement it in my codes.

also, please attach a simple code example if possible.

Here's what i tried:

class _MyHomePageState extends State<MyHomePage> {

  final ScrollController _mycontroller = new ScrollController();

  @override
  Widget build(BuildContext context) {
    body:
      Container(
        height: 100,
        child:
          Stack( children: <Widget>[
            SingleChildScrollView(
              controller: _mycontroller,
              child: Column( children: <Widget>[
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
                Text('LEFT            '),
              ],)
            ),
            SingleChildScrollView(
              controller: _mycontroller,
              child: Column(children: <Widget>[
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
                Text('          RIGHT'),
              ],)
            ),
          ])
      )
  }
}

i want both to scroll together if i scroll either one.
but they still scroll independently even if they have the same controller.
im not sure if im using controller correctly.

please advise.

Body:
In flutter there are 11 different types of widgets available to achieve scrolling functionality with a different task. To create a simple vertical ScrollView which can contain a different type of widgets with different behavior we would use SingleChildScrollView widget. This widget can show multiple widgets inside it.

Create Scaffold widget -> Safe Area widget in widget build area

class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return MaterialApp(
    home: Scaffold(
        body: SafeArea(
          child:
        )
       )
      );
   }
 }

Create SingleChildScrollView widget in Safe Area widget. Now we would make a Column widget inside SingleChildScrollView and put all our multiple widgets inside Column widget. We are creating multiple container widget and image widgets inside SingleChildScrollView. The all will scroll easily here.

SingleChildScrollView(
  child: Column(
  children: <Widget>[

    Container(
      color: Colors.green, // Yellow
      height: 120.0,
    ),

    Image.network('https://flutter-examples.com/wp-content/uploads/2019/09/blossom.jpg',
       width: 300, height: 200, fit: BoxFit.contain),

    Image.network('https://flutter-examples.com/wp-content/uploads/2019/09/sample_img.png',
       width: 200, fit: BoxFit.contain),

    Container(
      color: Colors.pink, // Yellow
      height: 120.0,
    ),

    Text('Some Sample Text - 1', style: TextStyle(fontSize: 28)),

    Text('Some Sample Text - 2', style: TextStyle(fontSize: 28)),

    Text('Some Sample Text - 3', style: TextStyle(fontSize: 28)),

    Container(
      color: Colors.redAccent, // Yellow
      height: 120.0,
    ),

    Image.network('https://flutter-examples.com/wp-content/uploads/2019/09/blossom.jpg',
       width: 300, height: 200, fit: BoxFit.contain),

  ],
  ),
 ),


问:
How to show every max value in mysql?
I've multiple values with different timestamps like the following:

```<code>10   01:01:00
20   01:35:00
30   02:10:00
05   02:45:00
12   03:05:00
21   03:30:00
10   04:06:00
40   05:15:00
</code>```

I don't have a column with which I can group by and find max. I want to get the records with max values like 30,21, and 40. The data is always in this format, like value increasing and then starts from zero again. What query will help me to find these records?

To clarify, it's sorted by the timestamp, and I want to get the timestamps for the local maxima, the rows where the next row has a lesser value:

```<code>value    tmstmp
-----   --------
 10     01:01:00
 20     01:35:00
 30     02:10:00  <-- this one since next value is 5 (< 30).

 05     02:45:00
 12     03:05:00
 21     03:30:00  <-- this one since next value is 10 (< 21).

 10     04:06:00
 40     05:15:00  <-- this one since next value is 40 (< infinity).
</code>```

答:
Somehow your question is not clear to me.
Assume that first column name is "value" and second column name is "timestamp".

Select Max(value) from  group by timestamp.

Title: How to show every max value in mysql?

Body:
I've multiple values with different timestamps like the following:

10   01:01:00
20   01:35:00
30   02:10:00
05   02:45:00
12   03:05:00
21   03:30:00
10   04:06:00
40   05:15:00

I don't have a column with which I can group by and find max. I want to get the records with max values like 30,21, and 40. The data is always in this format, like value increasing and then starts from zero again. What query will help me to find these records?

To clarify, it's sorted by the timestamp, and I want to get the timestamps for the local maxima, the rows where the next row has a lesser value:

value    tmstmp
-----   --------
 10     01:01:00
 20     01:35:00
 30     02:10:00  <-- this one since next value is 5 (< 30).

 05     02:45:00
 12     03:05:00
 21     03:30:00  <-- this one since next value is 10 (< 21).

 10     04:06:00
 40     05:15:00  <-- this one since next value is 40 (< infinity).