问:
Optimize deep Q network with long episode
I am working on a problem for which we aim to solve with deep Q learning. However, the problem is that training just takes too long for each episode, roughly 83 hours. We are envisioning to solve the problem within, say, 100 episode.

So we are gradually learning a matrix (100 * 10), and within each episode, we need to perform 100*10 iterations of certain operations. Basically we select a candidate from a pool of 1000 candidates, put this candidate in the matrix, and compute a reward function by feeding the whole matrix as the input:

The central hurdle is that the reward function computation at each step is costly, roughly 2 minutes, and each time we update one entry in the matrix.

All the elements in the matrix depend on each other in the long term, so the whole procedure seems not suitable for some "distributed" system, if I understood correctly.

Could anyone shed some lights on how we look at the potential optimization opportunities here? Like some extra engineering efforts or so? Any suggestion and comments would be appreciated very much. Thanks.

======================= update of some definitions =================

0. initial stage:

a 100 * 10 matrix, with every element as empty

1. action space:

each step I will select one element from a candidate pool of 1000 elements. Then insert the element into the matrix one by one.

2. environment:

each step I will have an updated matrix to learn.

An oracle function F returns a quantitative value range from 5000 ~ 30000, the higher the better (roughly one computation of F takes 120 seconds).

This function F takes the matrix as the input and perform a very costly computation, and it returns a quantitative value to indicate the quality of the synthesized matrix so far.

This function is essentially used to measure some performance of system, so it do takes a while to compute a reward value at each step.

3. episode:

By saying "we are envisioning to solve it within 100 episodes", that's just an empirical estimation. But it shouldn't be less than 100 episode, at least.

4. constraints

Ideally, like I mentioned, "All the elements in the matrix depend on each other in the long term", and that's why the reward function F computes the reward by taking the whole matrix as the input rather than the latest selected element.

Indeed by appending more and more elements in the matrix, the reward could increase, or it could decrease as well.

5. goal

The synthesized matrix should let the oracle function F returns a value greater than 25000. Whenever it reaches this goal, I will terminate the learning step.

答:
Not a solution to your question, just some general thoughts that maybe are relevant:

One of the biggest obstacles to apply Reinforcement Learning in "real world" problems is the astoundingly large amount of data/experience required to achieve acceptable results. For example, OpenAI in Dota 2 game colletected the experience equivalent to 900 years per day. In the original Deep Q-network paper, in order to achieve a performance close to a typicial human, it was required hundres of millions of game frames, depending on the specific game. In other benchmarks where the input are not raw pixels, such as MuJoCo, the situation isn't a lot better. So, if you don't have a simulator that can generate samples (state, action, next state, reward) cheaply, maybe RL is not a good choice. On the other hand, if you have a ground-truth model, maybe other approaches can easily outperform RL, such as Monte Carlo Tree Search (e.g., Deep Learning for Real-Time Atari Game Play Using Offline Monte-Carlo Tree Search Planning or Simple random search provides a competitive approach to reinforcement learning). All these ideas a much more are discussed in this great blog post.

The previous point is specially true for deep RL. The fact of approximatting value functions or policies using a deep neural network with millions of parameters usually implies that you'll need a huge quantity of data, or experience.

And regarding to your specific question:

In the comments, I've asked a few questions about the specific features of your problem. I was trying to figure out if you really need RL to solve the problem, since it's not the easiest technique to apply. On the other hand, if you really need RL, it's not clear if you should use a deep neural network as approximator or you can use a shallow model (e.g., random trees). However, these questions an other potential optimizations require more domain knowledge. Here, it seems you are not able to share the domain of the problem, which could be due a numerous reasons and I perfectly understand.

You have estimated the number of required episodes to solve the problem based on some empirical studies using a smaller version of size 20*10 matrix. Just a caution note: due to the curse of the dimensionality, the complexity of the problem (or the experience needed) could grow exponentially when the state space dimensionalty grows, although maybe it is not your case.

That said, I'm looking forward to see an answer that really helps you to solve your problem.


来源: stackexchange

问:
How can I forward touches to a UIButton from another UIView?
I have a UIButton and a UIView. The View sits above the button, and is larger than the button in size. The view itself is what I want to have accept the touch events, and I'd like to forward them to the button, so that all the normal button visual changes on touch happen.

I can't seem to make this work-- my UIView implements touchesBegan/Moved/Ended/Cancelled, and turns around and calls the same methods on the button with the same arguments. But the button doesn't respond.

I have ensured that the touch methods are in fact being called on the UIView.

Is there something obvious I'm missing here, or a better way of getting the control messages across? Or is there a good reason why this shouldn't work?

Thanks!

[Note: I'm not looking for workarounds for the view+button design. Let's assume that that's a requirement. I'm interested in the notion of controls that are touch proxies for other controls. Thanks.]

答:
I use the small class below when I need a larger touch target than the visual size of the button.

Usage:

```<code>let button = UIButton(...) // set a title, image, target/action etc on the button
let insets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let buttonContainer = TouchForwardingButtonContainer(button: button, insets: insets) // this is what you add to your view
</code>```

```<code>// a container view for a button that insets the button itself but forwards touches in the inset area to the button
// allows for a larger touch target than the visual size of the button itself
private class TouchForwardingButtonContainer: UIView {
    private let button: UIButton

    init(button: UIButton, insets: UIEdgeInsets) {
        self.button = button

        super.init(frame: .zero)

        button.translatesAutoresizingMaskIntoConstraints = false
        addSubview(button)
        let constraints = [
            button.topAnchor.constraint(equalTo: topAnchor, constant: insets.top),
            button.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom),
            button.leftAnchor.constraint(equalTo: leftAnchor, constant: insets.left),
            button.rightAnchor.constraint(equalTo: rightAnchor, constant: -insets.right)
        ]
        NSLayoutConstraint.activate(constraints)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        return button
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I use the small class below when I need a larger touch target than the visual size of the button.

Usage:

let button = UIButton(...) // set a title, image, target/action etc on the button
let insets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let buttonContainer = TouchForwardingButtonContainer(button: button, insets: insets) // this is what you add to your view

// a container view for a button that insets the button itself but forwards touches in the inset area to the button
// allows for a larger touch target than the visual size of the button itself
private class TouchForwardingButtonContainer: UIView {
    private let button: UIButton

    init(button: UIButton, insets: UIEdgeInsets) {
        self.button = button

        super.init(frame: .zero)

        button.translatesAutoresizingMaskIntoConstraints = false
        addSubview(button)
        let constraints = [
            button.topAnchor.constraint(equalTo: topAnchor, constant: insets.top),
            button.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom),
            button.leftAnchor.constraint(equalTo: leftAnchor, constant: insets.left),
            button.rightAnchor.constraint(equalTo: rightAnchor, constant: -insets.right)
        ]
        NSLayoutConstraint.activate(constraints)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        return button
    }
}

ContentLicense: CC BY-SA 4.0


问:
Ionic 3: buttons are not clickable and inputs can't be edited on browser
I can't add inputs on browser and also clicking button doesn't execute sign() in ts file.</p>

```<code> <ion-content padding>
  <ion-list>

    <ion-item>
      <ion-label floating>Username</ion-label>
      <ion-input type="text" value=""></ion-input>
    </ion-item>

    <ion-item>
      <ion-label floating >Password</ion-label>
      <ion-input type="password"></ion-input>
    </ion-item>

  </ion-list>

  <div padding>
    <button ion-button block (click)="sign()">Sign In</button>
  </div>
</ion-content>
</code>```

答:
If you still have this problem. Try to put ion-item outside the ion-list (remove the ion-list). I don't know why but it's working for me. (Ionic 4)</p>

```<code>//<ion-list></ion-list>
<ion-item>
    <ion-label>Username</ion-label>
    <ion-input type="text" [(ngModel)]="user.username" name="username"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label>Password</ion-label>
    <ion-input type="password" [(ngModel)]="user.password" name="password"></ion-input>
  </ion-item>
</code>```

Body:
I can't add inputs on browser and also clicking button doesn't execute sign() in ts file.

 <ion-content padding>
  <ion-list>

    <ion-item>
      <ion-label floating>Username</ion-label>
      <ion-input type="text" value=""></ion-input>
    </ion-item>

    <ion-item>
      <ion-label floating >Password</ion-label>
      <ion-input type="password"></ion-input>
    </ion-item>

  </ion-list>

    <button ion-button block (click)="sign()">Sign In</button>

</ion-content>

Body:
If you still have this problem. Try to put ion-item outside the ion-list (remove the ion-list). I don't know why but it's working for me. (Ionic 4)

//<ion-list></ion-list>
<ion-item>
    <ion-label>Username</ion-label>
    <ion-input type="text" [(ngModel)]="user.username" name="username"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label>Password</ion-label>
    <ion-input type="password" [(ngModel)]="user.password" name="password"></ion-input>
  </ion-item>


问:
Unable to download a pdf file from a server
If you wan't to download a file in HTML you can just put a download tag like the following:

```<code><a href="downloads/path" download>Download file</a>
</code>```

In my application you can search for a project and then you can download the files to it. I can perfectly search after the files and I get them displayed as I want. So then I tried to download them, but however it won't work.

Here is my HTML code:

```<code><div *ngFor="let file of FILES">
   <a href="{{file.downloadUrl}}" download>{{file.name}}</a>
</div>
</code>```

The problem now is, the files opens himself in the browser, but it should download itself. I am really confused at this point, because it is literally like it should be (atleast I think so)

答: Most modern browsers are set to read documents by default if they can instead of downloading them are you using the same browser and experiencing different results for the same links? The browser can decide not to download a pdf even if you use download in the anchor tag. The issue is covered in this other post pretty well: PDF file not downloading with HTML5 download attribute</p>

Body:
If you wan't to download a file in HTML you can just put a download tag like the following:

Download file

In my application you can search for a project and then you can download the files to it. I can perfectly search after the files and I get them displayed as I want. So then I tried to download them, but however it won't work.

Here is my HTML code:

   {{file.name}}

The problem now is, the files opens himself in the browser, but it should download itself. I am really confused at this point, because it is literally like it should be (atleast I think so)


问:
How To Hold A Value of 1 and Add 1 Every time It's Seen?
In Google Sheets, how do you get 1 cell to hold a value of 1 if two other cells equal the same text; and then add 1 to that 1 cell again every time the other 2 cells repetitively equal the same text?

For example, if B129=I3, then D129 = 1. 1 now is to be held and never forgotten.

Then, if B129=I3 again, then D129 = 2. D129 can now repetitively increase by 1 over and over again as many times as B129=I3.

答:
So every time you change B129, update D129</p>

```<code>function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My Sheet");
if  (e.range.getA1Notation() != 'B129')  return; //Something other than the cell you wanted changed
var x = ss.getRange("I3").getValue();
if (e.getValue() != x) return;  //B129 doesn't equal I3
var counter = ss.getRange("D129"); // cell reference
counter.setValue(counter.getValue() + 1);

}
</code>```

Body:
So every time you change B129, update D129

function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My Sheet");
if  (e.range.getA1Notation() != 'B129')  return; //Something other than the cell you wanted changed
var x = ss.getRange("I3").getValue();
if (e.getValue() != x) return;  //B129 doesn't equal I3
var counter = ss.getRange("D129"); // cell reference
counter.setValue(counter.getValue() + 1);

}


问:
is there an explicit interface declaration for abstract methods?
i have a (quite easy) problem and it seems I can't find out how to do it. I would appreciate some help.

I have two classes which are something like this:

```<code>public class FileParameters { ... }

