问:
Java MouseAdapter
So I have my custom mouse adapter. I want to call a method if:
The x and y coordinates are in a Rectangle with for example the coordinates x = 40 y = 40 and the width = 10 length = 10. How can I check if the x and y coordinates (of the mouse) are in the rectangle?
I tried this:

```<code>@Override
public void mouseClicked(MouseEvent e) {
    if(isXinBounds(e.getX()) || isYinBounds(e.getY())) {
        //This happens if the mouse click is in the rectangle
    }
}

//Check if the x coordinate of the mouse click is in the rectangle
private boolean isXinBounds(int x) {
    if(x <= ob.getBounds().getX() + ob.getBounds().getWidth() / 2 && x >= ob.getBounds().getX() - ob.getBounds().getWidth() / 2) return true;
    return false;
}

//Check if the y coordinate of the mouse click is in the rectangle
private boolean isYinBounds(int y) {
    if(y <= ob.getBounds().getY() + ob.getBounds().getHeight() / 2 && y >= ob.getBounds().getY() - ob.getBounds().getHeight() / 2) return true;
    return false;
}
</code>```

But that didn't work

答:
You're making a really weird formula to check if your click is in bounds of your rectangle.

If we set the rectangle coords:

```<code>x = 10
y = 10
width = 50
height = 50
</code>```

And create a new Rectangle with those values:

```<code>Rectangle rect = new Rectangle(x, y, widht, height)
</code>```

We can then do this for both X & Y

```<code>private boolean xIsInBounds(int x) {
    if (x >= rect.x && x <= rect.width + x) {
        return true;
    }
    return false;
}
</code>```

Because we check for the X & Y values as they are going to be always the same, but we have to add the X & Y values to the width and height respectively due to it being moved due to the X & Y values not being on 0,0.

The other issue in your code is that you're asking:

```<code>if (xIsInBounds(...) || yIsInBounds(...)) { ... }
</code>```

When it should be an && instead of ||.

Here's the code that produces the following output in the form of a Minimal Reproducible Example

```<code>import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ClickOnBounds extends MouseAdapter {
    private JFrame frame;
    private JPanel pane;
    private static final int X_COORD = 10;
    private static final int Y_COORD = 10;
    private static final int RECT_WIDTH = 50;
    private static final int RECT_HEIGHT = 50;
    private Rectangle rect = new Rectangle(X_COORD, Y_COORD, RECT_WIDTH, RECT_HEIGHT);

    @SuppressWarnings("serial")
    private void createAndShowGUI() {
        frame = new JFrame(this.getClass().getSimpleName());
        pane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.draw(rect);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(70, 70);
            }
        };

        pane.addMouseListener(this);
        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        super.mouseClicked(e);
        if (xIsInBound(e.getX()) && yIsInBound(e.getY())) {
            System.out.println("Yes! " + e.getX() + " " + e.getY());
        } else {
            System.out.println("No! " + e.getX() + " " + e.getY());
        }
    }

    private boolean xIsInBound(int x) {
        if (x >= rect.x && x <= rect.width + X_COORD) {
            return true;
        }
        return false;
    }

    private boolean yIsInBound(int y) {
        if (y >= rect.y && y <= rect.height + Y_COORD) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ClickOnBounds()::createAndShowGUI);
    }
}
</code>```

And, as you can see in the image above, it works perfectly.

Title: Java MouseAdapter

Body:
So I have my custom mouse adapter. I want to call a method if:
The x and y coordinates are in a Rectangle with for example the coordinates x = 40 y = 40 and the width = 10 length = 10. How can I check if the x and y coordinates (of the mouse) are in the rectangle?
I tried this:

@Override
public void mouseClicked(MouseEvent e) {
    if(isXinBounds(e.getX()) || isYinBounds(e.getY())) {
        //This happens if the mouse click is in the rectangle
    }
}

//Check if the x coordinate of the mouse click is in the rectangle
private boolean isXinBounds(int x) {
    if(x <= ob.getBounds().getX() + ob.getBounds().getWidth() / 2 && x >= ob.getBounds().getX() - ob.getBounds().getWidth() / 2) return true;
    return false;
}

//Check if the y coordinate of the mouse click is in the rectangle
private boolean isYinBounds(int y) {
    if(y <= ob.getBounds().getY() + ob.getBounds().getHeight() / 2 && y >= ob.getBounds().getY() - ob.getBounds().getHeight() / 2) return true;
    return false;
}

But that didn't work

Body:
You're making a really weird formula to check if your click is in bounds of your rectangle.

If we set the rectangle coords:

x = 10
y = 10
width = 50
height = 50

And create a new Rectangle with those values:

Rectangle rect = new Rectangle(x, y, widht, height)

We can then do this for both X & Y

private boolean xIsInBounds(int x) {
    if (x >= rect.x && x <= rect.width + x) {
        return true;
    }
    return false;
}

Because we check for the X & Y values as they are going to be always the same, but we have to add the X & Y values to the width and height respectively due to it being moved due to the X & Y values not being on 0,0.

The other issue in your code is that you're asking:

if (xIsInBounds(...) || yIsInBounds(...)) { ... }

When it should be an && instead of ||.

Here's the code that produces the following output in the form of a Minimal Reproducible Example

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ClickOnBounds extends MouseAdapter {
    private JFrame frame;
    private JPanel pane;
    private static final int X_COORD = 10;
    private static final int Y_COORD = 10;
    private static final int RECT_WIDTH = 50;
    private static final int RECT_HEIGHT = 50;
    private Rectangle rect = new Rectangle(X_COORD, Y_COORD, RECT_WIDTH, RECT_HEIGHT);

    @SuppressWarnings("serial")
    private void createAndShowGUI() {
        frame = new JFrame(this.getClass().getSimpleName());
        pane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.draw(rect);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(70, 70);
            }
        };

        pane.addMouseListener(this);
        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        super.mouseClicked(e);
        if (xIsInBound(e.getX()) && yIsInBound(e.getY())) {
            System.out.println("Yes! " + e.getX() + " " + e.getY());
        } else {
            System.out.println("No! " + e.getX() + " " + e.getY());
        }
    }

    private boolean xIsInBound(int x) {
        if (x >= rect.x && x <= rect.width + X_COORD) {
            return true;
        }
        return false;
    }

    private boolean yIsInBound(int y) {
        if (y >= rect.y && y <= rect.height + Y_COORD) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ClickOnBounds()::createAndShowGUI);
    }
}

And, as you can see in the image above, it works perfectly.


来源: stackexchange

问:
Where should I put jars on a dataproc cluster so they can be used by gcloud dataproc jobs submit spark?
I have an initialisation script that downloads a .jar from our local artefact repository and places it into /usr/local/bin on each node on the cluster. I can run it using

```<code>gcloud dataproc jobs submit spark --cluster=my_cluster \
      --region=us-central1 --jar=file:///usr/local/bin/myjar.jar -- arg1 arg2
</code>```

However I'd prefer it if my end users did not have to know the location of the jar.

Where can I put the .jar so that the location of it does not have to be specified?

答:
For spark jobs, you should be able to just place your jarfiles in /usr/lib/spark/jars on all nodes to automatically be available on the classpath.

For a more general coverage, you could add your jars to /usr/lib/hadoop/lib instead; the hadoop lib directory is also automatically included into Spark jobs on Dataproc, and is where libraries such as the GCS connector jarfile reside. You can see the hadoop lib directory being included via the SPARK_DIST_CLASSPATH environment variable configured in /etc/spark/conf/spark-env.sh.

If the desired behavior is still to specify using the --jar flag to specify a "main jar" instead of --jars to specify library jars that just provide classes, unfortunately there's currently no notion of a "working directory" on the cluster that would allow just specifying relative (instead of absolute) paths to the "main jar". However, there are two approaches that would have similar behavior:

Make the jarfiles local to the user's workspace from which jobs are being submitted - gcloud will then upload the jarfile at job-submission time into GCS and point the job at the jarfile when it runs in a job-specific directory. Note that this would cause duplicate uploads of the jarfile into GCS each time the job runs since it's always staging into a unique job directory; you'd have to gcloud dataproc jobs delete later on to clean up GCS space used by those jarfiles

(Preferred approach): Use the --class instead of the --jar argument for specifying what job to run after doing the steps above to make the jar available in the Spark classpath already. While the invocation of a classname is a bit more verbose, it still achieves the goal  of hiding details of jarfile location from the user.

For example, the classes used for "spark-shell" implementation are already on the classpath, so if you wanted to run a scala file as if you were running it through spark-shell, you could run:

```<code>gcloud dataproc jobs submit spark --cluster my-cluster \
    --class org.apache.spark.repl.Main \
    -- -i myjob.scala
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an initialisation script that downloads a .jar from our local artefact repository and places it into /usr/local/bin on each node on the cluster. I can run it using

gcloud dataproc jobs submit spark --cluster=my_cluster \
      --region=us-central1 --jar=file:///usr/local/bin/myjar.jar -- arg1 arg2

However I'd prefer it if my end users did not have to know the location of the jar.

Where can I put the .jar so that the location of it does not have to be specified?

Body:
For spark jobs, you should be able to just place your jarfiles in /usr/lib/spark/jars on all nodes to automatically be available on the classpath.

For a more general coverage, you could add your jars to /usr/lib/hadoop/lib instead; the hadoop lib directory is also automatically included into Spark jobs on Dataproc, and is where libraries such as the GCS connector jarfile reside. You can see the hadoop lib directory being included via the SPARK_DIST_CLASSPATH environment variable configured in /etc/spark/conf/spark-env.sh.

If the desired behavior is still to specify using the --jar flag to specify a "main jar" instead of --jars to specify library jars that just provide classes, unfortunately there's currently no notion of a "working directory" on the cluster that would allow just specifying relative (instead of absolute) paths to the "main jar". However, there are two approaches that would have similar behavior:

Make the jarfiles local to the user's workspace from which jobs are being submitted - gcloud will then upload the jarfile at job-submission time into GCS and point the job at the jarfile when it runs in a job-specific directory. Note that this would cause duplicate uploads of the jarfile into GCS each time the job runs since it's always staging into a unique job directory; you'd have to gcloud dataproc jobs delete later on to clean up GCS space used by those jarfiles

(Preferred approach): Use the --class instead of the --jar argument for specifying what job to run after doing the steps above to make the jar available in the Spark classpath already. While the invocation of a classname is a bit more verbose, it still achieves the goal  of hiding details of jarfile location from the user.

For example, the classes used for "spark-shell" implementation are already on the classpath, so if you wanted to run a scala file as if you were running it through spark-shell, you could run:

gcloud dataproc jobs submit spark --cluster my-cluster \
    --class org.apache.spark.repl.Main \
    -- -i myjob.scala


问:
Swift: Avoid scrolling top 2 tableview cells
Is there a way to stop scrolling certain cells in tableview? I want the top 2 cells in UITableView to be static and have scroll enabled on other cells. Scroll enabled property is on tableview, so it scrolls all the cells.

The top 2 cells are of height 44.0 each. I tried the below code, but it still scrolls the top 2 cells.

```<code>func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    isScrolling = true
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let startScrollingOffset = 88.0
    if (scrollView.contentOffset.y < CGFloat(startScrollingOffset)) {
        // moved to top
        isScrollDown = false
    } else if (scrollView.contentOffset.y > CGFloat(startScrollingOffset)) {
        // moved to bottom
        isScrollDown = true
    } else {
        // didn't move
    }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if isScrollDown == false {
        return
    }
}
</code>```

答:
If you're trying to achieve an effect like static cells that remain on top when the list scrolls, use header view property of UITableView, here is an example with minimum code required to make this work. Replace the headerView with whatever cells you're trying to not scroll.

class VC: UITableViewController {

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = .purple
        return headerView
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = String(describing: indexPath)
        return cell
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
}
```

Body:
Is there a way to stop scrolling certain cells in tableview? I want the top 2 cells in UITableView to be static and have scroll enabled on other cells. Scroll enabled property is on tableview, so it scrolls all the cells.

The top 2 cells are of height 44.0 each. I tried the below code, but it still scrolls the top 2 cells.

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    isScrolling = true
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let startScrollingOffset = 88.0
    if (scrollView.contentOffset.y < CGFloat(startScrollingOffset)) {
        // moved to top
        isScrollDown = false
    } else if (scrollView.contentOffset.y > CGFloat(startScrollingOffset)) {
        // moved to bottom
        isScrollDown = true
    } else {
        // didn't move
    }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if isScrollDown == false {
        return
    }
}


问:
Getting 'BadTokenException: Unable to add window' when trying to show Facebook dialog - Android
I'm getting a Bad Token Exception when trying to show the publish on wall dialog from the Facebook SDK(It happens every 2 times I run the app).

I have a 'publish' button, and its job is to show the dialog if the user is logged in to his FB account, or show the login dialog(and then immediately show the 'post on wall' dialog) if the user isn't logged in to his account.

Here's the on click listener of the Publish button -

```<code>    mPostButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if(mLoginButton.getVisibility() == 0)
                postOnWall();
            else
                mLoginButton.performClick();
        }
    });
</code>```

Here's the onAuthSucceed() listener -

```<code>public void onAuthSucceed() {
    postOnWall();
}
</code>```

Here's the PostOnWall function(which shows the publish dialog) -

```<code> public void postOnWall()
 {
    Bundle params = new Bundle();
    params.putString("name", FBname);
    params.putString("link", FBlink);
    params.putString("description", FBdescription);
    params.putString("picture", FBpicture);
    con = this;
    mFacebook.dialog(con, "feed", params, new SampleDialogListener());
 }
</code>```

Here's the log of the error -

```<code> 05-05 16:25:09.601: WARN/WindowManager(109): Attempted to add application window with unknown token HistoryRecord{405416b0 android.alco/.do_drive}.  Aborting.
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@405db9f8 is not valid; is your activity running?
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.ViewRoot.setView(ViewRoot.java:527)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.app.Dialog.show(Dialog.java:241)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at com.facebook.android.Facebook.dialog(Facebook.java:622)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.do_drive.postOnWall(do_drive.java:258)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.do_drive$SampleAuthListener.onAuthSucceed(do_drive.java:172)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.SessionEvents.onLoginSuccess(SessionEvents.java:78)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.LoginButton$LoginDialogListener.onComplete(LoginButton.java:100)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at com.facebook.android.Facebook$1.onComplete(Facebook.java:308)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at com.facebook.android.FbDialog$FbWebViewClient.shouldOverrideUrlLoading(FbDialog.java:133)
</code>```

I've looked all over and I can't find a solution.

EDIT - This only happens when the user is not logged in. In that case, he presses the 'publish' button, logs in, and then the 'postOnWall' function is called, which generates the error. I'm working on it for 2 days now, and couldn't find anything about it.

Thanks!

答:
Facing the same issue. As far as I can tell, from googling, its to do with your activity sometimes not being ready when the Facebook login activity returns its result. Why? No clue.

But I think this will work better: Define a flag in your class, set the flag in the AuthListener, and show the alert in the onStart if flag is set. Then you will for sure be in the comfort of your own activity:

```<code>private boolean authSuccess = false;
</code>```

...

```<code>public class SampleAuthListener implements AuthListener {
    authSuccess = true;
</code>```

...

```<code>protected void onStart() {
    super.onStart();
    if (authSuccess) {
        alert.show();
    }
}
</code>```

Disclaimer: I have very little Java/Android experience.

ContentLicense: CC BY-SA 3.0

Body:
I'm getting a Bad Token Exception when trying to show the publish on wall dialog from the Facebook SDK(It happens every 2 times I run the app).

I have a 'publish' button, and its job is to show the dialog if the user is logged in to his FB account, or show the login dialog(and then immediately show the 'post on wall' dialog) if the user isn't logged in to his account.

Here's the on click listener of the Publish button -

    mPostButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if(mLoginButton.getVisibility() == 0)
                postOnWall();
            else
                mLoginButton.performClick();
        }
    });

Here's the onAuthSucceed() listener -

public void onAuthSucceed() {
    postOnWall();
}

Here's the PostOnWall function(which shows the publish dialog) -

 public void postOnWall()
 {
    Bundle params = new Bundle();
    params.putString("name", FBname);
    params.putString("link", FBlink);
    params.putString("description", FBdescription);
    params.putString("picture", FBpicture);
    con = this;
    mFacebook.dialog(con, "feed", params, new SampleDialogListener());
 }

Here's the log of the error -

 05-05 16:25:09.601: WARN/WindowManager(109): Attempted to add application window with unknown token HistoryRecord{405416b0 android.alco/.do_drive}.  Aborting.
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@405db9f8 is not valid; is your activity running?
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.ViewRoot.setView(ViewRoot.java:527)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.app.Dialog.show(Dialog.java:241)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at com.facebook.android.Facebook.dialog(Facebook.java:622)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.do_drive.postOnWall(do_drive.java:258)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.do_drive$SampleAuthListener.onAuthSucceed(do_drive.java:172)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.SessionEvents.onLoginSuccess(SessionEvents.java:78)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at android.alco.LoginButton$LoginDialogListener.onComplete(LoginButton.java:100)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at com.facebook.android.Facebook$1.onComplete(Facebook.java:308)
 05-05 16:25:27.292: ERROR/AndroidRuntime(20089):     at com.facebook.android.FbDialog$FbWebViewClient.shouldOverrideUrlLoading(FbDialog.java:133)

I've looked all over and I can't find a solution.

EDIT - This only happens when the user is not logged in. In that case, he presses the 'publish' button, logs in, and then the 'postOnWall' function is called, which generates the error. I'm working on it for 2 days now, and couldn't find anything about it.

Thanks!

Body:
Facing the same issue. As far as I can tell, from googling, its to do with your activity sometimes not being ready when the Facebook login activity returns its result. Why? No clue.

But I think this will work better: Define a flag in your class, set the flag in the AuthListener, and show the alert in the onStart if flag is set. Then you will for sure be in the comfort of your own activity:

private boolean authSuccess = false;

...

public class SampleAuthListener implements AuthListener {
    authSuccess = true;

...

protected void onStart() {
    super.onStart();
    if (authSuccess) {
        alert.show();
    }
}

Disclaimer: I have very little Java/Android experience.


问:
ORA-24805:LOB type mismatch
Let there be table A(text_1 varchar2(4000 CHAR), text_2 varchar(4000 CHAR))
And here is the select for this:

```<code>SELECT sys.dbms_crypto.hash(empty_clob() || text_1 || text_2, 2)  from A;
</code>```

I am getting error 24805. I am expecting casting text_1 and text_2 to  CLOB , and connecting to each other. After that I need to get hash_code using function below. This code will also be part of PL/SQL block ( part of insert statement in function).
If I will use this:

```<code>SELECT sys.dbms_crypto.hash(to_clob('') || text_1 || text_2, 2)  from A;
</code>```

Everything is ok now. So, what was the problem?

```<code> create table A(text_1 varchar2(4000 CHAR), text_2 varchar2(4000 CHAR));
 insert into A(text_1,text_2)values ('test1','test2');
 commit;
</code>```

Here is an example of creating data for A.

答:
You can use TO_CLOB for concatenate your char based columns. Then use CONCAT which seems can work with CLOB. Try below.</p>

```<code>SELECT DBMS_CRYPTO.HASH(CONCAT(TO_CLOB (TEXT_1) , TO_CLOB (TEXT_2)), 2)  FROM A;
</code>```

Title: ORA-24805:LOB type mismatch

Body:
Let there be table A(text_1 varchar2(4000 CHAR), text_2 varchar(4000 CHAR))
And here is the select for this:

SELECT sys.dbms_crypto.hash(empty_clob() || text_1 || text_2, 2)  from A;

I am getting error 24805. I am expecting casting text_1 and text_2 to  CLOB , and connecting to each other. After that I need to get hash_code using function below. This code will also be part of PL/SQL block ( part of insert statement in function).
If I will use this:

SELECT sys.dbms_crypto.hash(to_clob('') || text_1 || text_2, 2)  from A;

Everything is ok now. So, what was the problem?