public abstract class File {
    ...
    public abstract FileParameters Params { get; }
}
</code>```

From both classes I have a derived special version:

```<code>public class SpecialFileParameters { ... }

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    public override FileParameters Params { get { return params; } }
}
</code>```

When I want to use the SpecialFileParameters I have to cast them first, e.g:

```<code>((SpecialFileParameters)SpecialFileObject.Parameters).DoSomething();
</code>```

which is quite obnoxious. What I would like to have is basically the same syntax as with interfaces

```<code>public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    private override FileParameters File.Params { get { return params; } }
    public new SpecialFileParameters Params { get { return params; } }
}
</code>```

But like this i get an compiler error: 'File' in explicit interface declaration is not an interface. Is there some other way to do this?

Some further information:

I cannot change the base classes, only my special classes

I actually need 2 special derived classes, one is written in C#, the other in C++/CLI. If the "trick" to makes it work is different between C# and C++ CLI please let me know.

Thanks for your help (and patience I guess ^^),

答:
Is it necessary to have the same method name between the two methods (the override and the new method)?  In these situations, I usually create a new method with a new name that returns the more derived type, and then have the override call this method in its implementation:

```<code>public override FileParameters Params { get { return SpecialParams; } }
public SpecialFileParameters SpecialParams { get { return params; } }
</code>```

In this way, when you have a SpecialFile object, you don't need the cast.  IF this doesn't work, perhaps you could explain more why you need the names of the methods to be the same for your situation.

ContentLicense: CC BY-SA 3.0

Body:
i have a (quite easy) problem and it seems I can't find out how to do it. I would appreciate some help.

I have two classes which are something like this:

public class FileParameters { ... }

public abstract class File {
    ...
    public abstract FileParameters Params { get; }
}

From both classes I have a derived special version:

public class SpecialFileParameters { ... }

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    public override FileParameters Params { get { return params; } }
}

When I want to use the SpecialFileParameters I have to cast them first, e.g:

((SpecialFileParameters)SpecialFileObject.Parameters).DoSomething();

which is quite obnoxious. What I would like to have is basically the same syntax as with interfaces

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    private override FileParameters File.Params { get { return params; } }
    public new SpecialFileParameters Params { get { return params; } }
}

But like this i get an compiler error: 'File' in explicit interface declaration is not an interface. Is there some other way to do this?

Some further information:

I cannot change the base classes, only my special classes

I actually need 2 special derived classes, one is written in C#, the other in C++/CLI. If the "trick" to makes it work is different between C# and C++ CLI please let me know.

Thanks for your help (and patience I guess ^^),

Body:
Is it necessary to have the same method name between the two methods (the override and the new method)?  In these situations, I usually create a new method with a new name that returns the more derived type, and then have the override call this method in its implementation:

public override FileParameters Params { get { return SpecialParams; } }
public SpecialFileParameters SpecialParams { get { return params; } }

In this way, when you have a SpecialFile object, you don't need the cast.  IF this doesn't work, perhaps you could explain more why you need the names of the methods to be the same for your situation.


问:
How do I create a timer for 1 second in java?
I need to make an image bounce on the screen. I am trying to do this by shifting the image up 5 units, then taking a one second break, then shifting another 5 units up, etc. I am trying to shift up 5 times and then shifting down 5 times, with a one second break between each shift. I need help making the timer for one second so it acts like a break between each shift. I need to write the time() method. </p>

```<code>public void moveIt(KeyEvent evt) throws InterruptedException {
    switch (evt.getKeyCode()) {
    case KeyEvent.VK_DOWN:
        myY += 0;
        break;
    case KeyEvent.VK_UP:
        for (int i = 1; i <= 10; i++) {
            if (i <= 5) {
                bounceUp();
            } else {
                bounceDown();
            }
            time();
        }
        break;
    case KeyEvent.VK_LEFT:
        myX -= 5;
        break;
    case KeyEvent.VK_RIGHT:
        myX += 5;
        break;
    }

    repaint();
}

Timer timer = new Timer();

public void bounceUp() throws InterruptedException {
    myY -= 10;
}

public void bounceDown() throws InterruptedException {
    myY += 10;
}

public void time() {
}
</code>```

答:
```<code>TimerTask task = new TimerTask()
{
   @Override
            public void run()
            {
                time();//executed each second
            }
}
timer.schedule(TimerTask task,1000,1000)
</code>```

That should help

Body:
I need to make an image bounce on the screen. I am trying to do this by shifting the image up 5 units, then taking a one second break, then shifting another 5 units up, etc. I am trying to shift up 5 times and then shifting down 5 times, with a one second break between each shift. I need help making the timer for one second so it acts like a break between each shift. I need to write the time() method.

public void moveIt(KeyEvent evt) throws InterruptedException {
    switch (evt.getKeyCode()) {
    case KeyEvent.VK_DOWN:
        myY += 0;
        break;
    case KeyEvent.VK_UP:
        for (int i = 1; i <= 10; i++) {
            if (i <= 5) {
                bounceUp();
            } else {
                bounceDown();
            }
            time();
        }
        break;
    case KeyEvent.VK_LEFT:
        myX -= 5;
        break;
    case KeyEvent.VK_RIGHT:
        myX += 5;
        break;
    }

    repaint();
}

Timer timer = new Timer();

public void bounceUp() throws InterruptedException {
    myY -= 10;
}

public void bounceDown() throws InterruptedException {
    myY += 10;
}

public void time() {
}

Body:
TimerTask task = new TimerTask()
{
   @Override
            public void run()
            {
                time();//executed each second
            }
}
timer.schedule(TimerTask task,1000,1000)

That should help


问:
Getting "Accumulated string array getting too large" querying Kusto from Power BI
We are trying to use Power Bi (Desktop, May 2019) to build a report on top of data in Azure Data Explorer\Kusto database and constantly receiving "Accumulated string array getting too large" errors.

Our data includes at able with about 350M rows - let's call it FACT, and a small table with 30 rows - let's call it DIM.

We defined a Many-to-one relationship between these tables in Power BI on the relevant columns. Built a simple report containing a singlMe atrix object based on the FACT table and a siTngle able object based on the DIM table for filtering the Matrix. When nothing is selected on the Table object the Matrix shows the results and everything is working quickly and nicely. However, when selecting any value from the Table object to filter the Matrix by we get an "Accumulated string array getting too large" error on the Matrix object.

Since we want to build a flexible report we cannot manually write the queries and must rely on Power BI to automatically generate them according to the users interactions.

How can we overcome this problem? It looks like Power BI is not sending optimized queries to Data Explorer but we found no way to control this.

Thanks,
H.G.

答: Unless there is something that can be improved on the Power BI side to send better queries, I think you should investigate baking the calculation into a table in Kusto. This could be a good use case for update policy. As new data arrives in your FACT table, the update policy would trigger and join it with the DIM table. Flattened tables work quite well in Kusto and then your Power BI query would be much simpler since all the data is available in a single table.</p>


问:
Projection of 3D Lidar point in the i-th camera image (KITTI Dataset)
I am working on an object classification problem, and I am using Lidar and camera data from the Kitti Dataset.
In this article: http://www.cvlibs.net/publications/Geiger2013IJRR.pdf, they provide the formulas for projecting the 3d PointCloud into the i-th camera image plane, but I don't understand some things :

Following equation((3) :

If the 3D point X is in velodyne camera image and Y in the i'th camera image, why X has four coordinates and Y three? It should have been 3 and 2, no?

(source: noelshack.com)

I need to project the 3D point Cloud into the camera image plane for then creating lidar images to use them as a channel for the CNN. Anyone who has ideas for it ?

Thank you in advance

答:
For your first query regarding x and y dimension there are two explanation.

Reason 1.

For image re-projection pin hole camera model is used which is in
perspective coordinate or homogenous coordinate. Perspective
projection uses the image origin as centre of projection and points
are mapped to the plane z=1. A 3D point  [x y z] is represented
by [xw yw zw w] and the point it maps on the plane is represented
by [xw yw zw]. Normalising with w gives.

So (x,y) -> [x y 1]T  : Homogeneous Image Coordinates

and (x,y,z) - > [x y z 1] T : Homogeneous Scene Coordinates

Reason 2.

With respect to the paper you have attached, considering equation
   (4) and (5)

It is clear that P is of dimension 3X4 and R is expanded to 4x4 dimension.Also x is of      dimension 1x4. So as per matrix multiplication rule number of columns of first matrix must equal to the number of rows of second matrix. So for given P of 3x4 and R of 4x4, x has to be 1x4.

Now coming to your second question of LiDAR image fusion, It requires intrinsic and extrinsic parameters (relative rotation and translation) and camera matrix. This rotation and translation forms a 3x4 matrix called as transformation matrix. So the point fusion equations becomes

```<code>[x y 1]^T = Transformation Matrix * Camera Matrix * [X Y Z 1]^T
</code>```

You can also refer :: Lidar Image Fusion KITTI

Once your LiDAR image fusion is done, you can input this image to your CNN model.I am not aware of DNN modules for LiDAR fused image.

Hope this helps..

Body:
For your first query regarding x and y dimension there are two explanation.

Reason 1.

For image re-projection pin hole camera model is used which is in
perspective coordinate or homogenous coordinate. Perspective
projection uses the image origin as centre of projection and points
are mapped to the plane z=1. A 3D point  [x y z] is represented
by [xw yw zw w] and the point it maps on the plane is represented
by [xw yw zw]. Normalising with w gives.

So (x,y) -> [x y 1]T  : Homogeneous Image Coordinates

and (x,y,z) - > [x y z 1] T : Homogeneous Scene Coordinates

Reason 2.

With respect to the paper you have attached, considering equation
   (4) and (5)

It is clear that P is of dimension 3X4 and R is expanded to 4x4 dimension.Also x is of      dimension 1x4. So as per matrix multiplication rule number of columns of first matrix must equal to the number of rows of second matrix. So for given P of 3x4 and R of 4x4, x has to be 1x4.

Now coming to your second question of LiDAR image fusion, It requires intrinsic and extrinsic parameters (relative rotation and translation) and camera matrix. This rotation and translation forms a 3x4 matrix called as transformation matrix. So the point fusion equations becomes

[x y 1]^T = Transformation Matrix * Camera Matrix * [X Y Z 1]^T

You can also refer :: Lidar Image Fusion KITTI

Once your LiDAR image fusion is done, you can input this image to your CNN model.I am not aware of DNN modules for LiDAR fused image.

Hope this helps..


问:
Entity Framework SQL Server Error Message Language
I am working on an Application utilizing Entity Framework for Data Access. For some purposes it is neccessary to parse the SqlException Message for further information. I already found out that this Exception Message is directly coming from SQL Server. So to make that parsing process work i need to make sure the language is set to the same in every environment.

I am using to set the language

```<code>SET LANGUAGE English;
</code>```

For test purposes I did following:

```<code>SET LANGUAGE English;
SELECT * FROM ABC;
</code>```

ABC does not exist so it will obviously fail and i will get an error message. In Management Studio my ErrorMessage is showing this:

this is in English as supposed to.

Now when i try the same in C# i will get:

which is in german.

What am i missing? Any ideas anyone? Thanks very much...

答:
instead of doing this in two ExecuteSqlCommand calls you should do this in one.

```<code>string command = "SET LANGUAGE English; SELECT * FROM ABC;";
ctx.Database.ExecuteSqlCommand(command);
</code>```

ExecuteSqlCommand will start a new auto commit session. Your first SET LANGUAGE pretty much has no effect since the select is in another session.

Body:
I am working on an Application utilizing Entity Framework for Data Access. For some purposes it is neccessary to parse the SqlException Message for further information. I already found out that this Exception Message is directly coming from SQL Server. So to make that parsing process work i need to make sure the language is set to the same in every environment.

I am using to set the language

SET LANGUAGE English;

For test purposes I did following:

SET LANGUAGE English;
SELECT * FROM ABC;

ABC does not exist so it will obviously fail and i will get an error message. In Management Studio my ErrorMessage is showing this:

this is in English as supposed to.

Now when i try the same in C# i will get:

which is in german.

What am i missing? Any ideas anyone? Thanks very much...

Body:
instead of doing this in two ExecuteSqlCommand calls you should do this in one.

string command = "SET LANGUAGE English; SELECT * FROM ABC;";
ctx.Database.ExecuteSqlCommand(command);

ExecuteSqlCommand will start a new auto commit session. Your first SET LANGUAGE pretty much has no effect since the select is in another session.


问:
How can I extract all the HTML tags from a page. Not the data between the tags
Sorry if it’s a newbie question. I’ve been googling for an hour and I also checked several questions on this site but I can’t seem to figure it out.

I’m trying to extract all the HTML tags (elements) from a few different pages. I don’t need the data between the HTML tags. I only need the tags that are being used, comments, etc.

So the output I’m looking for is whatever is between <> I guess. As an example, if the code is

```<code><head> title </head>
<body id=“body text”> blah blah blah </body>
</code>```

I’d like the output to be:

```<code><head> </head>
<body id=“body text”> </body>
</code>```

Thanks a lot in advance and sorry if it’s a silly question.

答:
You can try Perl</p>

```<code>$ perl -0777 -ne ' while(/(<.+?>)/g) { print "$1\n" } ' input.txt
<head>
</head>
<body id=“body text”>
</body>

$
</code>```

Body:
Sorry if it’s a newbie question. I’ve been googling for an hour and I also checked several questions on this site but I can’t seem to figure it out.

I’m trying to extract all the HTML tags (elements) from a few different pages. I don’t need the data between the HTML tags. I only need the tags that are being used, comments, etc.

So the output I’m looking for is whatever is between <> I guess. As an example, if the code is

 title
 blah blah blah

I’d like the output to be:

Thanks a lot in advance and sorry if it’s a silly question.

Body:
You can try Perl

$ perl -0777 -ne ' while(/(<.+?>)/g) { print "$1\n" } ' input.txt
<head>
</head>
<body id=“body text”>
</body>

$


问:
How to calculate month with fraction in Access VBA
I need to write a function that receives two arguments startdate and enddate where it returns the difference between these two dates.

Say that function is monthfractiondiff(startdate,enddate)

e.g. monthfractiondiff(15/01/2016,15/02/2016) will return
((31-15)/31)+(15/29) = 1.0333704116

monthfractiondiff(15/11/2018,15/02/2019) will return
((30-15)/30)+1+1+(15/28) = 3.0357142857

I vainly tried https://access-programmers.co.uk/forums/showthread.php?t=113589

答:
I would go with datediff().

```<code>datediff("d", "01/01/2019", date())/30.5
</code>```

Today this returns me 4,85245901639344.

Body:
I would go with datediff().

datediff("d", "01/01/2019", date())/30.5

Today this returns me 4,85245901639344.


问:
C++ error unexplained: error: expected initializer before '&' token
i know there's a few other posts like this, but i've been on this single error for over an hour now and can't figure it out. here's the code that's giving trouble

```<code>istream& operator>>(istream& in, UndirectedGraph& g)
{
    int numVerticies;
    in >> numVerticies;
    g = UndirectedGraph(numVerticies);

    for(int i = 0; i < numVerticies; i++)
    {
        int temp;
        in >> temp;
        if(temp != i)
        {
            g.linkedAdjacencyList[i]->value = temp;
        }
    }

    int edges;
    in >> edges;
    g.edges = edges;
    for(int i = 0; i < edges; i++)
    {
        int first;
        int second;
        in >> first >> second;
        addEdge(first, second);
    }
    return in;
}

ostream& operator<<(ostream& out, UndirectedGraph& g)
{
    out << g.numVerticies << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << g.linkedAdjacencyList[i] << " ";
    }
    out << endl;

    out << g.edges << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << linkedAdjacencyList[i]->value;
        Node* whereto;
        whereto = linkedAdjacencyList[i]->adj;
        while(whereto->adj != NULL)
        {
            out << " " << whereto->value;
            whereto->adj = whereto->adj->adj;
        }
    }
    return out;
}