 create table A(text_1 varchar2(4000 CHAR), text_2 varchar2(4000 CHAR));
 insert into A(text_1,text_2)values ('test1','test2');
 commit;

Here is an example of creating data for A.

Body:
You can use TO_CLOB for concatenate your char based columns. Then use CONCAT which seems can work with CLOB. Try below.

SELECT DBMS_CRYPTO.HASH(CONCAT(TO_CLOB (TEXT_1) , TO_CLOB (TEXT_2)), 2)  FROM A;


问:
Why my for loop is running one extra iteration in R?
I am trying to run the following simple code in R but the for loop runs one extra iteration and I am not able to figure out the reason behind it. Could you please help me with that?

fun <- function(x) {
  y <- as.character(0)
  for (i in 1:length(x)) {
    if (x[i] == "NO") {
      y[i] <- c("Its a NO")
      y <- append(y, y[i])
    } else if (x[i] == "YES") {
      y[i] <- c("Its a YES")
      y <- append(y, y[i])
    } else {
      y[i] <- c("Don't know")
      y <- append(y, y[i])
    }
  }
  return(y)
}

a <- c("YES","NA", "NO")

fun(a)
```

Thanks a lot in advance.

答:
For loops in R run from start to end inclusive.

```<code>for (i in start:end)
</code>```

Change it to:

```<code>for (i in 1:(length(x)-1)) {
</code>```

Body:
I am trying to run the following simple code in R but the for loop runs one extra iteration and I am not able to figure out the reason behind it. Could you please help me with that?

fun <- function(x) {
  y <- as.character(0)
  for (i in 1:length(x)) {
    if (x[i] == "NO") {
      y[i] <- c("Its a NO")
      y <- append(y, y[i])
    } else if (x[i] == "YES") {
      y[i] <- c("Its a YES")
      y <- append(y, y[i])
    } else {
      y[i] <- c("Don't know")
      y <- append(y, y[i])
    }
  }
  return(y)
}

a <- c("YES","NA", "NO")

fun(a)

Thanks a lot in advance.

Body:
For loops in R run from start to end inclusive.

for (i in start:end)

Change it to:

for (i in 1:(length(x)-1)) {


问:
How to put green box below yellow box in flutter layout?
I am trying to learn flutter and I am using the course from appbrewery.co and in that course I've got a layout challenge in which I have to make a layout according to this picture:

https://drive.google.com/uc?export=download&id=1k7oW5qVLJqzw_lEFsOFS_qKmkGjBX1pL

But I am not able to do it because I cannot move the green box below the yellow box. I am trying to do it, but not able to do it and they've not given any solution either. Can anyone look at my code and tell me what I am not able to get ?

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Row(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Container(
                height: 650,
                width: 90,
                color: Colors.red,
              ),
              SizedBox(width: 10),
              Container(
                height: 100,
                width: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                width: 100,
                color: Colors.green,
              ),
              SizedBox(width: 10),
              Container(
                height: 650,
                width: 100,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Thanks.

答:
you also require:

```<code> mainAxisAlignment: MainAxisAlignment.center,
</code>```

after Column so that it is positioned horizontally.

Body:
I am trying to learn flutter and I am using the course from appbrewery.co and in that course I've got a layout challenge in which I have to make a layout according to this picture:

https://drive.google.com/uc?export=download&id=1k7oW5qVLJqzw_lEFsOFS_qKmkGjBX1pL

But I am not able to do it because I cannot move the green box below the yellow box. I am trying to do it, but not able to do it and they've not given any solution either. Can anyone look at my code and tell me what I am not able to get ?

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Row(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Container(
                height: 650,
                width: 90,
                color: Colors.red,
              ),
              SizedBox(width: 10),
              Container(
                height: 100,
                width: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                width: 100,
                color: Colors.green,
              ),
              SizedBox(width: 10),
              Container(
                height: 650,
                width: 100,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Thanks.

Body:
you also require:

 mainAxisAlignment: MainAxisAlignment.center,

after Column so that it is positioned horizontally.


问:
Copy files to directory if they are not in another directory
I have four files file1, file2, file3, file4.

A directory /All contains all four files, a directory /A contains file1, file2. Now I want to copy the rest file3, file4 to another directory /B. How can I do this in the command line?

Thank you for the help.

Body: find ./All/ -type f -exec bash -c '[ ! -e "./A/$(basename "$0")" ] && cp "$0" ./B/' '{}' \;


问:
Is there a "correct" file name for an .ics file?
There are numerous implementations that default to near meaningless names (like "calendar.ics" "my appointment.ics") or no name at all. If it is in RFC 5545, I missed it. Is there another specification that is appropriate?

Is there a specification or authoritative best practice that says what the file name should be?

答:
I don't think there is one, on the caldav side it's mostly a generated UUID or something similar.

Quoting Caldav's RFC 4791 - section 5.3.2:

Clients populate calendar collections with calendar object resources.
The URL for each calendar object resource is entirely arbitrary and
does not need to bear a specific relationship to the calendar object
resource's iCalendar properties or other metadata.  New calendar
object resources MUST be created with a PUT request targeted at an
unmapped URI.  A PUT request targeted at a mapped URI updates an
existing calendar object resource.

This is an example bellow that section:

```<code>PUT /home/lisa/calendars/events/qwue23489.ics HTTP/1.1
   If-None-Match: *
   Host: cal.example.com
   Content-Type: text/calendar
   Content-Length: xxxx
   ...
</code>```

Even when you are sending an .ics file from Mac's calendar it just appends a date and time of the export to the name (iCal-20200528-202500.ics). So it can be whatever you want it to be.

Body:
I don't think there is one, on the caldav side it's mostly a generated UUID or something similar.

Quoting Caldav's RFC 4791 - section 5.3.2:

Clients populate calendar collections with calendar object resources.
The URL for each calendar object resource is entirely arbitrary and
does not need to bear a specific relationship to the calendar object
resource's iCalendar properties or other metadata.  New calendar
object resources MUST be created with a PUT request targeted at an
unmapped URI.  A PUT request targeted at a mapped URI updates an
existing calendar object resource.

This is an example bellow that section:

PUT /home/lisa/calendars/events/qwue23489.ics HTTP/1.1
   If-None-Match: *
   Host: cal.example.com
   Content-Type: text/calendar
   Content-Length: xxxx
   ...

Even when you are sending an .ics file from Mac's calendar it just appends a date and time of the export to the name (iCal-20200528-202500.ics). So it can be whatever you want it to be.


答:
One option is to initialize 'y' as the length of 'x' and then remove the append

fun <- function(x) {
  y <- character(length(x))
  for (i in seq_along(x)) {
    y[i] <- if (x[i] == "NO") {
      c("Its a NO")
    } else if (x[i] == "YES") {
      c("Its a YES")
    } else {
      c("Don't know")
    }
  }
  return(y)
}

a <- c("YES","NA", "NO")

fun(a)
#[1] "Its a YES"  "Don't know" "Its a NO"
```

Title: Why my for loop is running one extra iteration in R?


问:
What's the best way to test WCF services?
I've used this tool that microsoft ships with visual studio because it's quick and dirty

http://msdn.microsoft.com/en-us/library/bb552364.aspx

But it's kinda clunky and hard to work with.  Are there any other useful test clients out there that you use and don't require creating a new visual studio project and compiling code?

EDIT: I'm looking more for a graphical test tool that I can use to do quick ad-hoc tests of systems in our different environments without having to write a bunch different tests.

答: Well I end up writing unit tests in MS test. Before each test the service is hosted by the test assembly, and ripped down afterwards. Sure it's not unit testing, so purists will shudder, but it does mean I can run tests as often as I like.</p>

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Nick

OwnerDisplayName: blowdart


问:
Detect Request sent from Postman
I want to make a request to verify people's ID using laravel. Since it's very credential, I want to make it available only if they verify it from their mobiles.

So it must be prevented that the IDs are verified from postman request.

Is there a way to detect that a request is sent from postman or not?

Any idea would be very appreaciated :).

Thank you before

答:
So it must be prevented that the IDs are verified from postman request.
Is there a way to detect that a request is sent from postman or not?

Checking that it comes from Postman is easy for requests sent from Postman where the boxes are checked for Postman-Token and/or User-Agent:

So you would add a check for them in your backend, but then the attacker would not send the Postman-Token header and for the User-Agent we will just send exactly the same one your mobile app/browser sends, thus easily bypassing your checks. By the way Postman is not the only tool, others exist like Insomnia, and then you also need to remember that requests may also come from a Proxy like mitmproxy, burp, zap, charlie, and many others. Do you get the point... it's not feasible to rely on headers to identify what is doing the request.

I highlighted the word what because who is in the request for your API backend is not the same as what is doing it.

The Difference Between WHO and WHAT is Accessing the API Server

In an article I wrote, entitled Why Does Your Mobile App Need An Api Key? you can read more about the difference between who and what is accessing your API server, but i will I quote the following from it:

The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?

The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

So the who is the user of your API server that you will be able to Authenticate and Authorize access to the data, and the what is the software making that request in behalf of the user, your genuine web/mobile app, a tampered one, an automated script or someone manually poking around with your API via cURL, Postman or other similar tools.

By now I hope that you have enough knowledge to understand why the user(who) authentication is not the same as app(what) authentication/attestation.

POSSIBLE SOLUTIONS

I want to make a request to verify people's ID using laravel. Since it's very credential, I want to make it available only if they verify it from their mobiles.

It's not clear if you mean from a mobile browser or mobile app, but I will provide possible solutions for both.

For Mobile Apps

To learn how you can lock your API server to your mobile app I recommend you to read my answer to the question How to secure an API REST for mobile app? for the sections on Securing the API Server and A Possible Better Solution.

For web apps

Due to the nature of how the web was built, all you need is to hit F12 or inspect the page source, and then search for whatever you need to access the API server from another tool.

To learn some useful techniques to try that your API server only responds to requests coming from What you expect, your genuine web app, I invite you to read my answer to the question Secure api data from calls out of the app, specially the section dedicated to Defending the API Server.

DO YOU WANT TO GO THE EXTRA MILE?

I don't know if you already read some of the OWASP resources I am about to link, but in any response for a security question I like to reference the amazing work from the OWASP foundation ;)

For Web Apps

OWASP Web Top 10 Risks

The OWASP Top 10 is a powerful awareness document for web application security. It represents a broad consensus about the most critical security risks to web applications. Project members include a variety of security experts from around the world who have shared their expertise to produce this list.

The Web Security Testing Guide:

The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.

For Mobile Apps

OWASP Mobile Security Project - Top 10 risks

The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.

OWASP - Mobile Security Testing Guide:

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

For APIS

OWASP API Security Top 10

The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.

Title: Detect Request sent from Postman


问:
Sort an array to have specific items first in the array
I've got an array as such:

```<code>[{flag: true, other: 1},
 {flag: true, other: 2},
 {flag: false, other: 3},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6},
 {flag: false, other: 7}]
</code>```

I want to have this:

```<code>[{flag: false, other: 3},
 {flag: false, other: 7},
 {flag: true, other: 1},
 {flag: true, other: 2},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6}]
</code>```

Basically I want that if array[2].flag === false (or any other value I choose) the matching element gets placed first in the array, but after previous matching elements.
The elements that do not match, remain in the same order they were in originally.

Order of appearance is important.

How to do this best in JavaScript?

答:
One solution can be to sort the array on the basis of flag and then by the other

var a = [{flag: true, other: 1},
 {flag: true, other: 2},
 {flag: false, other: 3},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6},
 {flag: false, other: 7}];

a.sort((a, b)=> a.flag - b.flag).sort((a,b) => a.other - b.other);```

Body:
I've got an array as such:

[{flag: true, other: 1},
 {flag: true, other: 2},
 {flag: false, other: 3},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6},
 {flag: false, other: 7}]

I want to have this:

[{flag: false, other: 3},
 {flag: false, other: 7},
 {flag: true, other: 1},
 {flag: true, other: 2},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6}]

Basically I want that if array[2].flag === false (or any other value I choose) the matching element gets placed first in the array, but after previous matching elements.
The elements that do not match, remain in the same order they were in originally.

Order of appearance is important.

How to do this best in JavaScript?


问:
A problem involving correlated subqueries
The problem at hand, - Get pairs of PC models with identical speeds and the same RAM capacity. Each resulting pair should be displayed only once, i.e. (i, j) but not (j, i).
Result set: model with the bigger number, model with the smaller number, speed, and RAM.

```<code>Select a.model,model, speed, hd from pc a
where (a.speed in (select speed from pc where model<>a.model and `
a.speed=speed) and a.hd in(select hd from pc  where a.model<>model and a.hd=hd))
</code>```

I tried numerous ways, this is just one of them, the query resulted in identical models and every model had identical speed.

Here is database schema:

The database scheme consists of four tables:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)

答:
This worked best for me. Hope this helps</p>

```<code>select distinct (A.model),
B.model,
A.speed,
A.ram from pc A
join
pc B on A.speed=B.speed and A.ram=B.ram where A.model>B.model
</code>```

Body:
The problem at hand, - Get pairs of PC models with identical speeds and the same RAM capacity. Each resulting pair should be displayed only once, i.e. (i, j) but not (j, i).
Result set: model with the bigger number, model with the smaller number, speed, and RAM.

Select a.model,model, speed, hd from pc a
where (a.speed in (select speed from pc where model<>a.model and `
a.speed=speed) and a.hd in(select hd from pc  where a.model<>model and a.hd=hd))

I tried numerous ways, this is just one of them, the query resulted in identical models and every model had identical speed.

Here is database schema:

The database scheme consists of four tables:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)

Body:
This worked best for me. Hope this helps

select distinct (A.model),
B.model,
A.speed,
A.ram from pc A
join
pc B on A.speed=B.speed and A.ram=B.ram where A.model>B.model


问:
Cannot get pandas to open CSV [Python, Jupyter, Pandas]
OBJECTIVE

Using Jupyter notebooks, import a csv file for data manipulation

APPROACH

Import necessary libraries for statistical analysis (pandas, matplotlib, sklearn, etc.)

Import data set using pandas

Manipulate data

CODE

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")

import pandas as pd
from sklearn.cluster import KMeans

data = pd.read_csv("../data/walmart-stores.csv")

print(data)
</code>```

ERROR

```<code>OSError: File b'../data/walmart-stores.csv' does not exist
</code>```

FOLDER STRUCTURE

```<code>Anconda
  env
    kmean.ipynb
    data
      walmart-stores.csv
    (other folders [for anaconda env])
 (other folders)
</code>```

QUESTION(S)

The error clearly states that the csv file cannot be found. I imagine it has to do with the project running in an Anaconda environment, but I thought this was the purpose of Anaconda environments in the first place. Am I wrong?

After answering the question, are there any other suggestions on how I should structure my Jupyter Notebooks when using Anaconda?

NOTES: I am new to python, anaconda, and jupyter notebooks so please disregard are naivety/stupidity. Thank you!

答:
Fellow newbie here!
Try removing the "../" from your data location

Change

```<code>data = pd.read_csv("../data/walmart-stores.csv")
</code>```

to

```<code>data = pd.read_csv("data/walmart-stores.csv")
</code>```

Body:
OBJECTIVE

Using Jupyter notebooks, import a csv file for data manipulation

APPROACH

Import necessary libraries for statistical analysis (pandas, matplotlib, sklearn, etc.)

Import data set using pandas

Manipulate data

CODE

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")

import pandas as pd
from sklearn.cluster import KMeans

data = pd.read_csv("../data/walmart-stores.csv")

print(data)

ERROR

OSError: File b'../data/walmart-stores.csv' does not exist

FOLDER STRUCTURE

Anconda
  env
    kmean.ipynb
    data
      walmart-stores.csv
    (other folders [for anaconda env])
 (other folders)

QUESTION(S)

The error clearly states that the csv file cannot be found. I imagine it has to do with the project running in an Anaconda environment, but I thought this was the purpose of Anaconda environments in the first place. Am I wrong?

After answering the question, are there any other suggestions on how I should structure my Jupyter Notebooks when using Anaconda?

NOTES: I am new to python, anaconda, and jupyter notebooks so please disregard are naivety/stupidity. Thank you!

Body:
Fellow newbie here!
Try removing the "../" from your data location

Change

data = pd.read_csv("../data/walmart-stores.csv")

to

data = pd.read_csv("data/walmart-stores.csv")


问:
How to check if a string contains exactly two words in an SQL query?
I need to execute a simple SQL query that will only select those names that are made up of exactly two words</p>

```<code>SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>
</code>```

答:
You can use like and not like:

```<code>where name like '% %' and not like '% % %'
</code>```

Body:
I need to execute a simple SQL query that will only select those names that are made up of exactly two words

SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>

Body:
You can use like and not like:

where name like '% %' and not like '% % %'


问:
RPM: Can it do this?
New here.  I have a generalized question regarding something I'd like to do but am not familiar enough to know before I embark on a path I may not ever be able to complete.

I've developed a shell script and supporting shell code to install a vendor relational database product.  I'd like to wrap all this into RPM package that will operate primarily on AIX and Linux platforms.

Can I build an RPM package to take this vendor tar-ball and using my shell script install this vendor product?  There's no source or anything to compile, it's a tar-ball that would extract into a temp location (would love to use a ramdisk) then my script would spawn from the RPM and do all the remaining tasks like running the vendor installation program as well as many other things we do, prechecks, post-checks and validations.

Thanks

答:
you can do that, but it would be cleaner if you would:

extract the files and 'install' them at the correct location during the building of your rpm

run your pre/post checks upon installation

this way you don't need to package the whole tarball inside your rpm, and the final files belong to your rpm package. All files that you create in your %post scripts etc don't belong to your package, which is bad practice (since then they won't be removed when you uninstall the rpm package for example).

Title: RPM: Can it do this?


问:
what is this syntax error? I don't even know what the error is. I m just beginning
```<code>number = input("Please enter your number:")
number = int(number)
if number % 10 == 0 :
   print("Yes the number is a multiple of 10.")
elif :
    print("No the number is not a multiple of 10.")
else :
    print("Invalid number!")
</code>```

<p>this code gives the following output:  </p>

```<code>  File "multiple_10.py", line 5
elif :
     ^
SyntaxError: invalid syntax
</code>```

答:
The main problem is elif need a condition, but in your code that is missing

I don't know what condition is suitable for your code but I tried this and its working fine

```<code>number = input("Please enter your number:")
number = int(number)
number = number % 10
print(number)
if number == 0 :
   print("Yes the number is a multiple of 10.")
elif number > 0 :
    print("No the number is not a multiple of 10.")
else :
    print("Invalid number!")
</code>```

Body:
number = input("Please enter your number:")
number = int(number)
if number % 10 == 0 :
   print("Yes the number is a multiple of 10.")
elif :
    print("No the number is not a multiple of 10.")
else :
    print("Invalid number!")

this code gives the following output:

  File "multiple_10.py", line 5
elif :
     ^
SyntaxError: invalid syntax

Body:
The main problem is elif need a condition, but in your code that is missing

I don't know what condition is suitable for your code but I tried this and its working fine

number = input("Please enter your number:")
number = int(number)
number = number % 10
print(number)
if number == 0 :
   print("Yes the number is a multiple of 10.")
elif number > 0 :
    print("No the number is not a multiple of 10.")
else :
    print("Invalid number!")


问:
Ubuntu 16.04 - > ERROR: Couldn't connect to Docker daemon - you might need to run `docker-machine start default`
I am getting error on ubuntu 16.04

"ERROR: Couldn't connect to Docker daemon - you might need to run
  docker-    machine start default. "

when i run following command

```<code>sudo docker-compose up
</code>```

Can any one answer ?

答:
I had this same error 10 minutes ago and solved it by doing:

```<code>sudo snap remove docker
</code>```

when finished:

```<code>sudo snap install docker
</code>```

Problem solved.

Body:
I am getting error on ubuntu 16.04

"ERROR: Couldn't connect to Docker daemon - you might need to run
  docker-    machine start default. "

when i run following command

sudo docker-compose up

Can any one answer ?

Body:
I had this same error 10 minutes ago and solved it by doing:

sudo snap remove docker

when finished:

sudo snap install docker

Problem solved.


问:
Cloud Formation: Environment failed to launch as it entered Terminated state
I am building an elastic beanstalk environment. I get the above error when I run the template. I have added the IAM roles giving full EC2 access to cloud formation

```<code> Resources:
  TestApp:
    Type: 'AWS::ElasticBeanstalk::Application'
    Properties: {}
    Metadata:
      'AWS::CloudFormation::Designer':
        id: 53bb2af6-3a68-487a-8048-34f111147171

  EBE1RNK0:
    Type: 'AWS::ElasticBeanstalk::Environment'
    Properties:
      ApplicationName: !Ref TestApp
      Description: AWS Elastic Beanstalk Environment running Node Sample Application
      EnvironmentName: NodejsEnvironment
      SolutionStackName: 64bit Amazon Linux 2 v5.0.1 running Node.js 12
      OptionSettings:
        - Namespace: aws:autoscaling:launchconfiguration
          OptionName: InstanceType
          Value: t1.micro
</code>```

答:
Looking at the screen shot, it failed just after trying to access S3 - theres your suspect. AWS Docs say beanstalk will require access to S3, Xray and CloudWatch Logs and provide below example policy. Do your roles include these permissions?</p>

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "BucketAccess",
      "Action": [
        "s3:Get*",
        "s3:List*",
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:s3:::elasticbeanstalk-*",
        "arn:aws:s3:::elasticbeanstalk-*/*"
      ]
    },
    {
      "Sid": "XRayAccess",
      "Action": [
        "xray:PutTraceSegments",
        "xray:PutTelemetryRecords"
      ],
      "Effect": "Allow",
      "Resource": "*"
    },
    {
      "Sid": "CloudWatchLogsAccess",
      "Action": [
        "logs:PutLogEvents",
        "logs:CreateLogStream",
        "logs:DescribeLogStreams",
        "logs:DescribeLogGroups"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk*"
      ]
    }
  ]
}
</code>```

Body:
I am building an elastic beanstalk environment. I get the above error when I run the template. I have added the IAM roles giving full EC2 access to cloud formation

 Resources:
  TestApp:
    Type: 'AWS::ElasticBeanstalk::Application'
    Properties: {}
    Metadata:
      'AWS::CloudFormation::Designer':
        id: 53bb2af6-3a68-487a-8048-34f111147171

  EBE1RNK0:
    Type: 'AWS::ElasticBeanstalk::Environment'
    Properties:
      ApplicationName: !Ref TestApp
      Description: AWS Elastic Beanstalk Environment running Node Sample Application
      EnvironmentName: NodejsEnvironment
      SolutionStackName: 64bit Amazon Linux 2 v5.0.1 running Node.js 12
      OptionSettings:
        - Namespace: aws:autoscaling:launchconfiguration
          OptionName: InstanceType
          Value: t1.micro

Body:
Looking at the screen shot, it failed just after trying to access S3 - theres your suspect. AWS Docs say beanstalk will require access to S3, Xray and CloudWatch Logs and provide below example policy. Do your roles include these permissions?

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "BucketAccess",
      "Action": [
        "s3:Get*",
        "s3:List*",
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:s3:::elasticbeanstalk-*",
        "arn:aws:s3:::elasticbeanstalk-*/*"
      ]
    },
    {
      "Sid": "XRayAccess",
      "Action": [
        "xray:PutTraceSegments",
        "xray:PutTelemetryRecords"
      ],
      "Effect": "Allow",
      "Resource": "*"
    },
    {
      "Sid": "CloudWatchLogsAccess",
      "Action": [
        "logs:PutLogEvents",
        "logs:CreateLogStream",
        "logs:DescribeLogStreams",
        "logs:DescribeLogGroups"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk*"
      ]
    }
  ]
}


问:
Why is the width of the table row (tr) of a table element not working, but the height is?
Here's my code:

.table1 {
  background-color: gray;
  display: flex;
  justify-content: ;
  align-items: ;
  height: 400px;
  margin-left: 40px;
  padding-left: ;
}

.table1 tr {
  background-color: blue;
  height: 50px;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table1">

  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>

  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>

  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>

</table></code>```

Why is it that i can change the height of the "TR" but i can't change the width?

And yes, i know i can change the width using padding on the parent block, but why is it not working by just changing the width of the TR elements itself like it does for the height?

答:
Try set flex on tbody with flex-direction: column as follows:

.table1 tbody {
  background-color: gray;
  display: flex;
  justify-content: ;
  align-items: ;
  height: 400px;
  margin-left: 40px;
  padding-left: ;
  flex-direction: column;
}

.table1 tr {
  background-color: blue;
  height: 50px;
}
.table1 tr td, .table1 tr th {
  width: 150px;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table1">

  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>

  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>

  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>

</table></code>```

Please note that I've just added width to td and th as well.

Body:
Here's my code:

.table1 {
  background-color: gray;
  display: flex;
  justify-content: ;
  align-items: ;
  height: 400px;
  margin-left: 40px;
  padding-left: ;
}

.table1 tr {
  background-color: blue;
  height: 50px;
  width: 50px;
}

    First Name
    Last Name
    Age

    Jill
    Smith
    50

    Eve
    Jackson
    94

Why is it that i can change the height of the "TR" but i can't change the width?

And yes, i know i can change the width using padding on the parent block, but why is it not working by just changing the width of the TR elements itself like it does for the height?

Body:
Try set flex on tbody with flex-direction: column as follows:

.table1 tbody {
  background-color: gray;
  display: flex;
  justify-content: ;
  align-items: ;
  height: 400px;
  margin-left: 40px;
  padding-left: ;
  flex-direction: column;
}

.table1 tr {
  background-color: blue;
  height: 50px;
}
.table1 tr td, .table1 tr th {
  width: 150px;
  text-align: left;
}

<table class="table1">

  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>

  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>

  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>

</table>

Please note that I've just added width to td and th as well.


问:
How to get data out of an Arraylist
So in a previous quesiton I asked how i could merge multiple array list into one array list.

This answer worked (also listed below). However, I am having issues getting the records out.  How do I get the data out of this multi dimensional arraylist.  For example, what if I wanted to get just address out?

```<code>ArrayList Names = new ArrayList();
ArrayList Phone = new ArrayList();
ArrayList Address = new ArrayList();
ArrayList res = new ArrayList();
for(int i=0; i<Names.Count; i++)
{
  res.Add(new string[]{Names[i].ToString(), Phone[i].ToString(), Address[i].ToString()});
}
</code>```

答:
Personally, I would make this a struct.

```<code>public struct Record
{
  public String Name;
  public String Telephone;
  public String Address;
}
</code>```

And push the information in to the structs and then re-reference them. Something like:

```<code>ArrayList records = new ArrayList();
for (...) {
  records.Add(new Record(){
    Name = Names[i].ToString(),
    Telephone = Phone[i].ToString(),
    Address = Address[i].ToString()
  });
}
...
Console.WriteLine(records[0].Address);
</code>```

Title: How to get data out of an Arraylist

Body:
So in a previous quesiton I asked how i could merge multiple array list into one array list.

This answer worked (also listed below). However, I am having issues getting the records out.  How do I get the data out of this multi dimensional arraylist.  For example, what if I wanted to get just address out?

ArrayList Names = new ArrayList();
ArrayList Phone = new ArrayList();
ArrayList Address = new ArrayList();
ArrayList res = new ArrayList();
for(int i=0; i<Names.Count; i++)
{
  res.Add(new string[]{Names[i].ToString(), Phone[i].ToString(), Address[i].ToString()});
}

Body:
Personally, I would make this a struct.

public struct Record
{
  public String Name;
  public String Telephone;
  public String Address;
}

And push the information in to the structs and then re-reference them. Something like:

ArrayList records = new ArrayList();
for (...) {
  records.Add(new Record(){
    Name = Names[i].ToString(),
    Telephone = Phone[i].ToString(),
    Address = Address[i].ToString()
  });
}
...
Console.WriteLine(records[0].Address);


问:
How to access specific element in json and compare the values
I am new to json and coding. I want to read a json file and flag the value in "data" to check if the value is below 50 (in python). I do not know how to access specific values and convert them to int.

Below is my code and error:

```<code>input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

for row in var:
    if input["data"] < 50:
        print(input["data"])

Error:
TypeError: string indices must be integers.
</code>```

答:
The problem here (lines 6 and 7) is that you are referencing a string and not the JSON object.
The code below fix this issue.</p>

```<code>import json

input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

if var["data"] < 50:
    print(var["data"])
</code>```

Body:
I am new to json and coding. I want to read a json file and flag the value in "data" to check if the value is below 50 (in python). I do not know how to access specific values and convert them to int.

Below is my code and error:

input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

for row in var:
    if input["data"] < 50:
        print(input["data"])

Error:
TypeError: string indices must be integers.

Body:
The problem here (lines 6 and 7) is that you are referencing a string and not the JSON object.
The code below fix this issue.

import json

input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

if var["data"] < 50:
    print(var["data"])


问:
How to restart a loop on exception
I have this code:

```<code>for i in range(n):
    for v in range (m):
        # code
        try:
            # more code
        except IndexError:
            os.system('python "Example.py"')
</code>```

os.system('python "Example.py"') allows me to reinitialize the entire code, but what I really want to do is to go back right before the for v in range(m): part and start that loop again.
How can I do this? Is there any other way to do that instead of adding a function? If not, how can I code that function?

答:
Slightly neater than Gzegzor's example.</p>

```<code>for i in range(n):
    v=0
    while (v < m):
        # code
        try:
            # more code
        except IndexError:
            continue
        v += 1
</code>```

Title: How to restart a loop on exception

Body:
I have this code:

for i in range(n):
    for v in range (m):
        # code
        try:
            # more code
        except IndexError:
            os.system('python "Example.py"')

os.system('python "Example.py"') allows me to reinitialize the entire code, but what I really want to do is to go back right before the for v in range(m): part and start that loop again.
How can I do this? Is there any other way to do that instead of adding a function? If not, how can I code that function?

Body:
Slightly neater than Gzegzor's example.

for i in range(n):
    v=0
    while (v < m):
        # code
        try:
            # more code
        except IndexError:
            continue
        v += 1


答:
Not added extra things just solve your error which you are getting.</p>

```<code>import json
input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

print(var)
for row in var:
    print(row)
    if var["data"] < 50:
        print(var["data"])

</code>```

Title: How to access specific element in json and compare the values

Body:
Not added extra things just solve your error which you are getting.

import json
input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

print(var)
for row in var:
    print(row)
    if var["data"] < 50:
        print(var["data"])


问:
How do I make sure that a button is not pressed down in C#?
So I'm currently making a game in C# and I've added the ability sprint by pressing and holding left shift but the problem is that I don't want the player to be able to sprint while crouching which can happen at the moment so long as the are holding down both left shift and left control. I've tried 'GetButtonUp' and 'GetButtonDown' but they don't work at all. Here is my current sprint script with the issue:

```<code>public class AdvancedMovement : MonoBehaviour
{
    //Variables;
    PlayerMovement basicMovementScript;
    public float speedBoost = 10f;

    // Start is called before the first frame update
    void Start()
    {
        basicMovementScript = GetComponent<PlayerMovement>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.LeftShift))
            beginSprint();
        else if (Input.GetKeyUp(KeyCode.LeftShift))
            endSprint();
    }

    private void beginSprint()
    {
        basicMovementScript.speed += speedBoost;
    }

    private void endSprint()
    {
        basicMovementScript.speed -= speedBoost;
    }
}
</code>```

I would greatly appreciate some help.
Thanks.

答:
Input.GetKeyDown and Input.GetKeyUp are only called once, and that's when the action is made and the next frame is rendered.

If by any misfortune that specific frame is skipped, either for performance or debugging reasons, they could lead to unexpected behavior. which in your case could possibly translate into endSprint being called without the Input.GetKeyDown(KeyCode.LeftShift) being detected as an example.

What I suggest is that you use Input.GetKey instead, which is called at every update, so long as the Key is held down.

In your case, you could do:

if (Input.GetKeyDown(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol)) which will make sure the Left Ctrl Key is not held down.

What I would also do in a similar situation, instead of using Input.GetKeyDown(KeyCode.LeftShift) I would create a flag _isSprinting and use it in a way similar to the following:

```<code>void Update()
{

    if (!_isSprinting && Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol)))
    {
        beginSprint();

        _isSprinting = true;
    }

    if (_isSprinting && !Input.GetKey(KeyCode.LeftShift))
    {
        endSprint();

        _isSprinting = false;
    }
}
</code>```

Body:
So I'm currently making a game in C# and I've added the ability sprint by pressing and holding left shift but the problem is that I don't want the player to be able to sprint while crouching which can happen at the moment so long as the are holding down both left shift and left control. I've tried 'GetButtonUp' and 'GetButtonDown' but they don't work at all. Here is my current sprint script with the issue:

public class AdvancedMovement : MonoBehaviour
{
    //Variables;
    PlayerMovement basicMovementScript;
    public float speedBoost = 10f;

    // Start is called before the first frame update
    void Start()
    {
        basicMovementScript = GetComponent<PlayerMovement>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.LeftShift))
            beginSprint();
        else if (Input.GetKeyUp(KeyCode.LeftShift))
            endSprint();
    }

    private void beginSprint()
    {
        basicMovementScript.speed += speedBoost;
    }

    private void endSprint()
    {
        basicMovementScript.speed -= speedBoost;
    }
}

I would greatly appreciate some help.
Thanks.

Body:
Input.GetKeyDown and Input.GetKeyUp are only called once, and that's when the action is made and the next frame is rendered.

If by any misfortune that specific frame is skipped, either for performance or debugging reasons, they could lead to unexpected behavior. which in your case could possibly translate into endSprint being called without the Input.GetKeyDown(KeyCode.LeftShift) being detected as an example.

What I suggest is that you use Input.GetKey instead, which is called at every update, so long as the Key is held down.

In your case, you could do:

if (Input.GetKeyDown(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol)) which will make sure the Left Ctrl Key is not held down.

What I would also do in a similar situation, instead of using Input.GetKeyDown(KeyCode.LeftShift) I would create a flag _isSprinting and use it in a way similar to the following:

void Update()
{

    if (!_isSprinting && Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol)))
    {
        beginSprint();

        _isSprinting = true;
    }

    if (_isSprinting && !Input.GetKey(KeyCode.LeftShift))
    {
        endSprint();

        _isSprinting = false;
    }
}


答:
Assuming this is .NET 2.0 and not anything later so you have to stick with ArrayList, I would just introduce a new class to hold your information.

```<code>public class Person
{
    private string _name;
    public string Name { get { return _name; } }
    public Person(string name, string phone, string adress)
    {
        _name = name;
        ...
    }
}
</code>```

Then you can populate instances of this class in your arraylist and access its properties.

Title: How to get data out of an Arraylist

Body:
Assuming this is .NET 2.0 and not anything later so you have to stick with ArrayList, I would just introduce a new class to hold your information.

public class Person
{
    private string _name;
    public string Name { get { return _name; } }
    public Person(string name, string phone, string adress)
    {
        _name = name;
        ...
    }
}

Then you can populate instances of this class in your arraylist and access its properties.


问:
how to extract the contents of a strong tag using beautiful soup?
```<code> <li class="bg-blue">
 <img alt="Active Status" src="assets/images/icon-infected.png"/>
 <strong>83004</strong>
 <span>Active Cases</span>