int main()
{

    ifstream inFile;
    inFile.open("hw8.in");

    UndirectedGraph graph;
    inFile >> graph;
</code>```

...

here, the errors are on lines 1 and 28, with the overloading of istream and ostream.

Thanks for your help!

答:
Kind of reiterating what @don-wakefield said. I think you want your operators to return std::istream& and std::ostream& respectively (and not UndirectedGraph::istream and UndirectedGraph::ostream).

So the signatures would look like:

```<code>std::istream& UndirectedGraph::operator>>(istream& in, UndirectedGraph g)
std::ostream& UndirectedGraph::operator<<(ostream& out, UndirectedGraph& g)
</code>```

Body:
i know there's a few other posts like this, but i've been on this single error for over an hour now and can't figure it out. here's the code that's giving trouble

istream& operator>>(istream& in, UndirectedGraph& g)
{
    int numVerticies;
    in >> numVerticies;
    g = UndirectedGraph(numVerticies);

    for(int i = 0; i < numVerticies; i++)
    {
        int temp;
        in >> temp;
        if(temp != i)
        {
            g.linkedAdjacencyList[i]->value = temp;
        }
    }

    int edges;
    in >> edges;
    g.edges = edges;
    for(int i = 0; i < edges; i++)
    {
        int first;
        int second;
        in >> first >> second;
        addEdge(first, second);
    }
    return in;
}

ostream& operator<<(ostream& out, UndirectedGraph& g)
{
    out << g.numVerticies << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << g.linkedAdjacencyList[i] << " ";
    }
    out << endl;

    out << g.edges << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << linkedAdjacencyList[i]->value;
        Node* whereto;
        whereto = linkedAdjacencyList[i]->adj;
        while(whereto->adj != NULL)
        {
            out << " " << whereto->value;
            whereto->adj = whereto->adj->adj;
        }
    }
    return out;
}

int main()
{

    ifstream inFile;
    inFile.open("hw8.in");

    UndirectedGraph graph;
    inFile >> graph;

...

here, the errors are on lines 1 and 28, with the overloading of istream and ostream.

Thanks for your help!

Body:
Kind of reiterating what @don-wakefield said. I think you want your operators to return std::istream& and std::ostream& respectively (and not UndirectedGraph::istream and UndirectedGraph::ostream).

So the signatures would look like:

std::istream& UndirectedGraph::operator>>(istream& in, UndirectedGraph g)
std::ostream& UndirectedGraph::operator<<(ostream& out, UndirectedGraph& g)


问:
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"
I am pushing my docker image to AWS ECS. And, I am getting following error:
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"

Here is the full output:

```<code>The push refers to repository [myaddress.dkr.ecr.us-east-1.amazonaws.com/myrepositoryname]
3d4763f6944c: Layer already exists
5d22ab3cff2d: Layer already exists
080db391ad2c: Layer already exists
7030a45b5de7: Layer already exists
5d98bab77a5b: Layer already exists
f08694a3abdb: Layer already exists
c4cfb93dc085: Layer already exists
1a38a1227cbb: Layer already exists
caa05d68a0ed: Layer already exists
891119e77426: Layer already exists
1f912505da6e: Layer already exists
f1e810a48819: Layer already exists
a47630fbce4f: Layer already exists
09fc3edb847c: Layer already exists
6b60013e5875: Pushing [==================================================>]  323.9MB/323.9MB
d6335a641f5e: Layer already exists
5c33df241050: Layer already exists
ffc4c11463ee: Layer already exists
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"
</code>```

Is there any solution for the above issue? I tried to build an image again and also increased allocated memory in docker.

答:
I was getting a similar error, though in my case it was related to the NPM cache.

```<code>file integrity checksum failed for "root/.npm/_cacache/content-v2/sha512/d1/32/a7a1c3a9679bc2b3533e44dd7850d81c4c257024e9f32854b681383a5ed1c191412124a0d316bea11daa019c2bee1bf18770034bd53db117aedc09339b0b
</code>```

All I had to do was full build with the --no-cache option, e.g.:

```<code>docker build --no-cache .
</code>```

Push to AWS was successful after the full build.

Body:
I am pushing my docker image to AWS ECS. And, I am getting following error:
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"

Here is the full output:

The push refers to repository [myaddress.dkr.ecr.us-east-1.amazonaws.com/myrepositoryname]
3d4763f6944c: Layer already exists
5d22ab3cff2d: Layer already exists
080db391ad2c: Layer already exists
7030a45b5de7: Layer already exists
5d98bab77a5b: Layer already exists
f08694a3abdb: Layer already exists
c4cfb93dc085: Layer already exists
1a38a1227cbb: Layer already exists
caa05d68a0ed: Layer already exists
891119e77426: Layer already exists
1f912505da6e: Layer already exists
f1e810a48819: Layer already exists
a47630fbce4f: Layer already exists
09fc3edb847c: Layer already exists
6b60013e5875: Pushing [==================================================>]  323.9MB/323.9MB
d6335a641f5e: Layer already exists
5c33df241050: Layer already exists
ffc4c11463ee: Layer already exists
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"

Is there any solution for the above issue? I tried to build an image again and also increased allocated memory in docker.

Body:
I was getting a similar error, though in my case it was related to the NPM cache.

file integrity checksum failed for "root/.npm/_cacache/content-v2/sha512/d1/32/a7a1c3a9679bc2b3533e44dd7850d81c4c257024e9f32854b681383a5ed1c191412124a0d316bea11daa019c2bee1bf18770034bd53db117aedc09339b0b

All I had to do was full build with the --no-cache option, e.g.:

docker build --no-cache .

Push to AWS was successful after the full build.


问:
How make cURL request between two docker container?
I'm working with docker on differents projects. I've a nginx conatainer and two php container : one for my projets in php5.6 and another for php7.0 project's.

I need to to make a cURL request between my two php container (from 5.6 to 7) but I have no idea of how make it. I've try somthing with the different host file but I only get a Connection timed out or a Connection refused.

curl -X GET 'hostUrl'

When the hostUrl is the php7 docker ip I get the Connection timed out and when hostUrl is 127.0.0.1 I get the Connection refused error.

They are in the same networks in my docker-compose.

What can I do to solve my problem ?

Thanks

答:
If the two containers are under the same docker network; i.e. you have specified two containers on one docker-composer.yml file, then you should be able to talk to the other container simply using the hostname of the container.

If the two containers are not on the same docker network, you can have both container expose their private port and communicate via the host machine.

For e.g. if you have a container "A" running on port 9000 and container "B" running on port 8000; and you want to curl into container "A" from "B", then you can do this:

```<code><?php

// Get the docker host machine's ip:
$host_ip = exec("/sbin/ip route|awk '/default/ { print $3 }'");

// Now curl
// $container_a_url = "http://{$host_ip}:9000"
</code>```

Body:
If the two containers are under the same docker network; i.e. you have specified two containers on one docker-composer.yml file, then you should be able to talk to the other container simply using the hostname of the container.

If the two containers are not on the same docker network, you can have both container expose their private port and communicate via the host machine.

For e.g. if you have a container "A" running on port 9000 and container "B" running on port 8000; and you want to curl into container "A" from "B", then you can do this:

<?php

// Get the docker host machine's ip:
$host_ip = exec("/sbin/ip route|awk '/default/ { print $3 }'");

// Now curl
// $container_a_url = "http://{$host_ip}:9000"


问:
How practical is it to intercept certain SMS messages in Android but allow others to be handled by the built-in messaging app?
I've been developing an Android app that allows the operator to control equipment through API calls, which are sent and received via text messages.

Since we want people to still be able to use their phones as phones, we still want users to be able to send and receive text message with the built-in SMS app.

However, the issue with my app is that it is not the default SMS app, which means that these control messages:

Look like total garbage, so I would want to be able to delete these messages from a user's inbox (or have them never reach the inbox).

They also show a notification, since they're an SMS message and are handled by the system SMS app as such.

If I block a number, using the built-in SMS app, my app won't receive it either - so the logic, therefore, is to make my app the default SMS app so that it can intercept all messages before deciding how they should be handled. The problem now is that no other messages will reach the built-in SMS app.

One way around this is to forward messages to this built-in SMS app's inbox, but the built-in SMS app would no longer be able to send messages.

The inevitable answer that I expect is the only technically viable option is that I will have to implement a full SMS client in its entirety; however, this seems a really poor approach to me and massively pollutes the scope of development.

Is there really no way for me to create a default SMS app that can then "forward" an incoming SMS to either the built-in SMS app or my own app (for controlling the aforementioned machinery)?

答:
Android is not set up to work the way that you seek, except prior to Android 4.4, due to rampant abuse. Your options are:

Limit users of your app to Android 4.3 or older devices, in which case the SMS_RECEIVED broadcast is an ordered broadcast that you can cancel. This approach will be impractical due to the small number of active older devices, plus the challenges of limiting distribution to those devices.

Use createAppSpecificSmsToken() on SmsManager. This gives you a token that, if it is included in an SMS message, causes that message to be re-routed to your app by means of the supplied PendingIntent. However, these are one-time-use tokens, so you would need to be able to tell your server the next token to use, including the first token to use after app installation. It further implies that you have a server capable of tracking and using those tokens, and that may or may not be part of your overall system architecture. Also, createAppSpecificSmsToken() is only available on API Level 26+ (Android 8.0+).

Find a third-party SMS client that offers a plugin interface, and implement a plugin that meets your requirements. Then, require users of this equipment to switch to that SMS client.

Contribute a plugin interface to an existing open source SMS client project, then proceed as in the preceding bullet.

Write an SMS client, either from scratch or based off of an existing open source project, and have users of this equipment switch to that SMS client.

Require a rooted device and figure out some magic (e.g., Xposed module) that will allow you to handle SMS messages more to your liking. I presume that this is possible, as there are lots of creative uses of root, though I do not know if this specific thing is possible.

Create a custom ROM that handles SMS messages more to your liking, then require users of this equipment to install that custom ROM.


问:
How do I mark (or) shade the area below the graph of Surface plot in Matlab?
I am trying to plot a 3D surface graph for the following equation
 t_t <= (xi_i - xi_j) . sqrt(rho). I have included my code. But I would like to mark or shade the area under the graph of this surface plot. How do I solve it?

```<code>[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

colormap(jet)

surf(X,Y,Z)

colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');
</code>```

答:
Here's another way of using patch objects.

This solution is very similar to Ander's, but the patch construction is handled differently, so you don't need to loop and end up with only 4 patch entities to handle.

```<code>%% Prepare domain limits
xLim = [1 10] ; xStep = 0.5 ;
yLim = [1 20] ; yStep = 1 ;

x = xLim(1):xStep:xLim(2) ;
y = yLim(1):yStep:yLim(2) ;

%% Your code
[X,Y] = meshgrid(x,y);
Z = X.* sqrt(Y);
figure;
surf(X,Y,Z)
colorbar
xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');
ylabel('Density(\rho)');
zlabel('Transmission Delay (t_t)');

%% prepare patch elements
zLim = [min(Z) max(Z)] ;
pcol = [0.2857,1,0.7143] ;

xface = [ x xLim(2) xLim(1) ] ;
yface = [ y yLim(2) yLim(1) ] ;
xface0 = zeros(size(xface)) ;
yface0 = zeros(size(yface)) ;
xfaceZ = [zeros(size(x)) zLim(1) zLim(1)] ;
yfaceZ = [zeros(size(y)) zLim(1) zLim(1)] ;

%% display the patches
hp(1) = patch( xface , xface0+yLim(1) , xfaceZ ,pcol ) ;
hp(3) = patch( xface , xface0+yLim(2) , xfaceZ ,pcol ) ;
hp(2) = patch( yface0+xLim(1) , yface , yfaceZ ,pcol ) ;
hp(4) = patch( yface0+xLim(2) , yface , yfaceZ ,pcol ) ;

%% update top edge of patches
% to connect to the surface edges
hp(1).ZData(1:end-2) = Z(1,:) ;
hp(2).ZData(1:end-2) = Z(:,1) ;
hp(3).ZData(1:end-2) = Z(end,:) ;
hp(4).ZData(1:end-2) = Z(:,end) ;

%% Color according to preferences
set(hp, 'Facecolor',pcol , 'FaceAlpha',0.5 , 'EdgeColor','none')
</code>```

Will render:

Body:
I am trying to plot a 3D surface graph for the following equation
 t_t <= (xi_i - xi_j) . sqrt(rho). I have included my code. But I would like to mark or shade the area under the graph of this surface plot. How do I solve it?

[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

colormap(jet)

surf(X,Y,Z)

colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');

Body:
Here's another way of using patch objects.

This solution is very similar to Ander's, but the patch construction is handled differently, so you don't need to loop and end up with only 4 patch entities to handle.

%% Prepare domain limits
xLim = [1 10] ; xStep = 0.5 ;
yLim = [1 20] ; yStep = 1 ;

x = xLim(1):xStep:xLim(2) ;
y = yLim(1):yStep:yLim(2) ;

%% Your code
[X,Y] = meshgrid(x,y);
Z = X.* sqrt(Y);
figure;
surf(X,Y,Z)
colorbar
xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');
ylabel('Density(\rho)');
zlabel('Transmission Delay (t_t)');

%% prepare patch elements
zLim = [min(Z) max(Z)] ;
pcol = [0.2857,1,0.7143] ;

xface = [ x xLim(2) xLim(1) ] ;
yface = [ y yLim(2) yLim(1) ] ;
xface0 = zeros(size(xface)) ;
yface0 = zeros(size(yface)) ;
xfaceZ = [zeros(size(x)) zLim(1) zLim(1)] ;
yfaceZ = [zeros(size(y)) zLim(1) zLim(1)] ;

%% display the patches
hp(1) = patch( xface , xface0+yLim(1) , xfaceZ ,pcol ) ;
hp(3) = patch( xface , xface0+yLim(2) , xfaceZ ,pcol ) ;
hp(2) = patch( yface0+xLim(1) , yface , yfaceZ ,pcol ) ;
hp(4) = patch( yface0+xLim(2) , yface , yfaceZ ,pcol ) ;

%% update top edge of patches
% to connect to the surface edges
hp(1).ZData(1:end-2) = Z(1,:) ;
hp(2).ZData(1:end-2) = Z(:,1) ;
hp(3).ZData(1:end-2) = Z(end,:) ;
hp(4).ZData(1:end-2) = Z(:,end) ;

%% Color according to preferences
set(hp, 'Facecolor',pcol , 'FaceAlpha',0.5 , 'EdgeColor','none')

Will render:


问:
Cant onClick event do
 tag React
I have a sideBar that opens when I click on a button and i have
 items there.

I want do add an onCLick event to those items but, onClick event fires when page is loaded and when ever I click on  elements.

Any information is helpful, thank you.

```<code>const Sidedraw = props => {
  let drawClass = "sideDraw";
  if (props.show) {
    drawClass = "sideDraw open";
  }
  return (
    <nav className={drawClass}>
      <ul>
        <li className="matches" onclick={console.log("work work")}>
          Pro matches
        </li>
        <li className="matches">Public mathes</li>
        <li className="matches">Players</li>
        <li className="matches">Teams</li>
      </ul>
    </nav>
  );
};
</code>```

答:
As others have mentioned, the onClick should be a function reference.

Also, you will likely get a warning with the current code:

Non-interactive elements should not be assigned mouse or keyboard event listeners

You should place an interactive element (anchor, button, etc.) within the list item.

```<code><ul>
  <li className="matches">
    <button onClick={() => console.log('work work')}>Pro matches</button>
  </li>
  <li className="matches">Public mathes</li>
  <li className="matches">Players</li>
  <li className="matches">Teams</li>
</ul>
</code>```

Title: Cant onClick event do <li> tag React

Body:
I have a sideBar that opens when I click on a button and i have
 items there.

I want do add an onCLick event to those items but, onClick event fires when page is loaded and when ever I click on  elements.

Any information is helpful, thank you.

const Sidedraw = props => {
  let drawClass = "sideDraw";
  if (props.show) {
    drawClass = "sideDraw open";
  }
  return (

          Pro matches

Public mathes

Players

Teams

  );
};

Body:
As others have mentioned, the onClick should be a function reference.

Also, you will likely get a warning with the current code:

Non-interactive elements should not be assigned mouse or keyboard event listeners

You should place an interactive element (anchor, button, etc.) within the list item.

<ul>
  <li className="matches">
    <button onClick={() => console.log('work work')}>Pro matches</button>
  </li>
  <li className="matches">Public mathes</li>
  <li className="matches">Players</li>
  <li className="matches">Teams</li>
</ul>


问:
how to make a multiline textbox not accept Enter and Backspace
I have a multiline textbox which shouldn't accept alphabets, numbers, newline(enter key) and backspace. In short, the textbox.Text shouldn't be editable. But I do want the textbox to accept two shortcut keys - control and control+R. One way I can make the textbox un-editable is by making it read-only. But then the textbox wont accept any keystroke at all. In short, my shortcuts ( control and control+R) wont work( Control + R) with read-only method.

Can anyone help in this regard. That's all I have to do.

One thing I could do here is not to make the textbox read-only and then restrict the characters(alphabets and digits) that could be inputted in the textbox. With this code:

```<code>    private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
    {
        // only modifier keys, escape, enter, backspace etc is accepted now
        e.Handled = !char.IsControl(e.KeyChar);
    }

    private void txtResult_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true)
        {
            if (e.KeyCode == Keys.R)
            {
                // do something
            }
            else
            {
                //do something
            }
        }

        if (e.KeyCode == Keys.Escape)
        {
            //do something
        }
    }