</code>```

I need to extract the values inside the strong tag , how should I do that?

答:
Firstly you find the strong element and use text for getting the value. You can try it:

```<code>html_doc = """
<li class="bg-blue">
<img alt="Active Status" src="assets/images/icon-infected.png"/>
<strong>83004</strong>
<span>Active Cases</span>
"""

soup = BeautifulSoup(html_doc, 'lxml')

value = soup.find('strong').text
print(value)
</code>```

Body:
 83004
 Active Cases

I need to extract the values inside the strong tag , how should I do that?

Body:
Firstly you find the strong element and use text for getting the value. You can try it:

html_doc = """
<li class="bg-blue">
<img alt="Active Status" src="assets/images/icon-infected.png"/>
<strong>83004</strong>
<span>Active Cases</span>
"""

soup = BeautifulSoup(html_doc, 'lxml')

value = soup.find('strong').text
print(value)


问:
Close subnav once a different subnav is open with jQuery
Currently I have this working almost perfectly, but the user has the ability to open multiple sub-nav's at once, and I need any open sub-nav's to close when another one is open.

Basically, the jQuery that's beloe, I need to classes to be removed if a new sub-nav is clicked on, currently it only removes them if the same one is clicked.

HTML

```<code><nav class="st-menu" id="menu-4a">
    <ul>
        <li>
            <a href="#">Guidance Manual</a>
        </li>
        <li>
            <a href="#">Resource Directory</a><div class="toggle-arrow"><img src="/assets/images/chevron-up-solid.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">Stormwater Plan Review Resources</a></li>
                <li><a href="#">Pilot Projects</a></li>
                <li><a href="#">Proprietary Products</a></li>
                <li><a href="#">Additional Resources</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Stormwater 101</a><div class="toggle-arrow"><img src="/assets/images/chevron-up-solid.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">Regulations</a></li>
                <li><a href="#">Stormwater Management</a></li>
                <li><a href="#">Stormwater Billing & Retrofits</a></li>
                <li><a href="#">Green City, Clean Waters</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Contact Us</a><div class="toggle-arrow"><img src="/assets/images/chevron-up-solid.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">About Us</a></li>
                <li><a href="#">Development Review Contacts</a></li>
            </ul>
        </li>
    </ul>