</code>```

With this technique I can get the shortcuts(control and control+R) working. But the trouble with this method is that Enter and Backspace keys work as well making it possible to edit the text of textbox. How can I specifically restrict Enter and Backspace key being registered from the textbox, but let Control and Escape??

答:
The Enter and Backspace keys won't work if the textbox is set to ReadOnly, as you suggested early on in the question that you had done. Make sure the property is still set to true. You can either set it in the Properties window, or through code like so:

```<code>myTextBox.ReadOnly = true;
</code>```

Then, you need to handle the KeyDown event for the textbox control, and watch for the specific keys that you're interested in. Something like this:

```<code>private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
   if (e.Control)
   {
      if (e.KeyCode == Keys.R)
      {
         MessageBox.Show("Pressed Ctrl+R");
      }
      else
      {
         MessageBox.Show("Pressed Ctrl");
      }
   }
   else if (e.KeyCode == Keys.Escape)
   {
      MessageBox.Show("Pressed Esc");
   }
}
</code>```

This works exactly as expected, as long as the textbox is set to read-only. No other keys are recognized, and the user cannot change or modify any of the text in the textbox. You don't need to suppress the keypresses, as the control is already doing that when you set it to read-only. You also don't need to handle both the KeyDown and KeyPress events. KeyPress won't work for you anyway, as it doesn't let you handle control characters.

Body:
I have a multiline textbox which shouldn't accept alphabets, numbers, newline(enter key) and backspace. In short, the textbox.Text shouldn't be editable. But I do want the textbox to accept two shortcut keys - control and control+R. One way I can make the textbox un-editable is by making it read-only. But then the textbox wont accept any keystroke at all. In short, my shortcuts ( control and control+R) wont work( Control + R) with read-only method.

Can anyone help in this regard. That's all I have to do.

One thing I could do here is not to make the textbox read-only and then restrict the characters(alphabets and digits) that could be inputted in the textbox. With this code:

    private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
    {
        // only modifier keys, escape, enter, backspace etc is accepted now
        e.Handled = !char.IsControl(e.KeyChar);
    }

    private void txtResult_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true)
        {
            if (e.KeyCode == Keys.R)
            {
                // do something
            }
            else
            {
                //do something
            }
        }

        if (e.KeyCode == Keys.Escape)
        {
            //do something
        }
    }

With this technique I can get the shortcuts(control and control+R) working. But the trouble with this method is that Enter and Backspace keys work as well making it possible to edit the text of textbox. How can I specifically restrict Enter and Backspace key being registered from the textbox, but let Control and Escape??

Body:
The Enter and Backspace keys won't work if the textbox is set to ReadOnly, as you suggested early on in the question that you had done. Make sure the property is still set to true. You can either set it in the Properties window, or through code like so:

myTextBox.ReadOnly = true;

Then, you need to handle the KeyDown event for the textbox control, and watch for the specific keys that you're interested in. Something like this:

private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
   if (e.Control)
   {
      if (e.KeyCode == Keys.R)
      {
         MessageBox.Show("Pressed Ctrl+R");
      }
      else
      {
         MessageBox.Show("Pressed Ctrl");
      }
   }
   else if (e.KeyCode == Keys.Escape)
   {
      MessageBox.Show("Pressed Esc");
   }
}

This works exactly as expected, as long as the textbox is set to read-only. No other keys are recognized, and the user cannot change or modify any of the text in the textbox. You don't need to suppress the keypresses, as the control is already doing that when you set it to read-only. You also don't need to handle both the KeyDown and KeyPress events. KeyPress won't work for you anyway, as it doesn't let you handle control characters.


问:
Pass data from activity to fragment ( empty getArguments() )
I need to pass data from activity to fragment.
I did try set setArguments() , broadcast receiver
and I don't know where I am making a mistake
tip 1: in MainActivity setArguments() bundle is full of stuff but when I call getArguments() it's empty, why?

EDIT  :  i just forgot to load it in MainActivity after intance was saved

MainActivity:

```<code>    @Override
    protected void onSaveInstanceState(Bundle outState) {

        Bundle gameData = getIntent().getExtras();

        float current_zoom =(gameData.getFloat("current_zoom"));
        LatLng current_target =((LatLng)gameData.getParcelable("current_target"));
        float current_bearing =(gameData.getFloat("current_bearing"));
        String current_map_mode = (gameData.getString("current_map_mode"));

        Bundle dataActivityBundle = new Bundle();
        dataActivityBundle.putFloat("current_zoom",current_zoom);
        dataActivityBundle.putParcelable("current_target",current_target);
        dataActivityBundle.putFloat("current_bearing",current_bearing);
        dataActivityBundle.putString("current_map_mode",current_map_mode);

        MapFragment myObj = new MapFragment();
        myObj.setArguments(dataActivityBundle);
        Log.i("Rotate","Arguments : "+String.valueOf(mapFragment.getArguments()));

        super.onSaveInstanceState(outState);
    }
</code>```

MapFragment:

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment

       View v = inflater.inflate(R.layout.fragment_map, container, false);

        mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
        if(mapFragment==null){
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            mapFragment = SupportMapFragment.newInstance();
            ft.replace(R.id.map,mapFragment).commit();
        }
        mapFragment.getMapAsync(this);

       if (getArguments() != null) {

            current_zoom = getArguments().getFloat("current_zoom");
            current_target = getArguments().getParcelable("current_target");
            current_bearing = getArguments().getFloat("current_bearing");
            current_map_mode = getArguments().getString("current_map_mode");

            Log.i("Rotate","onCreateView : getArguments() != null");
            Log.i("Rotate","current_zoom "+getArguments().getFloat("current_zoom"));
            Log.i("Rotate","current_target "+getArguments().getParcelable("current_target"));
            Log.i("Rotate","current_bearing "+getArguments().getFloat("current_bearing"));
            Log.i("Rotate","current_map_mode "+getArguments().getString("current_map_mode"));
        }
}

</code>```

答:
Something you may be doing wrong is performing the fragment transaction in the fragment itself.  Traditionally, the transaction should take place in the parent activity.  Try to refactor your code by moving your transaction logic from MapFragment to MainActivity like so:

// MainActivity.java
  @Override
    protected void onSaveInstanceState(Bundle outState) {

        Bundle gameData = getIntent().getExtras();

        float current_zoom =(gameData.getFloat("current_zoom"));
        LatLng current_target =((LatLng)gameData.getParcelable("current_target"));
        float current_bearing =(gameData.getFloat("current_bearing"));
        String current_map_mode = (gameData.getString("current_map_mode"));

        Bundle dataActivityBundle = new Bundle();
        dataActivityBundle.putFloat("current_zoom",current_zoom);
        dataActivityBundle.putParcelable("current_target",current_target);
        dataActivityBundle.putFloat("current_bearing",current_bearing);
        dataActivityBundle.putString("current_map_mode",current_map_mode);

        // Fragment transaction code moved here
        MapFragment myObj = new MapFragment();
        myObj.setArguments(dataActivityBundle);
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        mapFragment = SupportMapFragment.newInstance();
        ft.replace(R.id.map,mapFragment).commit();
        Log.i("Rotate","Arguments : "+String.valueOf(mapFragment.getArguments()));

        super.onSaveInstanceState(outState);
    }