</nav>
</code>```

jQuery

```<code>$(".toggle-arrow").click(function(){
    $(this).closest('li').find(".reg-subnav").toggleClass('open-sub');
    $(this).closest('li').find('.arrow-image').toggleClass("flip");
});
</code>```

答:
You can use siblings and select the elements with the class and remove them.

$("nav").on("click", ".toggle-arrow", function(){
    var currentLi = $(this).closest('li')
    currentLi.find(".reg-subnav").toggleClass('open-sub');
    currentLi.find('.toggle-arrow').toggleClass("flip");

    //clean up the other open elements
    var otherLis = currentLi.siblings()
    otherLis.find(".open-sub").removeClass('open-sub')
    otherLis.find(".flip").removeClass('flip')

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.reg-subnav {
  display: none;
}

.reg-subnav.open-sub {
  display: block;
}

img {
 width: 20px;
}

.toggle-arrow {
  position: relative;
  cursor: pointer;
  display: inline-block;
}

.toggle-arrow img {
  transform: rotateX(180deg);
  transition: transform 0.75s;
  transform-style: preserve-3d;
}

.toggle-arrow.flip img {
  transform: rotateY(0deg);
}</code>```

            Guidance Manual

            Resource Directory

Stormwater Plan Review Resources

Pilot Projects

Proprietary Products

Additional Resources

            Stormwater 101

Regulations

Stormwater Management

Stormwater Billing & Retrofits

Green City, Clean Waters

            Contact Us

About Us

Development Review Contacts

```

Body:
Currently I have this working almost perfectly, but the user has the ability to open multiple sub-nav's at once, and I need any open sub-nav's to close when another one is open.

Basically, the jQuery that's beloe, I need to classes to be removed if a new sub-nav is clicked on, currently it only removes them if the same one is clicked.

HTML

            Guidance Manual

            Resource Directory

Stormwater Plan Review Resources

Pilot Projects

Proprietary Products

Additional Resources

            Stormwater 101

Regulations

Stormwater Management

Stormwater Billing & Retrofits

Green City, Clean Waters

            Contact Us

About Us

Development Review Contacts

jQuery

$(".toggle-arrow").click(function(){
    $(this).closest('li').find(".reg-subnav").toggleClass('open-sub');
    $(this).closest('li').find('.arrow-image').toggleClass("flip");
});

Body:
You can use siblings and select the elements with the class and remove them.

$("nav").on("click", ".toggle-arrow", function(){
    var currentLi = $(this).closest('li')
    currentLi.find(".reg-subnav").toggleClass('open-sub');
    currentLi.find('.toggle-arrow').toggleClass("flip");

    //clean up the other open elements
    var otherLis = currentLi.siblings()
    otherLis.find(".open-sub").removeClass('open-sub')
    otherLis.find(".flip").removeClass('flip')

});

.reg-subnav {
  display: none;
}

.reg-subnav.open-sub {
  display: block;
}

img {
 width: 20px;
}

.toggle-arrow {
  position: relative;
  cursor: pointer;
  display: inline-block;
}

.toggle-arrow img {
  transform: rotateX(180deg);
  transition: transform 0.75s;
  transform-style: preserve-3d;
}

.toggle-arrow.flip img {
  transform: rotateY(0deg);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="st-menu" id="menu-4a">
    <ul>
        <li>
            <a href="#">Guidance Manual</a>
        </li>
        <li>
            <a href="#">Resource Directory</a><div class="toggle-arrow"><img src="https://image.flaticon.com/icons/svg/120/120906.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">Stormwater Plan Review Resources</a></li>
                <li><a href="#">Pilot Projects</a></li>
                <li><a href="#">Proprietary Products</a></li>
                <li><a href="#">Additional Resources</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Stormwater 101</a><div class="toggle-arrow"><img src="https://image.flaticon.com/icons/svg/120/120906.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">Regulations</a></li>
                <li><a href="#">Stormwater Management</a></li>
                <li><a href="#">Stormwater Billing & Retrofits</a></li>
                <li><a href="#">Green City, Clean Waters</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Contact Us</a><div class="toggle-arrow"><img src="https://image.flaticon.com/icons/svg/120/120906.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">About Us</a></li>
                <li><a href="#">Development Review Contacts</a></li>
            </ul>
        </li>
    </ul>
</nav>


问:
Custom page show blog posts on tag
Since I am not so great programming in PHP I wanted to ask my question here, hopefully you guys can help me out.

I'm building a WordPress website, this website has a custom page template like custom-single.php.

On that custom template I want to show posts filtered on a tag. And the tag is coming from a Angular value like so {{ctrl.name.tagname}} and yes ofcourse I've made a tag as well in WordPress.

The code must show max 5 posts (fully with title and ofcourse the content), after the posts it must show max 5 items which are older then 5 posts before, but then only with title using a bullet-list.

答:
If your aim is not to learn php but only to solve your problem in your wordpress related project; you can support your question with visuals.

If you say I don't want to deal with the problem, you can get support from any freelance software developer at an affordable price. Sometimes you will be happier soon with this method.

Title: Custom page show blog posts on tag


问:
Accurate method to add months in PHP 5.1?
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

```<code>date('Y-m-d',strtotime( '+1 month', strtotime('now')));
</code>```

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?

答:
It certainly is possible in PHP: Check the strtotime manual, especially this comment.

If you have a MySQL connection available, SELECT DATE_ADD( '2011-05-31', INTERVAL 1 MONTH ) would be less redundant since the (correct) functionality is already implemented without you having to implement it yourself.

Body:
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

date('Y-m-d',strtotime( '+1 month', strtotime('now')));

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?


问:
How to configure Caddy 2 in docker-compose file to do reverse proxy without a bind mounted Caddyfile?
I have a docker-compose file with two services:

my webapp, it exposes port 3000

caddy, it works as reverse proxy for my web app and gives HTTPS

It works fine if I use a bind mounted Caddyfile:

```<code>caddy:
    image: caddy:2.0.0-alpine
    ports:
      - 80:80
      - 443:443
    volumes:
      - caddy:/data
      - .Caddyfile:/etc/caddy/Caddyfile
</code>```

Caddy file is pretty simple:

```<code>my-domain.com {
    reverse_proxy my-app:3000
}

</code>```

But I'd like to deploy it on the server without uploading Caddyfile. I want to configure my docker-compose.yml something like this:

```<code>version: "3"

services:
  my-app:
    image: my-app
    expose:
      - 3000

  caddy:
    image: caddy:2
    ports:
      - 80:80
      - 443:443
    environment:
      - reverse_proxy_from=my-app:3000
      - reverse_proxy_to=my-domain.com
    volumes:
      - caddy:/data

volumes:
  caddy:

</code>```

Also maybe it's possible to do it via caddy API. When I tried to configure a reversy proxy on bare OS, it works. But when I tried to do it with docker (docker-compose exec caddy caddy reverse-proxy --from my-site.net --to my-app:3000), I got some unclear to me errors messages:

```<code>root@test:/xxx# docker-compose exec caddy caddy reverse-proxy --from my-site.net --to app:3000
2020/05/15 11:49:57.787 WARN    admin   admin endpoint disabled
2020/05/15 11:49:57.787 INFO    http    server is listening only on the HTTPS port but has no TLS connection policies; adding one to enable TLS {"server_name": "proxy", "https_port": 443}
2020/05/15 11:49:57.787 INFO    http    enabling automatic HTTP->HTTPS redirects    {"server_name": "proxy"}
2020/05/15 11:49:57 [INFO][cache:0xc000726820] Started certificate maintenance routine
2020/05/15 11:49:57.788 INFO    tls cleaned up storage units
reverse-proxy: loading new config: http app module: start: tcp: listening on :80: listen tcp :80: bind: address already in use
</code>```

答:
This might be of interest:

https://hub.docker.com/r/lucaslorentz/caddy-docker-proxy

Per the description in the github repo it references, how it works is it scans Docker metadata looking for labels indicating that the service or container should be exposed on caddy.

Then it generates an in memory Caddyfile with website entries and proxy directives pointing to each Docker service DNS name or container IP.

Every time a docker object changes, it updates the Caddyfile and triggers a caddy zero-downtime reload.

Body:
I have a docker-compose file with two services:

my webapp, it exposes port 3000

caddy, it works as reverse proxy for my web app and gives HTTPS

It works fine if I use a bind mounted Caddyfile:

caddy:
    image: caddy:2.0.0-alpine
    ports:
      - 80:80
      - 443:443
    volumes:
      - caddy:/data
      - .Caddyfile:/etc/caddy/Caddyfile

Caddy file is pretty simple:

my-domain.com {
    reverse_proxy my-app:3000
}

But I'd like to deploy it on the server without uploading Caddyfile. I want to configure my docker-compose.yml something like this:

version: "3"

services:
  my-app:
    image: my-app
    expose:
      - 3000

  caddy:
    image: caddy:2
    ports:
      - 80:80
      - 443:443
    environment:
      - reverse_proxy_from=my-app:3000
      - reverse_proxy_to=my-domain.com
    volumes:
      - caddy:/data

volumes:
  caddy:

Also maybe it's possible to do it via caddy API. When I tried to configure a reversy proxy on bare OS, it works. But when I tried to do it with docker (docker-compose exec caddy caddy reverse-proxy --from my-site.net --to my-app:3000), I got some unclear to me errors messages:

root@test:/xxx# docker-compose exec caddy caddy reverse-proxy --from my-site.net --to app:3000
2020/05/15 11:49:57.787 WARN    admin   admin endpoint disabled
2020/05/15 11:49:57.787 INFO    http    server is listening only on the HTTPS port but has no TLS connection policies; adding one to enable TLS {"server_name": "proxy", "https_port": 443}
2020/05/15 11:49:57.787 INFO    http    enabling automatic HTTP->HTTPS redirects    {"server_name": "proxy"}
2020/05/15 11:49:57 [INFO][cache:0xc000726820] Started certificate maintenance routine
2020/05/15 11:49:57.788 INFO    tls cleaned up storage units
reverse-proxy: loading new config: http app module: start: tcp: listening on :80: listen tcp :80: bind: address already in use


问:
Jwts.builder().setClaims() method converts list to list of LinkedHashMaps
I have a method that tries to extract information from a Jwt token to instantiate a UserDetails instance from. The method looks like this:

```<code>public UserDetails loadUserByAuthToken(String authToken){
    Claims claims = getClaimsFromToken(authToken);
    return JwtUserFactory.create(
            claims.get(CLAIM_KEY_USER_ID, Long.class),
              ....
            Collection<? extends GrantedAuthority>claims.get(CLAIM_KEY_GRANTED_AUTHORITIES, Collection.class),
    );
</code>```

Despite explicitly casting the list value from CLAIM_KEY_GRANTED_AUTHORITIES to (List<GrantedAuthority>) it still converts the list to a linked hashmap.

I've read here that when the type is not defined Jackson automatically converts a list to a linked hashmap. Resteasy converting List to LinkedHashMap
The thread is about resteasy but i think the same thing is happening in my code.
In this thread Class cast exception in JWT I've read that Jackson is also used for determining data types when extracting data from a jwt token.

The point is that i am declaring a type, namely List.class. Thats as specific as i can give it because List<GrantedAuthority>.class results in a compile error. When i log the content of the list in the console it looks like this:

[{authority=ROLE_USER}, {authority=ROLE_ADMIN}]

How can i prevent Jackson from implicitly converting the GrantedAuthorityList to a List of LinkedHashMap and avoid a class cast exception?

I am using jjwt version 0.9.0

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

Thank you

EDIT: Heres the getClaimsFromToken method

```<code>public Claims getClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        e.printStackTrace();
        claims = null;
    }
    return claims;
}
</code>```

答:
Well after doing some more research i've found out that there is no solution in my case. According to Baeldung https://www.baeldung.com/jackson-collection-array jackson will convert custom object lists to LinkedHashMap lists. There is a way around this using jackson ObjectMapper together with TypeReference, but that only works when the custom object has a default no-args constructor, which mine doesn't.

So my work around is this:

```<code>convertListOfLinkedHashMapsToSimpleGrantedAuthorityList(objectMapper.convertValue(claims.get(CLAIM_KEY_GRANTED_AUTHORITIES, ArrayList.class),
                        new TypeReference<List<LinkedHashMap<String, SimpleGrantedAuthority>>>() { }));

    private Set<? extends GrantedAuthority> convertListOfLinkedHashMapsToSimpleGrantedAuthorityList(List<LinkedHashMap<String, SimpleGrantedAuthority>> linkedHashMapList){
        return linkedHashMapList.stream().flatMap(linkedHashMap -> linkedHashMap.values().stream()).collect(Collectors.toSet());
    }