```

```    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View v = inflater.inflate(R.layout.fragment_map, container, false);

        // Fragment transaction logic no longer here

        // Call private functions without initializing the object's own class
        getMapAsync(this);

       if (getArguments() != null) {

            current_zoom = getArguments().getFloat("current_zoom");
            current_target = getArguments().getParcelable("current_target");
            current_bearing = getArguments().getFloat("current_bearing");
            current_map_mode = getArguments().getString("current_map_mode");

            Log.i("Rotate","onCreateView : getArguments() != null");
            Log.i("Rotate","current_zoom "+getArguments().getFloat("current_zoom"));
            Log.i("Rotate","current_target "+getArguments().getParcelable("current_target"));
            Log.i("Rotate","current_bearing "+getArguments().getFloat("current_bearing"));
            Log.i("Rotate","current_map_mode "+getArguments().getString("current_map_mode"));
        }
}
```

Body:
I need to pass data from activity to fragment.
I did try set setArguments() , broadcast receiver
and I don't know where I am making a mistake
tip 1: in MainActivity setArguments() bundle is full of stuff but when I call getArguments() it's empty, why?

EDIT  :  i just forgot to load it in MainActivity after intance was saved

MainActivity:

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        Bundle gameData = getIntent().getExtras();

        float current_zoom =(gameData.getFloat("current_zoom"));
        LatLng current_target =((LatLng)gameData.getParcelable("current_target"));
        float current_bearing =(gameData.getFloat("current_bearing"));
        String current_map_mode = (gameData.getString("current_map_mode"));

        Bundle dataActivityBundle = new Bundle();
        dataActivityBundle.putFloat("current_zoom",current_zoom);
        dataActivityBundle.putParcelable("current_target",current_target);
        dataActivityBundle.putFloat("current_bearing",current_bearing);
        dataActivityBundle.putString("current_map_mode",current_map_mode);

        MapFragment myObj = new MapFragment();
        myObj.setArguments(dataActivityBundle);
        Log.i("Rotate","Arguments : "+String.valueOf(mapFragment.getArguments()));

        super.onSaveInstanceState(outState);
    }

MapFragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment

       View v = inflater.inflate(R.layout.fragment_map, container, false);

        mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
        if(mapFragment==null){
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            mapFragment = SupportMapFragment.newInstance();
            ft.replace(R.id.map,mapFragment).commit();
        }
        mapFragment.getMapAsync(this);

       if (getArguments() != null) {

            current_zoom = getArguments().getFloat("current_zoom");
            current_target = getArguments().getParcelable("current_target");
            current_bearing = getArguments().getFloat("current_bearing");
            current_map_mode = getArguments().getString("current_map_mode");

            Log.i("Rotate","onCreateView : getArguments() != null");
            Log.i("Rotate","current_zoom "+getArguments().getFloat("current_zoom"));
            Log.i("Rotate","current_target "+getArguments().getParcelable("current_target"));
            Log.i("Rotate","current_bearing "+getArguments().getFloat("current_bearing"));
            Log.i("Rotate","current_map_mode "+getArguments().getString("current_map_mode"));
        }
}

Body:
Something you may be doing wrong is performing the fragment transaction in the fragment itself.  Traditionally, the transaction should take place in the parent activity.  Try to refactor your code by moving your transaction logic from MapFragment to MainActivity like so:

// MainActivity.java
  @Override
    protected void onSaveInstanceState(Bundle outState) {

        Bundle gameData = getIntent().getExtras();

        float current_zoom =(gameData.getFloat("current_zoom"));
        LatLng current_target =((LatLng)gameData.getParcelable("current_target"));
        float current_bearing =(gameData.getFloat("current_bearing"));
        String current_map_mode = (gameData.getString("current_map_mode"));

        Bundle dataActivityBundle = new Bundle();
        dataActivityBundle.putFloat("current_zoom",current_zoom);
        dataActivityBundle.putParcelable("current_target",current_target);
        dataActivityBundle.putFloat("current_bearing",current_bearing);
        dataActivityBundle.putString("current_map_mode",current_map_mode);

        // Fragment transaction code moved here
        MapFragment myObj = new MapFragment();
        myObj.setArguments(dataActivityBundle);
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        mapFragment = SupportMapFragment.newInstance();
        ft.replace(R.id.map,mapFragment).commit();
        Log.i("Rotate","Arguments : "+String.valueOf(mapFragment.getArguments()));

        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View v = inflater.inflate(R.layout.fragment_map, container, false);

        // Fragment transaction logic no longer here

        // Call private functions without initializing the object's own class
        getMapAsync(this);

       if (getArguments() != null) {

            current_zoom = getArguments().getFloat("current_zoom");
            current_target = getArguments().getParcelable("current_target");
            current_bearing = getArguments().getFloat("current_bearing");
            current_map_mode = getArguments().getString("current_map_mode");

            Log.i("Rotate","onCreateView : getArguments() != null");
            Log.i("Rotate","current_zoom "+getArguments().getFloat("current_zoom"));
            Log.i("Rotate","current_target "+getArguments().getParcelable("current_target"));
            Log.i("Rotate","current_bearing "+getArguments().getFloat("current_bearing"));
            Log.i("Rotate","current_map_mode "+getArguments().getString("current_map_mode"));
        }
}


答:
The name of your container is the host name of the container.

If you have containers named webphp5 and webphp7. You can do something like this:

```<code>$ docker exec -it webphp5 bash #login into the container via console
$ curl -X GET 'webphp7'
</code>```

This is curl the you webphp7 container provided that you have your ports that you are trying to access open.

Title: How make cURL request between two docker container?

Body:
I'm working with docker on differents projects. I've a nginx conatainer and two php container : one for my projets in php5.6 and another for php7.0 project's.

I need to to make a cURL request between my two php container (from 5.6 to 7) but I have no idea of how make it. I've try somthing with the different host file but I only get a Connection timed out or a Connection refused.

curl -X GET 'hostUrl'

When the hostUrl is the php7 docker ip I get the Connection timed out and when hostUrl is 127.0.0.1 I get the Connection refused error.

They are in the same networks in my docker-compose.

What can I do to solve my problem ?

Thanks

Body:
The name of your container is the host name of the container.

If you have containers named webphp5 and webphp7. You can do something like this:

$ docker exec -it webphp5 bash #login into the container via console
$ curl -X GET 'webphp7'

This is curl the you webphp7 container provided that you have your ports that you are trying to access open.


问:
Protractor Not able to click the element While iterating the list of Elements
clickClaimIDFromList(claimId) {

```<code>   element.all(by.xpath('//*[@data-qa="dashboard.claim"]')).then(async (items) => {
            // console.log(items[0].getText());
            await expect(items[0].getText()).to.eventually.equal('12345');

            items.forEach(item => {
                     item.getText().then(async (text) => {
                            if (text === '12345') {
                                await console.log(item.getText());
                                await this.wait(10000);
                                return item.click();
                            }
                        }
                    );
                }
            );
        }

     );

}
</code>```

This code is getting executed successfully with out clicking the element. Could some one help me to rewrite it?

答:
Executable code:

async clickClaimIDFromList() {

```<code>    const allElems = await element.all(by.xpath('//*[@data-qa="dashboard.claim"]'));

    for (let i = 0; i < allElems.length; i++) {
        const item = allElems[i];

        // Save the result of the getText to a variable
        const itemText = await item.getText();
        console.log(itemText);

        if (itemText === '123124214') {
            await this.wait(10000);

            // No need to return the click, we can await it here
            await item.click();
        } else {
            console.log('else is being hit');
        }

    }
}
</code>```

Body:
clickClaimIDFromList(claimId) {

   element.all(by.xpath('//*[@data-qa="dashboard.claim"]')).then(async (items) => {
            // console.log(items[0].getText());
            await expect(items[0].getText()).to.eventually.equal('12345');

            items.forEach(item => {
                     item.getText().then(async (text) => {
                            if (text === '12345') {
                                await console.log(item.getText());
                                await this.wait(10000);
                                return item.click();
                            }
                        }
                    );
                }
            );
        }

     );

}

This code is getting executed successfully with out clicking the element. Could some one help me to rewrite it?

Body:
Executable code:

async clickClaimIDFromList() {

    const allElems = await element.all(by.xpath('//*[@data-qa="dashboard.claim"]'));

    for (let i = 0; i < allElems.length; i++) {
        const item = allElems[i];

        // Save the result of the getText to a variable
        const itemText = await item.getText();
        console.log(itemText);

        if (itemText === '123124214') {
            await this.wait(10000);

            // No need to return the click, we can await it here
            await item.click();
        } else {
            console.log('else is being hit');
        }

    }
}


问:
Cucumber 4 jvm rerun failed tests in jenkins using shell command
I added execution command to my jenkins shell command:

```<code>cd apitests && ./gradlew cucumber -Pthreads=${THREADS} -Ptags="not @notReady" && [ -s rerun/failed_scenarios.txt ] && ./gradlew cucumber -PfeaturePath='@rerun/failed_scenarios.txt' -Pthreads=80 || echo "File empty"
</code>```

In gradle I added task with cucumber options I set to save failed test to file:

```<code>cucumber {
    threads = 50
    glue = 'classpath:com.sixtleasing.cucumber.steps'
    plugin = ["pretty", "html:target/zucchini", "json:target/zucchini.json", "rerun:rerun/failed_scenarios.txt"]
    (...)
}
</code>```

Everything works when all tests are green. The problem starts when one of tests fails. In that case I see in the console:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':cucumber'.
> java.lang.RuntimeException: The execution failed

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
</code>```

why? If I run commands separatly it works but in jenkins as a one shell command it doesn't

答:
If the first invocation of gradle with cucumber fails, then nothing to the right of && is executed.  This is because the return code of the the gradlew process is non-zero if the build fails.

Give this a try:

```<code>cd apitests && ./gradlew cucumber -Pthreads=${THREADS} -Ptags="not @notReady" || ( [ -s rerun/failed_scenarios.txt ] && ./gradlew cucumber -PfeaturePath='@rerun/failed_scenarios.txt' -Pthreads=80 || echo "File empty" )
</code>```

Body:
I added execution command to my jenkins shell command:

cd apitests && ./gradlew cucumber -Pthreads=${THREADS} -Ptags="not @notReady" && [ -s rerun/failed_scenarios.txt ] && ./gradlew cucumber -PfeaturePath='@rerun/failed_scenarios.txt' -Pthreads=80 || echo "File empty"

In gradle I added task with cucumber options I set to save failed test to file:

cucumber {
    threads = 50
    glue = 'classpath:com.sixtleasing.cucumber.steps'
    plugin = ["pretty", "html:target/zucchini", "json:target/zucchini.json", "rerun:rerun/failed_scenarios.txt"]
    (...)
}

Everything works when all tests are green. The problem starts when one of tests fails. In that case I see in the console:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':cucumber'.
> java.lang.RuntimeException: The execution failed

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

why? If I run commands separatly it works but in jenkins as a one shell command it doesn't

Body:
If the first invocation of gradle with cucumber fails, then nothing to the right of && is executed.  This is because the return code of the the gradlew process is non-zero if the build fails.

Give this a try:

cd apitests && ./gradlew cucumber -Pthreads=${THREADS} -Ptags="not @notReady" || ( [ -s rerun/failed_scenarios.txt ] && ./gradlew cucumber -PfeaturePath='@rerun/failed_scenarios.txt' -Pthreads=80 || echo "File empty" )


问:
Tkinter Combobox accepting array as values
I am using a Combobox within a Tkinter GUI. The set-up is as follows:

```<code>list = np.arange(10)
var = IntVar(value=list[0])
box = ttk.Combobox(root, textvariable=var, value=list)
</code>```

It works as expected; but there is only one problem - for the first and last values of the drop-down list, the square brackets are attached to the integer.

You can see this from:

```<code>box['values']
</code>```

The output for this is:

```<code>('[0', '1', '2', '3', '4', '5', '6', '7', '8', '9]')
</code>```

You can see why the problem appears, check the first and last string characters within box['values'].

I need to remove this, since I am using the combobox value directly as the index location of another array. Therefore, it gives an error when the first/last element of the list are selected.

答:
You can first convert you numpy array to a list by tolist().

```<code>import tkinter as tk
from tkinter import ttk
import numpy as np

root = tk.Tk()
list = np.arange(10).tolist()

box = ttk.Combobox(root, value=list)
box.pack()

root.mainloop()
</code>```

Body:
I am using a Combobox within a Tkinter GUI. The set-up is as follows:

list = np.arange(10)
var = IntVar(value=list[0])
box = ttk.Combobox(root, textvariable=var, value=list)

It works as expected; but there is only one problem - for the first and last values of the drop-down list, the square brackets are attached to the integer.

You can see this from:

box['values']

The output for this is:

('[0', '1', '2', '3', '4', '5', '6', '7', '8', '9]')

You can see why the problem appears, check the first and last string characters within box['values'].

I need to remove this, since I am using the combobox value directly as the index location of another array. Therefore, it gives an error when the first/last element of the list are selected.

Body:
You can first convert you numpy array to a list by tolist().

import tkinter as tk
from tkinter import ttk
import numpy as np

root = tk.Tk()
list = np.arange(10).tolist()

box = ttk.Combobox(root, value=list)
box.pack()

root.mainloop()


问:
The exception of "Expected end of statement or expression"
The code is shown below and the error was come with underline code "user.id"/>&&nowPage=".</p>

```<code>function goPage() {
    var currentPage = parseInt($("#currentPage").val());
    var selectedPage = parseInt($("#selectPage").val());
    if (selectedPage != 0 && selectedPage != currentPage) {
       document.goPageForm.action = "user_ManageUserAllTopics.action?user.id= <s:property value="user.id"/>&&nowPage="+selectedPage;
       goPageForm.submit();
   }
}
</code>```

答:
You have given two && remove one & when you pass second parameter in url,also change "" to '' like below :

```<code> document.goPageForm.action = "user_ManageUserAllTopics.action?user.id= <s:property
 value='user.id'/>&nowPage="+selectedPage;
      //^ use single quote and remove  one &
</code>```

Body:
The code is shown below and the error was come with underline code "user.id"/>&&nowPage=".

function goPage() {
    var currentPage = parseInt($("#currentPage").val());
    var selectedPage = parseInt($("#selectPage").val());
    if (selectedPage != 0 && selectedPage != currentPage) {
       document.goPageForm.action = "user_ManageUserAllTopics.action?user.id= <s:property value="user.id"/>&&nowPage="+selectedPage;
       goPageForm.submit();
   }
}

Body:
You have given two && remove one & when you pass second parameter in url,also change "" to '' like below :

 document.goPageForm.action = "user_ManageUserAllTopics.action?user.id= <s:property
 value='user.id'/>&nowPage="+selectedPage;
      //^ use single quote and remove  one &


问:
How to handle new browser pop up after clicking a js button in Watir?
I am trying to using watir in ruby, I am able open a browser,
enter some values to a username/password form, but then I press enter, then I click the submit button (actually it is pressing an enter, it is easiler to code), it would pop up a new browser windows for our application, then I found I have no control to the new browser. What can I do?

In addition to my problem, the new browser window got no menubar, no toolbar, no navigation bar, thus I cannot open the IE developer toolbar to find the name of the element in the webpage in the new browser.

By the way, my app can only support IE.

I tried the attach method, but it does work:

C:/Ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb:302:

in `attach_browser_window': Unable to locate a window with title of (?-mix:New browser title) (Watir::Exception::NoMatchingWindowFoundException)

```<code>    from C:/Ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb
</code>```

:150:in `_attach_init'

```<code>    from C:/Ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb
</code>```

:144:in `attach'
        from test1.rb:36

答:
ok, there's  possibly this solution that might work:

```<code>b = Watir::Browser.start "http://yourpage"

b.execute_script("document.getElementById('your-image-id').onClick = function() {}")
</code>```

so, the idea is to get that image and overwrite it's onclick event

Body:
I am trying to using watir in ruby, I am able open a browser,
enter some values to a username/password form, but then I press enter, then I click the submit button (actually it is pressing an enter, it is easiler to code), it would pop up a new browser windows for our application, then I found I have no control to the new browser. What can I do?

In addition to my problem, the new browser window got no menubar, no toolbar, no navigation bar, thus I cannot open the IE developer toolbar to find the name of the element in the webpage in the new browser.

By the way, my app can only support IE.

I tried the attach method, but it does work:

C:/Ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb:302:

in `attach_browser_window': Unable to locate a window with title of (?-mix:New browser title) (Watir::Exception::NoMatchingWindowFoundException)

    from C:/Ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb

:150:in `_attach_init'

    from C:/Ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb

:144:in `attach'
        from test1.rb:36

Body:
ok, there's  possibly this solution that might work:

b = Watir::Browser.start "http://yourpage"

b.execute_script("document.getElementById('your-image-id').onClick = function() {}")

so, the idea is to get that image and overwrite it's onclick event


问:
Export CSV Writes Results to Single Line, How Do I get Multiple Lines?
I am looking for duplicates on a share drive so I can let the users know and they can clean it up before we use anything automated. My largest duplicate is close to 400 copies, but the info is all on a single line.

My query is getting the correct results:

$a = Get-ChildItem -Path "S:\" -File -Recurse |
     Select-Object -Property Fullname, @{N='Hash';E={(Get-FileHash $_.FullName).Hash}}

$cnt = $a | Group-Object -Property Hash

$cnt |
    Select-Object Count, @{N='FullName';E={($_.Group).FullName}}, @{N='Hash';E={($_.Group).Hash}} |
    Sort-Object -Property Count -Descending |
    Export-Csv C:\Temp\S_Drive_Counts.csv
```

<p>Here is an example of my results where each entry is on a single line:</p>

```
"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83 498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
```

<p>I need to pass this info on though, so I'd like to have each entry on a line by itself, similar to this:</p>

```
"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
"2","S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
```

I can do some string manipulation to the CSV if needed, but I am looking for a way to get it in the correct format before exporting to the CSV.

答:
Unroll your groups. Also, make better use of the pipeline.

Get-ChildItem -Path 'S:\' -File -Recurse |
    Select-Object Fullname, @{n='Hash';e={(Get-FileHash $_.FullName).Hash}} |
    Group-Object Hash |
    ForEach-Object {
        $cnt = $_.Count
        $_.Group | Select-Object @{n='Count';e={$cnt}}, FullName, Hash
    } |
    Sort-Object Count, Hash, FullName -Descending |
    Export-Csv 'C:\Temp\S_Drive_Counts.csv' -NoType
```

Body:
I am looking for duplicates on a share drive so I can let the users know and they can clean it up before we use anything automated. My largest duplicate is close to 400 copies, but the info is all on a single line.

My query is getting the correct results:

$a = Get-ChildItem -Path "S:\" -File -Recurse |
     Select-Object -Property Fullname, @{N='Hash';E={(Get-FileHash $_.FullName).Hash}}

$cnt = $a | Group-Object -Property Hash

$cnt |
    Select-Object Count, @{N='FullName';E={($_.Group).FullName}}, @{N='Hash';E={($_.Group).Hash}} |
    Sort-Object -Property Count -Descending |
    Export-Csv C:\Temp\S_Drive_Counts.csv

Here is an example of my results where each entry is on a single line:

"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83 498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"

I need to pass this info on though, so I'd like to have each entry on a line by itself, similar to this:

"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
"2","S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"

I can do some string manipulation to the CSV if needed, but I am looking for a way to get it in the correct format before exporting to the CSV.


问:
Regex: split object notation path string with array support
I've got a recursive function to go through an object and take what is needed using path string like jsonObj.object.item.value. The idea is to upgrade it somehow to support arrays.

```<code>const getValue = function(pathVar, obj) {
  obj = obj || x;
  // get very first node and the rest
  let [node, restNodes] = pathVar.split(/\.(.+)/, 2)
  // get interim object
  ret = obj[node];
  if(ret === undefined) return undefined;
  // pass rest of the nodes further with interim object
  if(restNodes) return getValue(restNodes, ret);
  return ret;
};
</code>```

Right now on each iteration simple regexp splits path string like jsonObj.object.item.value into jsonObj and object.item.value

the idea is to add array support here, so I can do transformations like

car.engine.something => car and engine.something

wheels[2].material.name => wheels and [2].material.name

[2].material.name => 2 and material.name

car.wheels[4] => car and wheels[4]

Any ideas how to do it?

答:
You could use eval which will just evaluate the expression. As for a functional approach, use the following.

```<code>function getValue(path, obj) {
    obj = obj || self; // self is the global window variable
    if( !path )
        return obj;

    let pattern = /(?:\["?)?(\w+)(?:\.|"?])?(.*)/i;

    let [ full, property, rest ] = path.match(pattern);
    return getValue( rest, obj[ property ] );
}

self.obj = { foo: [ 2, {bar: "baz"} ] };
console.log(getValue('obj.foo[1]["bar"]')) // 'baz'
</code>```

Pattern uses four groups. The first is non-capturing and expects a possible ["this will help match array or object properties. Then we expect a series of alphanumerics which we capture. Then another non capturing group to either close "] or match a .. Finally we capture the rest to use in the next call.

Again eval is capable of all of this.

Body:
I've got a recursive function to go through an object and take what is needed using path string like jsonObj.object.item.value. The idea is to upgrade it somehow to support arrays.

const getValue = function(pathVar, obj) {
  obj = obj || x;
  // get very first node and the rest
  let [node, restNodes] = pathVar.split(/\.(.+)/, 2)
  // get interim object
  ret = obj[node];
  if(ret === undefined) return undefined;
  // pass rest of the nodes further with interim object
  if(restNodes) return getValue(restNodes, ret);
  return ret;
};

Right now on each iteration simple regexp splits path string like jsonObj.object.item.value into jsonObj and object.item.value

the idea is to add array support here, so I can do transformations like

car.engine.something => car and engine.something

wheels[2].material.name => wheels and [2].material.name

[2].material.name => 2 and material.name

car.wheels[4] => car and wheels[4]

Any ideas how to do it?

Body:
You could use eval which will just evaluate the expression. As for a functional approach, use the following.