</code>```

Hope it will help anyone

Body:
I have a method that tries to extract information from a Jwt token to instantiate a UserDetails instance from. The method looks like this:

public UserDetails loadUserByAuthToken(String authToken){
    Claims claims = getClaimsFromToken(authToken);
    return JwtUserFactory.create(
            claims.get(CLAIM_KEY_USER_ID, Long.class),
              ....
            Collection<? extends GrantedAuthority>claims.get(CLAIM_KEY_GRANTED_AUTHORITIES, Collection.class),
    );

Despite explicitly casting the list value from CLAIM_KEY_GRANTED_AUTHORITIES to (List<GrantedAuthority>) it still converts the list to a linked hashmap.

I've read here that when the type is not defined Jackson automatically converts a list to a linked hashmap. Resteasy converting List to LinkedHashMap
The thread is about resteasy but i think the same thing is happening in my code.
In this thread Class cast exception in JWT I've read that Jackson is also used for determining data types when extracting data from a jwt token.

The point is that i am declaring a type, namely List.class. Thats as specific as i can give it because List<GrantedAuthority>.class results in a compile error. When i log the content of the list in the console it looks like this:

[{authority=ROLE_USER}, {authority=ROLE_ADMIN}]

How can i prevent Jackson from implicitly converting the GrantedAuthorityList to a List of LinkedHashMap and avoid a class cast exception?

I am using jjwt version 0.9.0

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

Thank you

EDIT: Heres the getClaimsFromToken method

public Claims getClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        e.printStackTrace();
        claims = null;
    }
    return claims;
}

Body:
Well after doing some more research i've found out that there is no solution in my case. According to Baeldung https://www.baeldung.com/jackson-collection-array jackson will convert custom object lists to LinkedHashMap lists. There is a way around this using jackson ObjectMapper together with TypeReference, but that only works when the custom object has a default no-args constructor, which mine doesn't.

So my work around is this:

convertListOfLinkedHashMapsToSimpleGrantedAuthorityList(objectMapper.convertValue(claims.get(CLAIM_KEY_GRANTED_AUTHORITIES, ArrayList.class),
                        new TypeReference<List<LinkedHashMap<String, SimpleGrantedAuthority>>>() { }));

    private Set<? extends GrantedAuthority> convertListOfLinkedHashMapsToSimpleGrantedAuthorityList(List<LinkedHashMap<String, SimpleGrantedAuthority>> linkedHashMapList){
        return linkedHashMapList.stream().flatMap(linkedHashMap -> linkedHashMap.values().stream()).collect(Collectors.toSet());
    }

Hope it will help anyone


问:
How do you change column name in csv file with linux on Mac
Simply just want to change few column names in a csv file and store it as it is using this code:

sed -i -e "1s/oldcolname/" -e "1s/newcolname/" xxx.csv.

But it does not work. I got the error message :

sed: 1: "1s/oldcolname/":unterminated substitute in regular expression.

Anyone knows how to rewrite it? Thanks!

答:
If you want to simply replace oldcolname with newcolname, here's a quick answer:

```<code>sed -i -e 's/oldcolname/newcolname/' your_file.csv
</code>```

Body:
If you want to simply replace oldcolname with newcolname, here's a quick answer:

sed -i -e 's/oldcolname/newcolname/' your_file.csv


问:
How do make a 2D interpolation in a table in Python?
I have a table of numbers, with two initial row and columns ( in Bold) which are values of CI and CII as input. my input can be a value between the values of these two, and based on that I should interpolate from the values of the table by crossing them.

so let's say , I should find the corresponding value from the table for CI = 0.33 which is between 0.3 and 0.35 on the Bolded first row and CII = 1.1.

Other questions on 2D interpolation did not really help me on this. Because I am using python add in in another software where I can not import scipty.interp2D.
I would be very thankfull if some solution would be suggested without the need to a specific library

I am not sure about the type of the interpolation to use. maybe linear. to give a better perspective, I plotted 3 arbitrary rows from the table, just taking the row and plotted against the sample number, it seems they have different behaviors over the samples. first ones increase, last ones are decreasing but never are a line :

答:
What kind of interpolation do you want? Polynomial? Exponentially piece-wise smooth? Is step-wise linear ok?

Assuming step-wise linear, you could just write up a function manually:

```<code># Sample data.
X    = [0,5,10] # Left to right, like in your table.
Y    = [0,2]    # Top to bottom, like in your table.
grid = [[1,2,4],[4,5,10]]

def f(x,y):
    # Find the vales that x and y are between.
    xi,yi = None,None
    for i,(x1,x2) in enumerate(zip(X[:-1],X[1:])):
        if x1 <= x <= x2:
            xi,w_x2,w_x1 = i,(x-x1)/(x2-x1),(x2-x)/(x2-x1)
            break
    for i,(y1,y2) in enumerate(zip(Y[:-1],Y[1:])):
        if y1 <= y <= y2:
            yi,w_y2,w_y1 = i,(y-y1)/(y2-y1),(y2-y)/(y2-y1)
            break
    if xi is None or yi is None:
        return False
        # You could add special cases to interpolate past the range if you would like.
    # Find the weighted average between the four corners.
    ave  = grid[yi][xi]    *w_y1*w_x1
    ave += grid[yi][xi+1]  *w_y1*w_x2
    ave += grid[yi+1][xi]  *w_y2*w_x1
    ave += grid[yi+1][xi+1]*w_y2*w_x2
    return ave

print(f(0,0),f(2.5,0),f(4,0),f(5,0),f(7.5,0),f(10,0))
print(f(0,1),f(2.5,1),f(4,1),f(5,1),f(7.5,1),f(10,1))
print(f(0,2),f(2.5,2),f(4,2),f(5,2),f(7.5,2),f(10,2))
</code>```

This could be done more efficiently with more information. For example, if you had consistent x_delta between your x values, you could skip the for loops. You could also skip the for loops if you use a SortedList from the sortedcontainers package. This could probably also be adapted for numpy if you wanted to use arrays instead of lists, etc.

You didn't provide me any working code or knowledge about modules you can use or algorithm you wanted, so I wrote this up without as best I could. :-)

Edit:

You shouldn't make people type out your data from a PNG image. Here is a small section, I can't type out more.

```<code>X    = [0,0.05,0.1,0.15,0.2]
Y    = [0.2,0.4]
grid = [[1,1.116,1.211,1.297,1.376],[1,1.094,1.174,1.248,1.319]]

...

print(f(0,0.2),f(0.025,0.2),f(0.05,0.2))
</code>```

Body:
What kind of interpolation do you want? Polynomial? Exponentially piece-wise smooth? Is step-wise linear ok?

Assuming step-wise linear, you could just write up a function manually:

# Sample data.
X    = [0,5,10] # Left to right, like in your table.
Y    = [0,2]    # Top to bottom, like in your table.
grid = [[1,2,4],[4,5,10]]

def f(x,y):
    # Find the vales that x and y are between.
    xi,yi = None,None
    for i,(x1,x2) in enumerate(zip(X[:-1],X[1:])):
        if x1 <= x <= x2:
            xi,w_x2,w_x1 = i,(x-x1)/(x2-x1),(x2-x)/(x2-x1)
            break
    for i,(y1,y2) in enumerate(zip(Y[:-1],Y[1:])):
        if y1 <= y <= y2:
            yi,w_y2,w_y1 = i,(y-y1)/(y2-y1),(y2-y)/(y2-y1)
            break
    if xi is None or yi is None:
        return False
        # You could add special cases to interpolate past the range if you would like.
    # Find the weighted average between the four corners.
    ave  = grid[yi][xi]    *w_y1*w_x1
    ave += grid[yi][xi+1]  *w_y1*w_x2
    ave += grid[yi+1][xi]  *w_y2*w_x1
    ave += grid[yi+1][xi+1]*w_y2*w_x2
    return ave

print(f(0,0),f(2.5,0),f(4,0),f(5,0),f(7.5,0),f(10,0))
print(f(0,1),f(2.5,1),f(4,1),f(5,1),f(7.5,1),f(10,1))
print(f(0,2),f(2.5,2),f(4,2),f(5,2),f(7.5,2),f(10,2))

This could be done more efficiently with more information. For example, if you had consistent x_delta between your x values, you could skip the for loops. You could also skip the for loops if you use a SortedList from the sortedcontainers package. This could probably also be adapted for numpy if you wanted to use arrays instead of lists, etc.

You didn't provide me any working code or knowledge about modules you can use or algorithm you wanted, so I wrote this up without as best I could. :-)

Edit:

You shouldn't make people type out your data from a PNG image. Here is a small section, I can't type out more.

X    = [0,0.05,0.1,0.15,0.2]
Y    = [0.2,0.4]
grid = [[1,1.116,1.211,1.297,1.376],[1,1.094,1.174,1.248,1.319]]

...

print(f(0,0.2),f(0.025,0.2),f(0.05,0.2))