function getValue(path, obj) {
    obj = obj || self; // self is the global window variable
    if( !path )
        return obj;

    let pattern = /(?:\["?)?(\w+)(?:\.|"?])?(.*)/i;

    let [ full, property, rest ] = path.match(pattern);
    return getValue( rest, obj[ property ] );
}

self.obj = { foo: [ 2, {bar: "baz"} ] };
console.log(getValue('obj.foo[1]["bar"]')) // 'baz'

Pattern uses four groups. The first is non-capturing and expects a possible ["this will help match array or object properties. Then we expect a series of alphanumerics which we capture. Then another non capturing group to either close "] or match a .. Finally we capture the rest to use in the next call.

Again eval is capable of all of this.


问:
How do I create a timer for 1 second in java?
I need to make an image bounce on the screen. I am trying to do this by shifting the image up 5 units, then taking a one second break, then shifting another 5 units up, etc. I am trying to shift up 5 times and then shifting down 5 times, with a one second break between each shift. I need help making the timer for one second so it acts like a break between each shift. I need to write the time() method. </p>

```<code>public void moveIt(KeyEvent evt) throws InterruptedException {
    switch (evt.getKeyCode()) {
    case KeyEvent.VK_DOWN:
        myY += 0;
        break;
    case KeyEvent.VK_UP:
        for (int i = 1; i <= 10; i++) {
            if (i <= 5) {
                bounceUp();
            } else {
                bounceDown();
            }
            time();
        }
        break;
    case KeyEvent.VK_LEFT:
        myX -= 5;
        break;
    case KeyEvent.VK_RIGHT:
        myX += 5;
        break;
    }

    repaint();
}

Timer timer = new Timer();

public void bounceUp() throws InterruptedException {
    myY -= 10;
}

public void bounceDown() throws InterruptedException {
    myY += 10;
}

public void time() {
}
</code>```

答:
Welcome to SO!
Try using the schedule in Timer, like this:

```<code>Timer timer = new Timer();
timer.schedule(new YourClass(), 0, 1000);
</code>```

Also, here's a great answer on the same issue:
https://stackoverflow.com/a/12908477/10713658

Body:
I need to make an image bounce on the screen. I am trying to do this by shifting the image up 5 units, then taking a one second break, then shifting another 5 units up, etc. I am trying to shift up 5 times and then shifting down 5 times, with a one second break between each shift. I need help making the timer for one second so it acts like a break between each shift. I need to write the time() method.

public void moveIt(KeyEvent evt) throws InterruptedException {
    switch (evt.getKeyCode()) {
    case KeyEvent.VK_DOWN:
        myY += 0;
        break;
    case KeyEvent.VK_UP:
        for (int i = 1; i <= 10; i++) {
            if (i <= 5) {
                bounceUp();
            } else {
                bounceDown();
            }
            time();
        }
        break;
    case KeyEvent.VK_LEFT:
        myX -= 5;
        break;
    case KeyEvent.VK_RIGHT:
        myX += 5;
        break;
    }

    repaint();
}

Timer timer = new Timer();

public void bounceUp() throws InterruptedException {
    myY -= 10;
}

public void bounceDown() throws InterruptedException {
    myY += 10;
}

public void time() {
}

Body:
Welcome to SO!
Try using the schedule in Timer, like this:

Timer timer = new Timer();
timer.schedule(new YourClass(), 0, 1000);

Also, here's a great answer on the same issue:
https://stackoverflow.com/a/12908477/10713658


问:
Laravel - display a PDF file in storage without forcing download?
I have a PDF file stored in app/storage/, and I want authenticated users to be able to view this file. I know that I can make them download it using

```<code>return Response::download($path, $filename, $headers);
</code>```

but I was wondering if there is a way to make them view the file directly in the browser, for example when they are using Google Chrome with the built-in PDF viewer. Any help will be appreciated!

答:
Laravel 5.6.*

```<code>$name = 'file.jpg';
</code>```

store on image or pdf

```<code>$file->storeAs('public/', $name );
</code>```

download image or pdf

```<code>return response()->download($name);
</code>```

view image or pdf

```<code>return response()->file($name);
</code>```

Body:
I have a PDF file stored in app/storage/, and I want authenticated users to be able to view this file. I know that I can make them download it using

return Response::download($path, $filename, $headers);

but I was wondering if there is a way to make them view the file directly in the browser, for example when they are using Google Chrome with the built-in PDF viewer. Any help will be appreciated!

Body:
Laravel 5.6.*

$name = 'file.jpg';

store on image or pdf

$file->storeAs('public/', $name );

download image or pdf

return response()->download($name);

view image or pdf

return response()->file($name);


问:
Split Rectangle in Categories of sub rectangles
Given a rectangle i would like to split it in a given amount n of sub-rectangles where:

a is the amount of subrectangles which should have a defined z SMALL area

b is the amount of subrectangles which should have a defined y MEDIUM area

c is the amount of subrectangles which should have a defined x BIGGER area
may be I should be able to define d and e . But let's leave them for now.

With "defined area" i mean the geometric area should be the same but the rectangles could have different shape.
May I ask ..which algorithm would You suggest to apply in this case.

I should have a function like this PSEUDO code:

```<code>RectBoundaries[] function getRectangles(screenRectangle, amountOfRectangleCategories, amountOfRectanglesPerCategory[]) {
   function1 => getRectanglesForCategory1(amountOfRectanglesPerCategory[0], screenRectangle)
   function2 => getRectanglesForCategory2(amountOfRectanglesPerCategory[1], screenRectangle)
   function3 => getRectanglesForCategory3(amountOfRectanglesPerCategory[2], screenRectangle)

   return function1 + function2 + function3;
}
</code>```

EDITED:
How to split a rectangle in multiple (defined amount of) categories of decreasing smaller rectangles.

答:
By your question I understand you first split your main area in 3 area. One big, one medium and one small. Given this I made a small algo in Javascript, hope it solve your problem

let canvas = document.getElementById("output");
let ctx = canvas.getContext('2d');
ctx.strokeStyle = 'rgb(255, 255, 255)';

function draw(rect) {
  ctx.rect(rect[0], rect[1], rect[2], rect[3]);
  ctx.stroke();
}

function splitArea(rect, nbRect) {
  let [nbColumns, nbLines] = getBestRatio(nbRect);
  let x=rect[0];
  let y=rect[1];
  let width = rect[2]/nbColumns;
  let height = rect[3]/nbLines;
  let result = new Array();

  for(let i=0; i<nbLines; i++) {
    for(let j=0; j<nbColumns; j++) {
      result.push([x+j*width, y+i*height, width, height]);
    }
  }

  return result;
}

function getBestRatio(nb) {
  for(let i=Math.round(Math.sqrt(nb)); i>0; i--) {
    if(nb%i==0) {
      return [i, nb/i];
    }
  }
}

//main rectangle
let rect = [10, 10, 280, 280]; //x, y, width, height

// 3 differents area
let bigArea = [rect[0], rect[1], rect[2], rect[3]*2/3]; // 2∕3 area
let mediumArea = [rect[0], rect[1]+rect[3]*2/3, rect[2]*2/3, rect[3]*1/3]; // 2/3 * 1/3 area
let smallArea = [rect[0]+rect[2]*2/3, rect[1]+rect[3]*2/3, rect[2]*1/3, rect[3]*1/3]; // 1/3 * 1/3 area

draw(bigArea);
draw(mediumArea);
draw(smallArea);

splitArea(bigArea, 6).forEach(area => draw(area));
splitArea(mediumArea, 12).forEach(area => draw(area));
splitArea(smallArea, 3).forEach(area => draw(area));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="output" height="300px" width="300px" style="background-color: grey"></code>```

Body:
Given a rectangle i would like to split it in a given amount n of sub-rectangles where:

a is the amount of subrectangles which should have a defined z SMALL area

b is the amount of subrectangles which should have a defined y MEDIUM area

c is the amount of subrectangles which should have a defined x BIGGER area
may be I should be able to define d and e . But let's leave them for now.

With "defined area" i mean the geometric area should be the same but the rectangles could have different shape.
May I ask ..which algorithm would You suggest to apply in this case.

I should have a function like this PSEUDO code:

RectBoundaries[] function getRectangles(screenRectangle, amountOfRectangleCategories, amountOfRectanglesPerCategory[]) {
   function1 => getRectanglesForCategory1(amountOfRectanglesPerCategory[0], screenRectangle)
   function2 => getRectanglesForCategory2(amountOfRectanglesPerCategory[1], screenRectangle)
   function3 => getRectanglesForCategory3(amountOfRectanglesPerCategory[2], screenRectangle)

   return function1 + function2 + function3;
}

EDITED:
How to split a rectangle in multiple (defined amount of) categories of decreasing smaller rectangles.

Body:
By your question I understand you first split your main area in 3 area. One big, one medium and one small. Given this I made a small algo in Javascript, hope it solve your problem

let canvas = document.getElementById("output");
let ctx = canvas.getContext('2d');
ctx.strokeStyle = 'rgb(255, 255, 255)';

function draw(rect) {
  ctx.rect(rect[0], rect[1], rect[2], rect[3]);
  ctx.stroke();
}

function splitArea(rect, nbRect) {
  let [nbColumns, nbLines] = getBestRatio(nbRect);
  let x=rect[0];
  let y=rect[1];
  let width = rect[2]/nbColumns;
  let height = rect[3]/nbLines;
  let result = new Array();

  for(let i=0; i<nbLines; i++) {
    for(let j=0; j<nbColumns; j++) {
      result.push([x+j*width, y+i*height, width, height]);
    }
  }

  return result;
}

function getBestRatio(nb) {
  for(let i=Math.round(Math.sqrt(nb)); i>0; i--) {
    if(nb%i==0) {
      return [i, nb/i];
    }
  }
}

//main rectangle
let rect = [10, 10, 280, 280]; //x, y, width, height

// 3 differents area
let bigArea = [rect[0], rect[1], rect[2], rect[3]*2/3]; // 2∕3 area
let mediumArea = [rect[0], rect[1]+rect[3]*2/3, rect[2]*2/3, rect[3]*1/3]; // 2/3 * 1/3 area
let smallArea = [rect[0]+rect[2]*2/3, rect[1]+rect[3]*2/3, rect[2]*1/3, rect[3]*1/3]; // 1/3 * 1/3 area

draw(bigArea);
draw(mediumArea);
draw(smallArea);

splitArea(bigArea, 6).forEach(area => draw(area));
splitArea(mediumArea, 12).forEach(area => draw(area));
splitArea(smallArea, 3).forEach(area => draw(area));

<canvas id="output" height="300px" width="300px" style="background-color: grey">