问:
How to delete property in JS and map new object?
wanted to remove properties that has matching errorCode and transform new object once all filtering is done, I am not getting below expected response any idea what is the issue with below code ?

if settlementCode matches with drugPriceErrors findErrCode should return true.

main.js

```<code>const data = [{
            "isBrand": true,
            "drugName": "Lipitor",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "85",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        },
        {
            "isBrand": false,
            "drugName": "Atorvastatin Calcium",
            "drugStrength": "80mg",
            "drugForm": "Tablet",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ];

const drugPricesErrors = [99,45,89];

function filterDrugs (data) {
  const response = [];
const _drugPrice = data.map(item => {
        const retailHasCode = findErrCode(item.retailPrice.rejectMessage);
        const mailHasCode = findErrCode (item.mailPrice.rejectMessage);

        if(retailHasCode) {
            delete item.retailPrice;
        }

        if(mailHasCode) {
            delete item.mailPrice;
        }

  return item;

    });

    _.forEach(_drugPrice, function(drug) {
        if(drug.retailPrice !== undefined || drug.mailPrice !== undefined){
            response.push(drug);
        }
    });

  return response;
}

function findErrCode(data) {
    const filterMessage = data.filter( message => drugPriceErrors.includes(item.settlementCode));
    return filterMessage;
}
</code>```

expected output

```<code>[{
            "isBrand": true,
            "drugName": "Lipitor",
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "85",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ]
</code>```

答:
Update your findErrCode to something like this:

```<code>let findErrCode = data =>
  data.some(i => drugPriceErrors.includes(Number(i.settlementCode)))
</code>```

Key is to use Number to convert your settlementCode so the Array.some works. Also use Array.some since you only care if the result is true or false (Boolean). Array.filter would actually return records etc.

You can see it working here

Body:
wanted to remove properties that has matching errorCode and transform new object once all filtering is done, I am not getting below expected response any idea what is the issue with below code ?

if settlementCode matches with drugPriceErrors findErrCode should return true.

main.js

const data = [{
            "isBrand": true,
            "drugName": "Lipitor",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "85",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        },
        {
            "isBrand": false,
            "drugName": "Atorvastatin Calcium",
            "drugStrength": "80mg",
            "drugForm": "Tablet",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ];

const drugPricesErrors = [99,45,89];

function filterDrugs (data) {
  const response = [];
const _drugPrice = data.map(item => {
        const retailHasCode = findErrCode(item.retailPrice.rejectMessage);
        const mailHasCode = findErrCode (item.mailPrice.rejectMessage);

        if(retailHasCode) {
            delete item.retailPrice;
        }

        if(mailHasCode) {
            delete item.mailPrice;
        }

  return item;

    });

    _.forEach(_drugPrice, function(drug) {
        if(drug.retailPrice !== undefined || drug.mailPrice !== undefined){
            response.push(drug);
        }
    });

  return response;
}

function findErrCode(data) {
    const filterMessage = data.filter( message => drugPriceErrors.includes(item.settlementCode));
    return filterMessage;
}

expected output

[{
            "isBrand": true,
            "drugName": "Lipitor",
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "85",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ]

Body:
Update your findErrCode to something like this:

let findErrCode = data =>
  data.some(i => drugPriceErrors.includes(Number(i.settlementCode)))

Key is to use Number to convert your settlementCode so the Array.some works. Also use Array.some since you only care if the result is true or false (Boolean). Array.filter would actually return records etc.

You can see it working here


来源: stackexchange

问:
How do plugins identify what type of server a website is running on?
I have tested a few plugins for Firefox and Chrome which can identify IP number of a given website ofcause. But some of them can also show what server-side technology the website runs on.

How do they do this? I know about client-user-agent, is there something similar in the HTTP protocol where the server sendes a "server-host-agent" kinda string?

And if so, how would the code for retreiving this look. I guess its something with WebClient?

Anyone?

答:
Using the HttpWebRequest and setting the Method property to HEAD, you can do a HTTP HEAD request, which is very lightweight. It will return the HTTP Headers (which may or may not be correct). They HTTP Headers may also differ from server to server as there is no standard for what headers a server should expose.

The code:

```<code>HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
myReq.Method = "HEAD";
WebResponse myRes = myReq.GetResponse();
for(int i=0; i < myHttpWebResponse.Headers.Count; ++i) {
   Console.WriteLine(
      "\nHeader Name:{0}, Value :{1}",
      myHttpWebResponse.Headers.Keys[i], myHttpWebResponse.Headers[i]
   );
}
</code>```

EDIT:

```<code>var request = (HttpWebRequest)WebRequest.Create("http://www.http500.com");
try
{
    var response = request.GetResponse();
}
catch (WebException wex)
{
    // Safe cast to HttpWebResponse using 'as', will return null if unsuccessful
    var httpWebResponse = wex.Response as HttpWebResponse;
    if(httpWebResponse != null)
    {
        var httpStatusCode = httpWebResponse.StatusCode;
        // HttpStatusCode is an enum, cast it to int for its actual value
        var httpStatusCodeInt = (int)httpWebResponse.StatusCode;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using the HttpWebRequest and setting the Method property to HEAD, you can do a HTTP HEAD request, which is very lightweight. It will return the HTTP Headers (which may or may not be correct). They HTTP Headers may also differ from server to server as there is no standard for what headers a server should expose.

The code:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
myReq.Method = "HEAD";
WebResponse myRes = myReq.GetResponse();
for(int i=0; i < myHttpWebResponse.Headers.Count; ++i) {
   Console.WriteLine(
      "\nHeader Name:{0}, Value :{1}",
      myHttpWebResponse.Headers.Keys[i], myHttpWebResponse.Headers[i]
   );
}

EDIT:

var request = (HttpWebRequest)WebRequest.Create("http://www.http500.com");
try
{
    var response = request.GetResponse();
}
catch (WebException wex)
{
    // Safe cast to HttpWebResponse using 'as', will return null if unsuccessful
    var httpWebResponse = wex.Response as HttpWebResponse;
    if(httpWebResponse != null)
    {
        var httpStatusCode = httpWebResponse.StatusCode;
        // HttpStatusCode is an enum, cast it to int for its actual value
        var httpStatusCodeInt = (int)httpWebResponse.StatusCode;
    }
}


问:
p:messages displays but disapear almost instantly
i have a strange problem with a p:message tag. On page a have a dataTable with data from my db that i can edit in a p:dialog. Once all validations succeds and the update in db is done i refresh the dataTable and add a faces message info to display the succes of the operation. In the front-end i update the form whom contains both the dataTable and the dialog. My problem is that the message is displayed but almost instantly disapears. It's like the message tag is updated with the form. I don't get it.

I have tried to move the message tag in & out of the form in didn't change anything.
I have tried to tweak the remoteCommand to update just the dataTable and the dialog but it didn't work.

```<code><p:messages autoUpdate="true" showDetail="true" severity="info,error" />
<h:form id="form">
    <p:dataTable
    style="width: 80%; margin-left: auto; margin-right: auto; text-align:center"
        var="achievement" value="#{achievementBean.listAchievement}">
    ...
    </p:dataTable>

    <p:dialog header="#{i18n['achievement']}" widgetVar="dlg"
        dynamic="true" closable="false" resizable="false" showEffect="fade"
        hideEffect="fade">
        <h:panelGroup id="achievementDetail">
            <p:messages autoUpdate="true" severity="warn" />
            ...
            <h:panelGrid columns="2" style="width: 100%; text-align:center">
                <p:commandButton value="#{i18n['general.submit']}"
                    icon="fa fa-check"
                    actionListener="#{achievementBean.submitAchievement}"
                    oncomplete="if(!args.validationFailed){updateForm();}" />
                <p:commandButton value="#{i18n['general.cancel']}"
                    icon="fa fa-close" action="#{achievementBean.submitCancel}"
                    oncomplete="PF('dlg').hide();" update="@form" process="@this" />
            </h:panelGrid>
            <p:remoteCommand name="updateForm" update="@form" />
        </h:panelGroup>
    </p:dialog>
</h:form>
</code>```

答:
Thanks for yours answers. Sorry about the mre i always forget about it. I'll try to not forget it next time.
I finally managed to solve my problem.

I added an id to the first

I added an update of this id in the submit

ContentLicense: CC BY-SA 4.0

Body:
i have a strange problem with a p:message tag. On page a have a dataTable with data from my db that i can edit in a p:dialog. Once all validations succeds and the update in db is done i refresh the dataTable and add a faces message info to display the succes of the operation. In the front-end i update the form whom contains both the dataTable and the dialog. My problem is that the message is displayed but almost instantly disapears. It's like the message tag is updated with the form. I don't get it.

I have tried to move the message tag in & out of the form in didn't change anything.
I have tried to tweak the remoteCommand to update just the dataTable and the dialog but it didn't work.

<h:form id="form">

    ...

        <h:panelGroup id="achievementDetail">

            ...
            <h:panelGrid columns="2" style="width: 100%; text-align:center">

            </h:panelGrid>

        </h:panelGroup>

</h:form>

Body:
Thanks for yours answers. Sorry about the mre i always forget about it. I'll try to not forget it next time.
I finally managed to solve my problem.

I added an id to the first <p:message>

I added an update of this id in the submit <p:commandButton>


问:
Boggle type word checker using jquery
I am trying to create a variation of a Boggle type word checker using jQuery. The variation is that a letter can be used more than once and the board is always two lines.

I have been using a string divided in half as the 'board', and using a recursive function to search for a given word. I have looked at similar examples but cannot seem to code the function correctly.

For example, if the board string is OMRAWNLET. The board would look like:

```<code>O M R A W
N L E T
</code>```

It would return true if the word to search for is watermelon.  Can anyone please guide me or write the function? Thanks.

答:
If all you are wanting to check is if the inputted word is valid based on the letters on the board, you can do that rather simply. Just pass the letters as an array and input as a string. From there simply search letter by letter through input to see if it's in the letters array.

function validate_input(letters, input){
input = input.toUpperCase();

  var errors = input.split("").filter(function(letter){
    return (letters.indexOf(letter) == -1);
  });

 return (errors == "");
}

var letters = ["O","M","R","A","W","N","L","E","T"];

console.log(validate_input(letters, "lemfon"));
console.log(validate_input(letters, "watermelon"));```

Title: Boggle type word checker using jquery

Body:
I am trying to create a variation of a Boggle type word checker using jQuery. The variation is that a letter can be used more than once and the board is always two lines.

I have been using a string divided in half as the 'board', and using a recursive function to search for a given word. I have looked at similar examples but cannot seem to code the function correctly.

For example, if the board string is OMRAWNLET. The board would look like:

O M R A W
N L E T

It would return true if the word to search for is watermelon.  Can anyone please guide me or write the function? Thanks.


问:
How to invoke a c# function to fill value into razor html textbox?
I am using the function that fetches the output from PowerShell script into the output String variable. I need to call that function inside an @HTMLTextBox to load the value.

I have created the function and using razor format to invoke the function inside the textbox element.

```<code>@using System.Management.Automation
@functions {

public string PowerShellExecutor(string script) {
    var shell = PowerShell.Create();
    string outString = "";
    shell.Commands.AddScript(script);
    var results = shell.Invoke();
    if (results.Count>0)
    {
        var builder = new StringBuilder();
        foreach (var psObj in results)
        {
            builder.Append(psObj.BaseObject.ToString() + "\r\n");

        }
        outString = Server.HtmlEncode(builder.ToString());
    }
    return outString;
  }
}

<div class="col-md-12">
                @Html.TextBox("txtDirectory", @PowerShellExecutor("$env:USERDNSDOMAIN") , new { @class = "form-control", @type = "number"})
</div>
</code>```

The textbox is suppose to fill the value of the output obtained when the command is passed through the function. However, It shows blank.

答:
Remove the @ for the PowerShellExecutor and you should also remove  @type = "number" to make your text box accept a string.

```<code>@Html.TextBox("txtDirectory", PowerShellExecutor("$env:USERDNSDOMAIN") , new { @class = "form-control"})
</code>```

Body:
I am using the function that fetches the output from PowerShell script into the output String variable. I need to call that function inside an @HTMLTextBox to load the value.

I have created the function and using razor format to invoke the function inside the textbox element.

@using System.Management.Automation
@functions {

public string PowerShellExecutor(string script) {
    var shell = PowerShell.Create();
    string outString = "";
    shell.Commands.AddScript(script);
    var results = shell.Invoke();
    if (results.Count>0)
    {
        var builder = new StringBuilder();
        foreach (var psObj in results)
        {
            builder.Append(psObj.BaseObject.ToString() + "\r\n");

        }
        outString = Server.HtmlEncode(builder.ToString());
    }
    return outString;
  }
}

                @Html.TextBox("txtDirectory", @PowerShellExecutor("$env:USERDNSDOMAIN") , new { @class = "form-control", @type = "number"})

The textbox is suppose to fill the value of the output obtained when the command is passed through the function. However, It shows blank.

Body:
Remove the @ for the PowerShellExecutor and you should also remove  @type = "number" to make your text box accept a string.

@Html.TextBox("txtDirectory", PowerShellExecutor("$env:USERDNSDOMAIN") , new { @class = "form-control"})


问:
How to SET OUT parameter when my stored procedure gets error?
I'm writing stored procedure on mariadb 5.5 and trying to return error code when SQL EXCEPTION occurs in it.

My code is like below...

```<code>delimiter $$
CREATE PROCEDURE sp_test(
                             IN fooin  varchar(50),
                            INOUT fooout varchar(50)
                              )
BEGIN

   DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
      SET fooout = '9999'; #which means error
      RESIGNAL;
   END;

   SET fooout = '0000';
   select now_(); # Error happens here on my purpose
END$$
DELIMITER ;
</code>```

The result is like below...

```<code>MariaDB [emsdevdb]> call sp_test('foo',@result);
ERROR 1305 (42000): FUNCTION emsdevdb.now_ does not exist
MariaDB [emsdevdb]> select @result;
+---------+
| @result |
+---------+
| NULL    |
+---------+
1 row in set (0.00 sec)
</code>```

Why @result prints NULL instead of '9999'?

How to return my own error-code for the case of SQL EXCEPTION?

NULL value of out parameter means that stored procedure encount an error?

Any advice would be appreciated.

Thanks in advance.

答:
Try:

DELIMITER $$

DROP PROCEDURE IF EXISTS sp_test$$

CREATE PROCEDURE sp_test(
  IN fooin varchar(50),
  INOUT fooout varchar(50)
)
BEGIN
  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    SET fooout = '9999'; #which means error
    -- RESIGNAL;
  END;

  SET fooout = '0000';
  SELECT now_(); # Error happens here on my purpose
END$$

DELIMITER ;

SET @result := NULL;

CALL sp_test('foo', @result);

SELECT @result;
```

Body:
I'm writing stored procedure on mariadb 5.5 and trying to return error code when SQL EXCEPTION occurs in it.

My code is like below...

delimiter $$
CREATE PROCEDURE sp_test(
                             IN fooin  varchar(50),
                            INOUT fooout varchar(50)
                              )
BEGIN

   DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
      SET fooout = '9999'; #which means error
      RESIGNAL;
   END;

   SET fooout = '0000';
   select now_(); # Error happens here on my purpose
END$$
DELIMITER ;

The result is like below...

MariaDB [emsdevdb]> call sp_test('foo',@result);
ERROR 1305 (42000): FUNCTION emsdevdb.now_ does not exist
MariaDB [emsdevdb]> select @result;
+---------+
| @result |
+---------+
| NULL    |
+---------+
1 row in set (0.00 sec)

Why @result prints NULL instead of '9999'?

How to return my own error-code for the case of SQL EXCEPTION?

NULL value of out parameter means that stored procedure encount an error?

Any advice would be appreciated.

Thanks in advance.


问:
ViewController background color won't change
I've started a new project, and I'm trying to create it using MVC and a programmatic UI.

I'm trying to set a ViewController's background color, but it just won't change.

I have already written my programmatic UI, but I changed the background color in the ViewController itself, but not from the view.

This is my view:

import UIKit

class ReportView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.appColors.white
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
```

<p>This is my <code>ViewController</code>:</p>

<pre class="lang-swift prettyprint-override"><code>import UIKit

class ReportsVC: UIViewController {

    override func loadView() {
        view = ReportView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
</code>```

This is my AppDelegate:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var navigationController: UINavigationController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        self.window = UIWindow(frame: UIScreen.main.bounds)

        if let window = window{
            let reportsVC = ReportsVC()
            navigationController = UINavigationController(rootViewController: reportsVC)
            window.rootViewController = navigationController
            window.makeKeyAndVisible()
        }

        return true
    }
}
```

I tried changing the background color from the ViewController itself just to check, but it stayed the same.

答:
You need to add your view to the viewcontroller's content view this like :

```<code>self.view.addSubview(ReportView(frame: self.view.frame))
</code>```

The view needs to have a frame to be visible.

Body:
I've started a new project, and I'm trying to create it using MVC and a programmatic UI.

I'm trying to set a ViewController's background color, but it just won't change.

I have already written my programmatic UI, but I changed the background color in the ViewController itself, but not from the view.

This is my view:

import UIKit

class ReportView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.appColors.white
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

This is my ViewController:

import UIKit

class ReportsVC: UIViewController {

    override func loadView() {
        view = ReportView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

This is my AppDelegate:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var navigationController: UINavigationController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        self.window = UIWindow(frame: UIScreen.main.bounds)

        if let window = window{
            let reportsVC = ReportsVC()
            navigationController = UINavigationController(rootViewController: reportsVC)
            window.rootViewController = navigationController
            window.makeKeyAndVisible()
        }

        return true
    }
}

I tried changing the background color from the ViewController itself just to check, but it stayed the same.

Body:
You need to add your view to the viewcontroller's content view this like :

self.view.addSubview(ReportView(frame: self.view.frame))

The view needs to have a frame to be visible.


答:
```<code>  SELECT
  d.deviceId, d.deviceName, d.deviceDescription,
  dl.time_stamp, dl.FuelLevel, dl.Voltage
  FROM Device d, DataLog dl
  WHERE d.deviceId=dl.deviceID
  ORDER BY time_stamp DESC
  LIMIT 1
</code>```

Title: Joining one table to the latest row in another table using MySQL

Body:
I want to join two tables in a special way, first table is devices which has a list of devices.

The second table is datalog which is where abit of data is stored for everytime a device in devices gets polled.

Devices Table:

+----------+------------+----------------------------+---------------------+
| deviceId | deviceName | deviceDescription          | timeCreated         |
+----------+------------+----------------------------+---------------------+
|        1 | System 1   | Main System in Server Room | 2010-01-01 00:00:00 |
|        2 | System 2   | Outdoor System             | 2010-01-01 00:00:00 |
+----------+------------+----------------------------+---------------------+

DataLog Table:

+----+---------------------+----------+-----------+---------+
| id | time_stamp          | DeviceId | FuelLevel | Voltage |
+----+---------------------+----------+-----------+---------+
|  1 | 2010-01-01 00:00:00 |        1 |        60 |     220 |
|  2 | 2010-01-01 00:00:00 |        2 |        20 |     221 |
|  3 | 2010-01-02 00:00:00 |        1 |       100 |     219 |
|  4 | 2010-01-02 00:00:00 |        2 |       100 |     222 |
|  5 | 2010-01-03 00:00:00 |        1 |        80 |     219 |
|  6 | 2010-01-03 00:00:00 |        2 |        99 |     220 |
+----+---------------------+----------+-----------+---------+

Currently I am getting the latest data for each device using a query on the DataLog table with:

 Where DeviceId = 1 ORDER BY timestamp DESC LIMIT 1

What I would like is one query to return a list of all devices, with the columns joined with the latest data for each device like this:

+----------+------------+----------------------------+---------------------+-----------+---------+
| deviceId | deviceName | deviceDescription          | time_stamp          |FuelLevel  | Voltage |
+----------+------------+----------------------------+---------------------+-----------+---------+
|        1 | System 1   | Main System in Server Room | 2010-01-03 00:00:00 |        80 |     219 |
|        2 | System 2   | Outdoor System             | 2010-01-03 00:00:00 |       99  |     220 |
+----------+------------+----------------------------+---------------------+-----------+---------+


问:
Avoid retain cycles for function pointers in Swift
Let's start with this playground example

Example 1

```<code>import UIKit

internal final class TestClass1 {
    var testVar: Int = 1

    internal init() {
        print("TestClass1 init is called!")
    }

    deinit {
        print("TestClass1 deinit is called!")
    }

    internal func func1() {
        print("func1 is called!")
    }
}

internal final class TestClass2 {
    init() {
        let testClass1: TestClass1 = TestClass1()
        testClass1.testVar = 10
    }
}

var testClass2: TestClass2 = TestClass2()
</code>```

Output

TestClass1 init is called!

TestClass1 deinit is called!

Example 2

```<code>import UIKit

internal final class TestClass1 {
    internal final var funcPointer: (() -> ())!

    internal init() {
        self.funcPointer = self.func1
        print("TestClass1 init is called!")
    }

    deinit {
        print("TestClass1 deinit is called!")
    }

    internal func func1() {
        print("func1 is called!")
    }
}

internal final class TestClass2 {
    init() {
        let testClass1: TestClass1 = TestClass1()
        testClass1.funcPointer()
    }
}

var testClass2: TestClass2 = TestClass2()
</code>```

Output

TestClass1 init is called!

func1 is called!

My problem is, that the deinit() method is never called in example 2. I think there is a retain cycle but I don't know how to fix it.

I found this example and this SO post but I can't implement it in my example code.

答:
To fix it, you have to call the func1 through weak self.

```<code>internal init() {
    self.funcPointer = { [weak self] in
        self?.func1()
    }
    print("TestClass1 init is called!")
}
</code>```

This way you can prevent retain cycles.

What happens at the moment is that you are assigning an instance function to your instance property who now has a strong reference to your function.

Hope this helps.

Body:
Let's start with this playground example

Example 1

import UIKit

internal final class TestClass1 {
    var testVar: Int = 1

    internal init() {
        print("TestClass1 init is called!")
    }

    deinit {
        print("TestClass1 deinit is called!")
    }

    internal func func1() {
        print("func1 is called!")
    }
}

internal final class TestClass2 {
    init() {
        let testClass1: TestClass1 = TestClass1()
        testClass1.testVar = 10
    }
}

var testClass2: TestClass2 = TestClass2()

Output

TestClass1 init is called!

TestClass1 deinit is called!

Example 2

import UIKit

internal final class TestClass1 {
    internal final var funcPointer: (() -> ())!

    internal init() {
        self.funcPointer = self.func1
        print("TestClass1 init is called!")
    }

    deinit {
        print("TestClass1 deinit is called!")
    }

    internal func func1() {
        print("func1 is called!")
    }
}

internal final class TestClass2 {
    init() {
        let testClass1: TestClass1 = TestClass1()
        testClass1.funcPointer()
    }
}

var testClass2: TestClass2 = TestClass2()

Output

TestClass1 init is called!

func1 is called!

My problem is, that the deinit() method is never called in example 2. I think there is a retain cycle but I don't know how to fix it.

I found this example and this SO post but I can't implement it in my example code.

Body:
To fix it, you have to call the func1 through weak self.

internal init() {
    self.funcPointer = { [weak self] in
        self?.func1()
    }
    print("TestClass1 init is called!")
}

This way you can prevent retain cycles.

What happens at the moment is that you are assigning an instance function to your instance property who now has a strong reference to your function.

Hope this helps.


问:
Building Multiple URLs using modify_url
I created a page scrape function that scrapes some data.  I want to be able to create a list of URL's so that I can pass along more than 1 argument in the function call in order to build different URL's.  Is there a way to do this using httr::modify_url?

My code which creates a single URL is as follows:

```<code>library(tidyverse)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang
library(httr)

# Arguments for Function
hand = NULL
prp = "P"
month = NULL
year = 2019
pitch_type = "FA"
report_type = "pfx"
lim = 0

url <- httr::modify_url("https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php",
                        query = list(
                          hand = hand,
                          reportType = report_type,
                          prp = prp,
                          month = month,
                          year = year,
                          pitch = pitch_type,
                          ds = "velo",
                          lim = lim
                        ))

# Single Query Result
url
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=FA&ds=velo&lim=0"

</code>```

I was wondering if I could use the httr::modify_url query from above and  some combination of purrr::reduce(paste0) to create the URL's for additional arguments:

```<code># Requested Query
pitch_type = c("FA", "SI")
report_type = c("pfx", "outcome")

# URL Generating Function for User inputs
generate_urls <- function(hand = NULL, report_type = c("pfx", "outcome"), prp = "P", month = NULL, year = NULL, pitch_type = c("FA", "SI"), lim = 0) {
# Not sure of what to put in function for modify_url call
}

# Result
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=SI&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=SI&ds=velo&lim=0"
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=SI&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=SI&ds=velo&lim=0"
</code>```

答:
Here's an option using tidyverse function. First, we can define the space of parameter that we want to walk over

```<code>params <- list(
  hand = NULL,
  prp = "P",
  year = 2019,
  month = NULL,
  pitch_type = c("FA", "SI"),
  report_type = c("pfx", "outcome"),
  lim = 0
)
</code>```

Then we can get all the URLs with

```<code>library(tidyverse) # tidyr for crossing(); purrr for pmap(), map_chr()
library(httr)
baseurl <- "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php"
crossing(!!!params) %>%
  pmap(list) %>%
  map_chr( ~modify_url(baseurl, query=.x) )
</code>```

the crossing() takes care of getting all possible combinations of parameters. The pmap(list) then turns each of the rows of the tibble into their own list (which is what we need to pass to query= parameter of modify_url. Then finally we call the url generating function for each set of parameters and return a character string.

Title: Building Multiple URLs using modify_url

Body:
I created a page scrape function that scrapes some data.  I want to be able to create a list of URL's so that I can pass along more than 1 argument in the function call in order to build different URL's.  Is there a way to do this using httr::modify_url?

My code which creates a single URL is as follows:

library(tidyverse)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang
library(httr)

# Arguments for Function
hand = NULL
prp = "P"
month = NULL
year = 2019
pitch_type = "FA"
report_type = "pfx"
lim = 0

url <- httr::modify_url("https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php",
                        query = list(
                          hand = hand,
                          reportType = report_type,
                          prp = prp,
                          month = month,
                          year = year,
                          pitch = pitch_type,
                          ds = "velo",
                          lim = lim
                        ))

# Single Query Result
url
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=FA&ds=velo&lim=0"

I was wondering if I could use the httr::modify_url query from above and  some combination of purrr::reduce(paste0) to create the URL's for additional arguments:

# Requested Query
pitch_type = c("FA", "SI")
report_type = c("pfx", "outcome")

# URL Generating Function for User inputs
generate_urls <- function(hand = NULL, report_type = c("pfx", "outcome"), prp = "P", month = NULL, year = NULL, pitch_type = c("FA", "SI"), lim = 0) {
# Not sure of what to put in function for modify_url call
}

# Result
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=SI&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=pfx&prp=P&year=2019&pitch=SI&ds=velo&lim=0"
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=FA&ds=velo&lim=0"
"https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=SI&ds=velo&lim=0"
#> [1] "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?reportType=outcome&prp=P&year=2019&pitch=SI&ds=velo&lim=0"

Body:
Here's an option using tidyverse function. First, we can define the space of parameter that we want to walk over

params <- list(
  hand = NULL,
  prp = "P",
  year = 2019,
  month = NULL,
  pitch_type = c("FA", "SI"),
  report_type = c("pfx", "outcome"),
  lim = 0
)

Then we can get all the URLs with

library(tidyverse) # tidyr for crossing(); purrr for pmap(), map_chr()
library(httr)
baseurl <- "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php"
crossing(!!!params) %>%
  pmap(list) %>%
  map_chr( ~modify_url(baseurl, query=.x) )

the crossing() takes care of getting all possible combinations of parameters. The pmap(list) then turns each of the rows of the tibble into their own list (which is what we need to pass to query= parameter of modify_url. Then finally we call the url generating function for each set of parameters and return a character string.


问:
The easiest way to transform collection to array?
Suppose we have a Collection<Foo>. What is the best (shortest in LoC in current context) way to transform it to Foo[]? Any well-known libraries are allowed.

UPD: (one more case in this section; leave comments if you think it's worth to create another thread for it): What about transforming Collection<Foo> to Bar[] where Bar has constructor with 1 parameter of type Foo i.e. public Bar(Foo foo){ ... } ?

答:
If you use Guava in your project you can use Iterables::toArray.

```<code>Foo[] foos = Iterables.toArray(x, Foo.class);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you use Guava in your project you can use Iterables::toArray.

Foo[] foos = Iterables.toArray(x, Foo.class);


问:
Selecting elements from "div" dropdown - Selenium
I have a "div" dropdown, not "select". So my function works fine everywhere except dropdows which open not from the dropdown button place, but from above (because dropdown is placed at the bottom of the page) to prevent... page scrolling i guess? Maybe the problem is that it opens too fast or too slow or what, so function usually clicks not the needed element but one of the closest to it. Mostly it works this way if element is not at the beginning of dropdown so it is scrolled to the element. Any suggestions what can be made?

The best way i found is to use actions, splitting moving to element and clicking into 2 rows (works much worse if writing in 1 row). By the way, "waitVisibilityOfElement(By)" is a function with webdriver wait for expected conditions

```<code>public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        waitVisibilityOfElement(by);
        Actions actions = new Actions(wrappedWebDriver);
       actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
}
</code>```

I expect needed element to be clicked, But usually it clicks another one

Ok with some help i came to a final decision which is the best way to select dropdown filters without using any .sleep() functions if other simple ways do not work for you.

```<code>public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        WebElement eleV = wrappedWebDriver.findElement(by);

        waitVisibilityOfElement(by);

        JavascriptExecutor js = (JavascriptExecutor) wrappedWebDriver;
        js.executeScript("arguments[0].scrollIntoView();", eleV);

        Actions actions = new Actions(wrappedWebDriver);
        actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
    }
</code>```

答:
Did you try to add fluet wait before clicking?
That can be helpful.
Also would be great if you can share information about DOM in that question?
That is a sample for java, but I think that can help you in js too.</p>

```<code>Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class);
</code>```

Body:
I have a "div" dropdown, not "select". So my function works fine everywhere except dropdows which open not from the dropdown button place, but from above (because dropdown is placed at the bottom of the page) to prevent... page scrolling i guess? Maybe the problem is that it opens too fast or too slow or what, so function usually clicks not the needed element but one of the closest to it. Mostly it works this way if element is not at the beginning of dropdown so it is scrolled to the element. Any suggestions what can be made?

The best way i found is to use actions, splitting moving to element and clicking into 2 rows (works much worse if writing in 1 row). By the way, "waitVisibilityOfElement(By)" is a function with webdriver wait for expected conditions

public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        waitVisibilityOfElement(by);
        Actions actions = new Actions(wrappedWebDriver);
       actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
}

I expect needed element to be clicked, But usually it clicks another one

Ok with some help i came to a final decision which is the best way to select dropdown filters without using any .sleep() functions if other simple ways do not work for you.

public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        WebElement eleV = wrappedWebDriver.findElement(by);

        waitVisibilityOfElement(by);

        JavascriptExecutor js = (JavascriptExecutor) wrappedWebDriver;
        js.executeScript("arguments[0].scrollIntoView();", eleV);

        Actions actions = new Actions(wrappedWebDriver);
        actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
    }

Body:
Did you try to add fluet wait before clicking?
That can be helpful.
Also would be great if you can share information about DOM in that question?
That is a sample for java, but I think that can help you in js too.

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class);


问:
visual studio 2015 exp results differ
I have a c++ code in visual studio 2015 c++11.  The code  does EXP of

```<code>val = 7.3526137268510955991

double myCalulatedEXP= EXP(val);
//Lets print
std::cout.precision(20);
std::cout<<myCalulatedEXP;
</code>```

On one machine I get  1560.2693207530153359 and on the other, I get 1560.2693207530151085
See that last 4 digits does not match causing trouble for me.
Though the difference is small it multiplies and adds up to a bigger difference later on.

Both machines have same processor identifier .

```<code>PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 63 Stepping 2, GenuineIntel
</code>```

Both machines have same OS via

```<code> `systeminfo | findstr /B /C:"OS Name" /C:"OS Version"`

OS Name:                   Microsoft Windows Server 2012 R2 Standard
OS Version:                6.3.9600 N/A Build 9600
</code>```

Both are windows server 2012 machines. I ran dependency walker to check if they are having different dlls versions linked . Both are exactly the same .

Please suggest

1) What can cause such differences?

2) How can I avoid such differences?

3) If processor, OS, dlls are the same can I still expect different results

答:
If you look at the IEEE 754 binary format for a double it is: 53 significant binary bits / 15.95 significant decimal digits plus 11 exponent bits.  (wiki: https://en.wikipedia.org/wiki/IEEE_754)

This means if you print the double using a format that shows more than 16 significant digits, the extra digits may be garbage.

Not always, for example %.20f might be perfectly accurate if the exponent of the number is -4.

53 bits of accuracy is the best case.  A chain of operation on numbers of different magnitudes can lose accuracy, for example (1.23 e+20) + (0.45 e-30).

```<code>std::cout.precision(20);
</code>```

Since a double has a maximum accuracy of 16 digits, this may include undefined digits.

This question's top answer suggests using 17 digits: How do I print a double value with full precision using cout?

Additional notes in the comments point to  Theorem 15 in this abstract of What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Title: visual studio 2015 exp results differ

Body:
I have a c++ code in visual studio 2015 c++11.  The code  does EXP of

val = 7.3526137268510955991

double myCalulatedEXP= EXP(val);
//Lets print
std::cout.precision(20);
std::cout<<myCalulatedEXP;

On one machine I get  1560.2693207530153359 and on the other, I get 1560.2693207530151085
See that last 4 digits does not match causing trouble for me.
Though the difference is small it multiplies and adds up to a bigger difference later on.

Both machines have same processor identifier .

PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 63 Stepping 2, GenuineIntel

Both machines have same OS via

 `systeminfo | findstr /B /C:"OS Name" /C:"OS Version"`

OS Name:                   Microsoft Windows Server 2012 R2 Standard
OS Version:                6.3.9600 N/A Build 9600

Both are windows server 2012 machines. I ran dependency walker to check if they are having different dlls versions linked . Both are exactly the same .

Please suggest

1) What can cause such differences?

2) How can I avoid such differences?

3) If processor, OS, dlls are the same can I still expect different results

Body:
If you look at the IEEE 754 binary format for a double it is: 53 significant binary bits / 15.95 significant decimal digits plus 11 exponent bits.  (wiki: https://en.wikipedia.org/wiki/IEEE_754)

This means if you print the double using a format that shows more than 16 significant digits, the extra digits may be garbage.

Not always, for example %.20f might be perfectly accurate if the exponent of the number is -4.

53 bits of accuracy is the best case.  A chain of operation on numbers of different magnitudes can lose accuracy, for example (1.23 e+20) + (0.45 e-30).

std::cout.precision(20);

Since a double has a maximum accuracy of 16 digits, this may include undefined digits.

This question's top answer suggests using 17 digits: How do I print a double value with full precision using cout?

Additional notes in the comments point to  Theorem 15 in this abstract of What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html


问:
Applying formula to range of cells, then pasting values
I need to apply a formula/function (the DOLLAR function) to a range of cells, then cut and paste just the values.

I have a heading row and use Find to get to the column that I need. Then with all of the cells below, I want to apply the DOLLAR formula. However, the result at the end of my macro needs to be that those cells now contain just the value after applying the formula, and not the formula itself (this is because I'm going to use the sheet to run a mail merge so it can't have formulas).

I've tried running Do While and other cut/paste methods. I just don't have the skill to get it done :(

```<code>Sub ProjectSummaryAdjustment()

   Workbooks("Project Summary").Activate

   Range("A1",Range("A1").End(xlToRight)).Find("TD Budget Effort").Select
</code>```

This is as far as I've gotten with the code. Now for all the cells below, I want to apply the DOLLAR formula, then have just the values pasted there. I don't mind if it has to cut and paste to the first empty column and then cut and paste back to the original column.

答:
First make sure that you should avoid Select and Activate.  Then you can simple use evaluate to do the conversion.  You do need to set the field as text first:</p>

```<code>With Workbooks("Project Summary").Worksheets("Sheet1") 'Change to your sheet name
    Dim rng As Range
    Set rng = .Range("A1", .Range("A1").End(xlToRight)).Find("TD Budget Effort")
    'Test to make sure the header was found
    If Not rng Is Nothing Then
        With .Range(.Cells(2, rng.Column), .Cells(.Rows.Count, rng.Column).End(xlUp))
            .NumberFormat = "@"
            .Value = .Parent.Evaluate("index(DOLLAR(" & .Address & "),)")
        End With
    End If
End With
</code>```

Body:
I need to apply a formula/function (the DOLLAR function) to a range of cells, then cut and paste just the values.

I have a heading row and use Find to get to the column that I need. Then with all of the cells below, I want to apply the DOLLAR formula. However, the result at the end of my macro needs to be that those cells now contain just the value after applying the formula, and not the formula itself (this is because I'm going to use the sheet to run a mail merge so it can't have formulas).

I've tried running Do While and other cut/paste methods. I just don't have the skill to get it done :(

Sub ProjectSummaryAdjustment()

   Workbooks("Project Summary").Activate

   Range("A1",Range("A1").End(xlToRight)).Find("TD Budget Effort").Select

This is as far as I've gotten with the code. Now for all the cells below, I want to apply the DOLLAR formula, then have just the values pasted there. I don't mind if it has to cut and paste to the first empty column and then cut and paste back to the original column.

Body:
First make sure that you should avoid Select and Activate.  Then you can simple use evaluate to do the conversion.  You do need to set the field as text first:

With Workbooks("Project Summary").Worksheets("Sheet1") 'Change to your sheet name
    Dim rng As Range
    Set rng = .Range("A1", .Range("A1").End(xlToRight)).Find("TD Budget Effort")
    'Test to make sure the header was found
    If Not rng Is Nothing Then
        With .Range(.Cells(2, rng.Column), .Cells(.Rows.Count, rng.Column).End(xlUp))
            .NumberFormat = "@"
            .Value = .Parent.Evaluate("index(DOLLAR(" & .Address & "),)")
        End With
    End If
End With


问:
Set-RunOnce run ps1 file from changing usb drive letter
So I am using this Powershell script: Set-RunOnce https://www.powershellgallery.com/packages/WindowsImageConverter/1.0/Content/Set-RunOnce.ps1

When I put the driveletter hardcoded in (E:\ServerInstall.ps1) it works like a charm.
But I want to be sure this script can run from any drive letter the USB gets plugged into.

How can I get this changing drive letter in the registry?

I first tried it with -ExecutionPolicy Bypass, but that didn't change much either.

I also tried this:

$getusb = Get-WmiObject Win32_Volume -Filter "DriveType='2'" .
.\Set-RunOnce.ps1 Set-RunOnce -Command

'%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe `
-ExecutionPolicy Unrestricted -File $getusb.Name\ServerInstall.ps1'

-->
$getusb.Name\ServerInstall.ps1 ended being hardcoded in the registry, but it didn't know what
$getusb.name was, so the script didn't launch.

```<code>. .\Set-RunOnce.ps1
Set-RunOnce -Command '%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe `
-ExecutionPolicy Unrestricted -File (wmic logicaldisk where drivetype=2)
ServerInstall.ps1'
</code>```

答:
The Set-RunOnce function is really easy to understand and simple to adjust.

I would suggest creating a derived function of your own to do what you want and use that instead:

```<code>function Set-RunOnceForUSB {
    # get the driveletter from WMI for the first (possibly only) USB disk
    $firstUSB   = @(Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DriveType -eq 2} | Select-Object -ExpandProperty DeviceID)[0]
    # or use:
    # $firstUSB = @(Get-WmiObject Win32_Volume -Filter "DriveType='2'" | Select-Object -ExpandProperty DriveLetter)[0]

    # combine that with the name of your script file to create a complete path
    $scriptPath = Join-Path -Path $firstUSB -ChildPath 'ServerInstall.ps1'

    # create the command string. use double-quotes so the variable $scriptPath gets expanded
    $command = "%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File $scriptPath"

    # next, add this to the registry same as the original Set-RunOnce function does
    if (-not ((Get-Item -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce).Run )) {
        New-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $command -PropertyType ExpandString
    }
    else {
        Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $command -PropertyType ExpandString
    }
}
</code>```

Body:
So I am using this Powershell script: Set-RunOnce https://www.powershellgallery.com/packages/WindowsImageConverter/1.0/Content/Set-RunOnce.ps1

When I put the driveletter hardcoded in (E:\ServerInstall.ps1) it works like a charm.
But I want to be sure this script can run from any drive letter the USB gets plugged into.

How can I get this changing drive letter in the registry?

I first tried it with -ExecutionPolicy Bypass, but that didn't change much either.

I also tried this:

$getusb = Get-WmiObject Win32_Volume -Filter "DriveType='2'" .
.\Set-RunOnce.ps1 Set-RunOnce -Command

'%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe `
-ExecutionPolicy Unrestricted -File $getusb.Name\ServerInstall.ps1'

-->
$getusb.Name\ServerInstall.ps1 ended being hardcoded in the registry, but it didn't know what
$getusb.name was, so the script didn't launch.

. .\Set-RunOnce.ps1
Set-RunOnce -Command '%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe `
-ExecutionPolicy Unrestricted -File (wmic logicaldisk where drivetype=2)
ServerInstall.ps1'

Body:
The Set-RunOnce function is really easy to understand and simple to adjust.

I would suggest creating a derived function of your own to do what you want and use that instead:

function Set-RunOnceForUSB {
    # get the driveletter from WMI for the first (possibly only) USB disk
    $firstUSB   = @(Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DriveType -eq 2} | Select-Object -ExpandProperty DeviceID)[0]
    # or use:
    # $firstUSB = @(Get-WmiObject Win32_Volume -Filter "DriveType='2'" | Select-Object -ExpandProperty DriveLetter)[0]

    # combine that with the name of your script file to create a complete path
    $scriptPath = Join-Path -Path $firstUSB -ChildPath 'ServerInstall.ps1'

    # create the command string. use double-quotes so the variable $scriptPath gets expanded
    $command = "%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File $scriptPath"

    # next, add this to the registry same as the original Set-RunOnce function does
    if (-not ((Get-Item -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce).Run )) {
        New-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $command -PropertyType ExpandString
    }
    else {
        Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $command -PropertyType ExpandString
    }
}


问:
constructor.name is undefined in Internet Explorer
My debugging work in IE ended today by finding that constructor.name is undefined.

I created the following simple code that reproduces the issue:

```<code>({}).constructor.name === undefined // => true
</code>```

Is there any workaround to make this work?

Maybe overriding somehow the prototype?

If possible, I don't want to change the syntax, because the change would be major.

JSFIDDLE

答:
I wrote this for my needs (acknowledging it may not be full-proof):

```<code>if (!Object.constructor.prototype.hasOwnProperty('name')) {
    Object.defineProperty(Object.constructor.prototype, 'name', {
        get: function () {
            return this.toString().trim().replace(/^\S+\s+(\w+)[\S\s]+$/, '$1');
        }
    })
}
</code>```

The regex being performed in the method is making an assumption that the 2nd non-whitespace group of characters IS the name of the constructor.  This is a viable solution for the code that I'm working with, while this may not be full-coverage for all others' needs.

Body:
My debugging work in IE ended today by finding that constructor.name is undefined.

I created the following simple code that reproduces the issue:

({}).constructor.name === undefined // => true

Is there any workaround to make this work?

Maybe overriding somehow the prototype?

If possible, I don't want to change the syntax, because the change would be major.

JSFIDDLE

Body:
I wrote this for my needs (acknowledging it may not be full-proof):

if (!Object.constructor.prototype.hasOwnProperty('name')) {
    Object.defineProperty(Object.constructor.prototype, 'name', {
        get: function () {
            return this.toString().trim().replace(/^\S+\s+(\w+)[\S\s]+$/, '$1');
        }
    })
}

The regex being performed in the method is making an assumption that the 2nd non-whitespace group of characters IS the name of the constructor.  This is a viable solution for the code that I'm working with, while this may not be full-coverage for all others' needs.


问:
Android Studio: Transparent checkout using Mercado Pago
I am trying to implement for the first time the Mercado Pago's transparent checkout in Android.

I've already downloaded the newest version of the SDK provided in https://github.com/mercadopago/px-android and executed it normally in the Emulator.

In the GitHub page mentioned above, we have an explanation of how to implement Mercado Pago's checkout with just one line of code:

```<code>new MercadoPagoCheckout.Builder("public_key", "checkout_preference_id")
    .build()
    .startPayment(activityOrContext, requestCode);
</code>```

Where public_key we can get in the credentials webpage. But the String checkout_preference_id I have no idea of how to create it, even though they showed how to create it at the end of the GitHub webpage.

Create your preference id

```<code>curl -X POST \
     'https://api.mercadopago.com/checkout/preferences?access_token=ACCESS_TOKEN' \
     -H 'Content-Type: application/json' \
     -d '{
           "items": [
               {
               "title": "Dummy Item",
               "description": "Multicolor Item",
               "quantity": 1,
               "currency_id": "ARS",
               "unit_price": 10.0
               }
           ],
           "payer": {
               "email": "payer@email.com"
           }
     }'
</code>```

I tried to put a random String in checkout_preference_id, but it did not work. Only the String in the example app of Mercado Pago worked.

```<code>private static final String DUMMY_PREFERENCE_ID = "243962506-0bb62e22-5c7b-425e-a0a6-c22d0f4758a9";
</code>```

All the other ways of implementing it presented in the example app of Mercado Pago require a fake confirmation of payment.

I appreciate if anyone could show some code of how to create and pass the variable checkout_preference_id into the main command of Mercado Pago payment.

EDIT

I also appreciate if anyone could give us an example of a Not fake confirmation of payment with some code.

I guess checkout_preference_id can be accessed via a Marketplace website or maybe creating a curl using Android's webservice. Then, it is still a mystery to me.

Concerning to the alternitive way of paying with MercadoPago, we have this other arguments to pass:

```<code>new MercadoPagoCheckout.Builder("public_key", checkoutPreference, paymentConfiguration)
                .build()
                .startPayment(activityOrContext, requestCode);
</code>```

Where checkoutPreference allows you to create a custom item to sell.

```<code>final Item item = new Item.Builder("Product Title", 1, new BigDecimal(12.3)).setDescription("Product Description").build();
CheckoutPreference checkoutPreference = new CheckoutPreference.Builder(Sites.BRASIL, "a@a.a", Collections.singletonList(item)).setDefaultInstallments(1).build();
</code>```

paymentConfiguration is implemented the fake confirmation of payment.

```<code>PaymentConfiguration paymentConfiguration = new PaymentConfiguration.Builder(new MyPaymentProcessor()).build();
</code>```

Where the class MyPaymentProcessor() and the other classes in which it depends on can be found in the GitHub example.

答:
```<code>val queue = Volley.newRequestQueue(this)

    val strJson = "{\n" +
            "           \"items\": [\n" +
            "               {\n" +
            "               \"title\": \"Item\",\n" +
            "               \"description\": \"Multicolor Item\",\n" +
            "               \"quantity\": 1,\n" +
            "               \"currency_id\": \"BRL\",\n" +
            "               \"unit_price\": 35.0\n" +
            "               }\n" +
            "           ],\n" +
            "           \"payer\": {\n" +
            "\t\t    \"name\": \"Núbia\",\n" +
            "\t\t    \"surname\": \"Macedo\",\n" +
            "\t\t    \"email\": \"leann@gmail.com\",\n" +
            "\t\t    \"date_created\": \"2015-06-02T12:58:41.425-04:00\",\n" +
            "\t\t    \"phone\": {\n" +
            "\t\t      \"area_code\": \"\",\n" +
            "\t\t      \"number\": \"880.402.7555\"\n" +
            "\t\t    },\n" +
            "\t\t    \"identification\": {\n" +
            "\t\t      \"type\": \"DNI\",\n" +
            "\t\t      \"number\": \"123456789\"\n" +
            "\t\t    },\n" +
            "\t\t    \"address\": {\n" +
            "\t\t      \"street_name\": \"Núbia Viela\",\n" +
            "\t\t      \"street_number\": 25598,\n" +
            "\t\t      \"zip_code\": \"8972\"\n" +
            "\t\t    }\n" +
            "\t\t  }\n" +
            "     }"

    val obj = JSONObject(strJson)

    //val url = "https://api.mercadopago.com/checkout/preferences"
    val url = "https://api.mercadopago.com/checkout/preferences?access_token=TEST-XXXXXXXXXXXX-XXXXXXX-XXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXX"
    val stringRequest = object : JsonObjectRequest(Method.POST, url, obj,
        Response.Listener<JSONObject> {response ->
            val checkoutPreferenceId: String= response.getString("id")
            MercadoPagoCheckout.Builder("TEST-XXXXXXXX-XXXX-XXXX-XXXXX-XXXXXXXXXX", checkoutPreferenceId)
                .build().startPayment(this, REQUEST_CODE)
        },
        Response.ErrorListener { error ->
            val erros = error.toString()
            val teste1 = "sdsds"
            val teste12 = "sdsds"
            val teste13 = "sdsds"
        }

    ) {
        @Throws(AuthFailureError::class)
        override fun getHeaders(): Map<String, String> {
            val headers = HashMap<String, String>()
            headers["Content-Type"] = "application/json"
            return headers
        }

    }

    val policy = DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
    stringRequest.retryPolicy = policy
    queue.add(stringRequest)
</code>```

Do not forget to swap your access_token.

Json example: https://www.mercadopago.com.br/developers/pt/guides/payments/web-checkout/personalization/

packages:

```<code>implementation 'com.mercadopago.android.px:checkout:4.5.2'
implementation 'com.android.volley:volley:1.1.0'
</code>```

Body:
I am trying to implement for the first time the Mercado Pago's transparent checkout in Android.

I've already downloaded the newest version of the SDK provided in https://github.com/mercadopago/px-android and executed it normally in the Emulator.

In the GitHub page mentioned above, we have an explanation of how to implement Mercado Pago's checkout with just one line of code:

new MercadoPagoCheckout.Builder("public_key", "checkout_preference_id")
    .build()
    .startPayment(activityOrContext, requestCode);

Where public_key we can get in the credentials webpage. But the String checkout_preference_id I have no idea of how to create it, even though they showed how to create it at the end of the GitHub webpage.

Create your preference id

curl -X POST \
     'https://api.mercadopago.com/checkout/preferences?access_token=ACCESS_TOKEN' \
     -H 'Content-Type: application/json' \
     -d '{
           "items": [
               {
               "title": "Dummy Item",
               "description": "Multicolor Item",
               "quantity": 1,
               "currency_id": "ARS",
               "unit_price": 10.0
               }
           ],
           "payer": {
               "email": "payer@email.com"
           }
     }'

I tried to put a random String in checkout_preference_id, but it did not work. Only the String in the example app of Mercado Pago worked.

private static final String DUMMY_PREFERENCE_ID = "243962506-0bb62e22-5c7b-425e-a0a6-c22d0f4758a9";

All the other ways of implementing it presented in the example app of Mercado Pago require a fake confirmation of payment.

I appreciate if anyone could show some code of how to create and pass the variable checkout_preference_id into the main command of Mercado Pago payment.

EDIT

I also appreciate if anyone could give us an example of a Not fake confirmation of payment with some code.

I guess checkout_preference_id can be accessed via a Marketplace website or maybe creating a curl using Android's webservice. Then, it is still a mystery to me.

Concerning to the alternitive way of paying with MercadoPago, we have this other arguments to pass:

new MercadoPagoCheckout.Builder("public_key", checkoutPreference, paymentConfiguration)
                .build()
                .startPayment(activityOrContext, requestCode);

Where checkoutPreference allows you to create a custom item to sell.

final Item item = new Item.Builder("Product Title", 1, new BigDecimal(12.3)).setDescription("Product Description").build();
CheckoutPreference checkoutPreference = new CheckoutPreference.Builder(Sites.BRASIL, "a@a.a", Collections.singletonList(item)).setDefaultInstallments(1).build();

paymentConfiguration is implemented the fake confirmation of payment.

PaymentConfiguration paymentConfiguration = new PaymentConfiguration.Builder(new MyPaymentProcessor()).build();

Where the class MyPaymentProcessor() and the other classes in which it depends on can be found in the GitHub example.

Body:
val queue = Volley.newRequestQueue(this)

    val strJson = "{\n" +
            "           \"items\": [\n" +
            "               {\n" +
            "               \"title\": \"Item\",\n" +
            "               \"description\": \"Multicolor Item\",\n" +
            "               \"quantity\": 1,\n" +
            "               \"currency_id\": \"BRL\",\n" +
            "               \"unit_price\": 35.0\n" +
            "               }\n" +
            "           ],\n" +
            "           \"payer\": {\n" +
            "\t\t    \"name\": \"Núbia\",\n" +
            "\t\t    \"surname\": \"Macedo\",\n" +
            "\t\t    \"email\": \"leann@gmail.com\",\n" +
            "\t\t    \"date_created\": \"2015-06-02T12:58:41.425-04:00\",\n" +
            "\t\t    \"phone\": {\n" +
            "\t\t      \"area_code\": \"\",\n" +
            "\t\t      \"number\": \"880.402.7555\"\n" +
            "\t\t    },\n" +
            "\t\t    \"identification\": {\n" +
            "\t\t      \"type\": \"DNI\",\n" +
            "\t\t      \"number\": \"123456789\"\n" +
            "\t\t    },\n" +
            "\t\t    \"address\": {\n" +
            "\t\t      \"street_name\": \"Núbia Viela\",\n" +
            "\t\t      \"street_number\": 25598,\n" +
            "\t\t      \"zip_code\": \"8972\"\n" +
            "\t\t    }\n" +
            "\t\t  }\n" +
            "     }"

    val obj = JSONObject(strJson)

    //val url = "https://api.mercadopago.com/checkout/preferences"
    val url = "https://api.mercadopago.com/checkout/preferences?access_token=TEST-XXXXXXXXXXXX-XXXXXXX-XXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXX"
    val stringRequest = object : JsonObjectRequest(Method.POST, url, obj,
        Response.Listener<JSONObject> {response ->
            val checkoutPreferenceId: String= response.getString("id")
            MercadoPagoCheckout.Builder("TEST-XXXXXXXX-XXXX-XXXX-XXXXX-XXXXXXXXXX", checkoutPreferenceId)
                .build().startPayment(this, REQUEST_CODE)
        },
        Response.ErrorListener { error ->
            val erros = error.toString()
            val teste1 = "sdsds"
            val teste12 = "sdsds"
            val teste13 = "sdsds"
        }

    ) {
        @Throws(AuthFailureError::class)
        override fun getHeaders(): Map<String, String> {
            val headers = HashMap<String, String>()
            headers["Content-Type"] = "application/json"
            return headers
        }

    }

    val policy = DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
    stringRequest.retryPolicy = policy
    queue.add(stringRequest)

Do not forget to swap your access_token.

Json example: https://www.mercadopago.com.br/developers/pt/guides/payments/web-checkout/personalization/

packages:

implementation 'com.mercadopago.android.px:checkout:4.5.2'
implementation 'com.android.volley:volley:1.1.0'


问:
Java open file on shared location
I want to do something like this:

File root = new File("C:/file.txt");

but on a folder which is shared on a local network. So lets say the file is on 192.168.1.28 how make it with above command?

Next not working:

File root = new File("//192.168.1.2/file.txt");

File root = new File("\\\\192.168.1.2/file.txt");

File root = new File("\\192.168.1.2/file.txt");

File root = new File("file:\\192.168.1.2/file.txt");

File root = new File("file://192.168.1.2/file.txt");

Thanks a lot.

答:
With Java 1.8, you can use Java to access files on shared location. Let's say you want to access a .xls file called (Sample.xls) on a shared location.</p>

```<code>String location = "\\\your.shared.location.company.com\\folder1\\folder2\\";
String fileName = "Sample.xls";
FileInputStream fis = new FileInputStream(location + fileName);
</code>```

Title: Java open file on shared location

Body:
With Java 1.8, you can use Java to access files on shared location. Let's say you want to access a .xls file called (Sample.xls) on a shared location.

String location = "\\\your.shared.location.company.com\\folder1\\folder2\\";
String fileName = "Sample.xls";
FileInputStream fis = new FileInputStream(location + fileName);


问:
Stack limit (0.2Gb) exceeded...Probable infinite recursion (cycle):
Pretty new to Prolog, but I'm trying to implement a context-free grammar and I'm having an issue passing a test case with the rules I have.

I've tried changing the order of my rules to seem more logically correct, but I can't seem to get consistent correct outputs and I continue to get the same stack error. I think it has something to do with vp --> vp, np. being recursive, but if that's the case, then why doesn't np --> np, pp. give me an error as well? My code is below:

```<code>:- use_module(library(tabling)).
:- table s/2.

s --> np, vp.
np --> det, n.
np --> np, pp.
vp --> vp, pp.
vp --> v, np.
pp --> p, np.

det --> [the].
n --> [cop].
n --> [criminal].
n --> [street].
v --> [chased].

p --> [in].
p --> [by].
</code>```

Asking this to the query ideally should return true:

```<code>$- s([the,cop,chased,the,criminal], []).
</code>```

And asking this should return false:

```<code>$- s([the, cop, the, criminal, chased], []).
</code>```

I've tried both and they just give me the same error:

```<code>Stack limit (0.2Gb) exceeded
  Stack sizes: local: 0.2Gb, global: 22Kb, trail: 5Kb
  Stack depth: 1,561,893, last-call: 0%, Choice points: 1,561,869
  Probable infinite recursion (cycle):
    [1,561,893] vp([length:3], _1424)
    [1,561,892] vp([length:3], _1456)
</code>```

Any feedback is appreciated!

答:
The problem is that you have constructed a left recursive grammar. Indeed if we look at the rules you defined, we see:

```<code>:- use_module(library(tabling)).
:- table s/2.

s --> np, vp.
np --> det, n.
<b>np</b> --> <b>np</b>, pp.
<b>vp</b> --> <b>vp</b>, pp.
vp --> v, np.
pp --> p, np.

det --> [the].
n --> [cop].
n --> [criminal].
n --> [street].
v --> [chased].

p --> [in].
p --> [by].</code>```

Now based on how Prolog implements predicates, it can not work with such left recursive grammar, since if you call np/2, it will first call np/2, and hence we never get out of the "loop" (until the call stack overflows).

We can however use tabling here, like you somehow did with s/2, which is not necessary, since there is no left-recursive path in s that yields (directly or indirectly) s --> s, .... We need to table np/2 and vp/2, like:

```<code>:- use_module(library(tabling)).
<b>:- table np/2.</b>
<b>:- table vp/2.</b>

s --> np, vp.
np --> det, n.
np --> np, pp.
vp --> vp, pp.
vp --> v, np.
pp --> p, np.

det --> [the].
n --> [cop].
n --> [criminal].
n --> [street].
v --> [chased].

p --> [in].
p --> [by].</code>```

We then indeed can obtain the expected results:

```<code>?- s([the,cop,chased,the,criminal], []).
true.

?- s([the, cop, the, criminal, chased], []).
false.
</code>```

Body:
Pretty new to Prolog, but I'm trying to implement a context-free grammar and I'm having an issue passing a test case with the rules I have.

I've tried changing the order of my rules to seem more logically correct, but I can't seem to get consistent correct outputs and I continue to get the same stack error. I think it has something to do with vp --> vp, np. being recursive, but if that's the case, then why doesn't np --> np, pp. give me an error as well? My code is below:

:- use_module(library(tabling)).
:- table s/2.

s --> np, vp.
np --> det, n.
np --> np, pp.
vp --> vp, pp.
vp --> v, np.
pp --> p, np.

det --> [the].
n --> [cop].
n --> [criminal].
n --> [street].
v --> [chased].

p --> [in].
p --> [by].

Asking this to the query ideally should return true:

$- s([the,cop,chased,the,criminal], []).

And asking this should return false:

$- s([the, cop, the, criminal, chased], []).

I've tried both and they just give me the same error:

Stack limit (0.2Gb) exceeded
  Stack sizes: local: 0.2Gb, global: 22Kb, trail: 5Kb
  Stack depth: 1,561,893, last-call: 0%, Choice points: 1,561,869
  Probable infinite recursion (cycle):
    [1,561,893] vp([length:3], _1424)
    [1,561,892] vp([length:3], _1456)

Any feedback is appreciated!

Body:
The problem is that you have constructed a left recursive grammar. Indeed if we look at the rules you defined, we see:

:- use_module(library(tabling)).
:- table s/2.

s --> np, vp.
np --> det, n.
np --> np, pp.
vp --> vp, pp.
vp --> v, np.
pp --> p, np.

det --> [the].
n --> [cop].
n --> [criminal].
n --> [street].
v --> [chased].

p --> [in].
p --> [by].

Now based on how Prolog implements predicates, it can not work with such left recursive grammar, since if you call np/2, it will first call np/2, and hence we never get out of the "loop" (until the call stack overflows).

We can however use tabling here, like you somehow did with s/2, which is not necessary, since there is no left-recursive path in s that yields (directly or indirectly) s --> s, .... We need to table np/2 and vp/2, like:

:- use_module(library(tabling)).
:- table np/2.
:- table vp/2.

s --> np, vp.
np --> det, n.
np --> np, pp.
vp --> vp, pp.
vp --> v, np.
pp --> p, np.

det --> [the].
n --> [cop].
n --> [criminal].
n --> [street].
v --> [chased].

p --> [in].
p --> [by].

We then indeed can obtain the expected results:

?- s([the,cop,chased,the,criminal], []).
true.

?- s([the, cop, the, criminal, chased], []).
false.


问:
can't get the value of an input
I have a function in which I create an input like

```<code>tr = document.createElement("tr");
td1 = document.createElement("td");
td2 = document.createElement("td");
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(document.createElement("input"));
td2.setAttribute("id", "nr");
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
</code>```

Afterward, I want to get the value of it in another function with:

```<code>var nr = document.getElementById("nr").value;
</code>```

it will know the nr element but the value is undefined

答:
This line is setting the id of the , not the appended child input element:

```<code>td2.setAttribute("id", "nr");
</code>```

Title: can't get the value of an input

Body:
I have a function in which I create an input like

tr = document.createElement("tr");
td1 = document.createElement("td");
td2 = document.createElement("td");
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(document.createElement("input"));
td2.setAttribute("id", "nr");
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);

Afterward, I want to get the value of it in another function with:

var nr = document.getElementById("nr").value;

it will know the nr element but the value is undefined

Body:
This line is setting the id of the <td>, not the appended child input element:

td2.setAttribute("id", "nr");


问:
Random y axis in Pandas catplot
Please see figure.

I'm using sns.catplot(x='Event', y='# Runs', hue='Code', data=df) to plot this. I don't understand why the y-axis is all over the place.

答:
You're passing in a list of strings, not a list of numbers. Seaborn can't sort those as if they're numeric, and just lists them on the axis in the order received. Try casting the column astype('int')

Since you have some blank strings in your data, you need to select those out somehow if you don't want them plotted, df[df['# Runs']!=''] or similar, then cast the column to int as previously discussed, then try your plotting again. This should sort the axis correctly, without blank or NaN values

Title: Random y axis in Pandas catplot


问:
How do you fix the "element not interactable" exception?
I know this has been asked lots of times before but how do you get around the "element not interactable" exception?

Here is my code:

```<code>button = driver.find_element_by_class_name(u"infoDismiss")
type(button)
button.click()
driver.implicitly_wait(10)
</code>```

Here is the HTML:

```<code><button class="dismiss infoDismiss">
    <string for="inplay_button_dismiss">Dismiss</string>
</button>
</code>```

And here is the error message:

```<code>selenium.common.exceptions.ElementNotInteractableException: Message:
</code>```

After is says message there is literally nothing.

I have spent lots of time searching the web, not finding anything that solves my issue. I would really appreciate an answer.

Edit: Changed "w" to driver so it is easier to read

Update: I have just realized that I've found the HTML of the wrong button! The real button HTML is below:

```<code><button class="dismiss">
    <string for="exit">Dismiss</string>
</button>
</code>```

Also, I've used the answers and comments and edited my code to look like this:

```<code>button = driver.find_element_by_css_selector("button.dismiss")
w.implicitly_wait(10)
ActionChains(w).move_to_element(button).click(button)
</code>```

And now I get a new error:

```<code>selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection
</code>```

The error happens in line 1: button = driver.find_element_by_css_selector("button.dismiss")

答:
For the html code:

test.html

```<code><button class="dismiss"  onclick="alert('hello')">
    <string for="exit">Dismiss</string>
</button>
</code>```

the below python code worked for me. You can just try it.

```<code>from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()
</code>```

Body:
I know this has been asked lots of times before but how do you get around the "element not interactable" exception?

Here is my code:

button = driver.find_element_by_class_name(u"infoDismiss")
type(button)
button.click()
driver.implicitly_wait(10)

Here is the HTML:

<button class="dismiss infoDismiss">
    <string for="inplay_button_dismiss">Dismiss</string>
</button>

And here is the error message:

selenium.common.exceptions.ElementNotInteractableException: Message:

After is says message there is literally nothing.

I have spent lots of time searching the web, not finding anything that solves my issue. I would really appreciate an answer.

Edit: Changed "w" to driver so it is easier to read

Update: I have just realized that I've found the HTML of the wrong button! The real button HTML is below:

<button class="dismiss">
    <string for="exit">Dismiss</string>
</button>

Also, I've used the answers and comments and edited my code to look like this:

button = driver.find_element_by_css_selector("button.dismiss")
w.implicitly_wait(10)
ActionChains(w).move_to_element(button).click(button)

And now I get a new error:

selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection

The error happens in line 1: button = driver.find_element_by_css_selector("button.dismiss")

Body:
For the html code:

test.html

<button class="dismiss"  onclick="alert('hello')">
    <string for="exit">Dismiss</string>
</button>

the below python code worked for me. You can just try it.

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()


问:
Send message through parallel whatsapp to unsaved number
I'm trying to send message through Whatsapp to unsaved number, I have two whatsapps and I'm getting the chooser but not able to add number to it, it shows my recent contact list.

I've tried Uri, PackageManager, and lots of things but no output

```<code>num = "91" + edt_num.getText().toString();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi, This is me");
sendIntent.putExtra("jid", num + "@s.whatsapp.net");
sendIntent.setPackage("com.whatsapp");
if (sendIntent.resolveActivity(getPackageManager()) == null) {
                    Toast.makeText(MainActivity.this, "Error/n", Toast.LENGTH_SHORT).show();
                    return;
}
startActivity(sendIntent);
</code>```

答:
Use this Function for Sending Message to Unsaved number

Must use country code in phoneNumber, e.g.91xxxxxxxxxx

```<code>public void SendWhatsappMessage(String phoneNumber,String message){
        PackageManager pm = getPackageManager();
        Intent send= new Intent(Intent.ACTION_VIEW);
        try {
            String url = "https://api.whatsapp.com/send?phone="+ phoneNumber +"&text=" + URLEncoder.encode(message, "UTF-8");
            send.setPackage("com.whatsapp");
            send.setData(Uri.parse(url));
            if (send.resolveActivity(pm) != null) {
                startActivity(send);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
</code>```

Body:
I'm trying to send message through Whatsapp to unsaved number, I have two whatsapps and I'm getting the chooser but not able to add number to it, it shows my recent contact list.

I've tried Uri, PackageManager, and lots of things but no output

num = "91" + edt_num.getText().toString();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi, This is me");
sendIntent.putExtra("jid", num + "@s.whatsapp.net");
sendIntent.setPackage("com.whatsapp");
if (sendIntent.resolveActivity(getPackageManager()) == null) {
                    Toast.makeText(MainActivity.this, "Error/n", Toast.LENGTH_SHORT).show();
                    return;
}
startActivity(sendIntent);

Body:
Use this Function for Sending Message to Unsaved number

Must use country code in phoneNumber, e.g.91xxxxxxxxxx

public void SendWhatsappMessage(String phoneNumber,String message){
        PackageManager pm = getPackageManager();
        Intent send= new Intent(Intent.ACTION_VIEW);
        try {
            String url = "https://api.whatsapp.com/send?phone="+ phoneNumber +"&text=" + URLEncoder.encode(message, "UTF-8");
            send.setPackage("com.whatsapp");
            send.setData(Uri.parse(url));
            if (send.resolveActivity(pm) != null) {
                startActivity(send);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }


问:
How to add 3rd party JARs to Maven project
My area of expertise is not Java. I develop in other languages on other platforms.

Right now I'm developing a series of Java servlets for a project. The servlets are to run on a CentOS server running FileNetP8.

I actually got all of the planned items finished and running.

Now when I am trying to add a few more services, the library I came across is available via Maven. I have no idea what Maven is. Read up on it today. Created a test project to try it out.

My development environment is Eclipse Photon on Windows 10.

Now my problem is I can't figure out how to add the Filenet JARs to the project. I can't upload them to some Maven repo. Searching the Web says to add them to the local repo, but I don't understand how to do that to the Local repo in Eclipse's builtin Maven.

I think that the JARs don't need to be packaged within the deployment WAR because the app will be deployed to the Websphere server that runs Filenet so they should be available on it. Should I add them as external JAR references to get the project to compile?

答:
I provide below the following approaches to check based upon your suitability.

Approach-1: Install manually

If you have only 1 jar file, execute the following command by replacing as per your requirements.

```<code>mvn install:install-file \
   -Dfile=<file path location> \
   -DgroupId=<your own custom group id> \
   -DartifactId=<your own custom artifact id> \
   -Dversion=<some version number> \
   -Dpackaging=jar \
   -DgeneratePom=true
</code>```

Once it is done, use the following in your project pom.xml in the dependency section.

```<code><dependency>
    <groupId>your own custom group id</groupId>
    <artifactId>your own custom artifact id</artifactId>
    <version>some version number</version>
</dependency>
</code>```

The downside of the above approach is, only you can use it as it installs in your .m2 directory. For other developers, they have to follow the same approach. It is not a suggested approach.

Approach-2: Manually add the location of jar file

Add the following dependency in pom.xml

```<code><dependency>
    <groupId>some.group.id</groupId>
    <artifactId>some.artifat.id</artifactId>
    <version>some.version.no</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/libs/yourActualJarFileName.jar</systemPath>
</dependency>
</code>```

The downside of the above approach is, you have to put all the jar files in a directory and you have to provide the path. All the jar files should be part of your project, it means all the jar file should be put in source code repository. Although it servers the purposes, still it is not a good approach. If you got a newer/higher version of jar file, again you have to put it inside your lib directory. It means you have manage all the old and new versions of jar files.

Best Approach

Maintain Nexus or Artifactory, or any artifactory management system in the organisation and put all the jar files and provide the definition of your custom jar file. It will provide you pom definition. Based upon this, you have to add the dependencies in your project pom.xml. Here you can maintain n number version of your custom jar files.

Body:
I provide below the following approaches to check based upon your suitability.

Approach-1: Install manually

If you have only 1 jar file, execute the following command by replacing as per your requirements.

mvn install:install-file \
   -Dfile=<file path location> \
   -DgroupId=<your own custom group id> \
   -DartifactId=<your own custom artifact id> \
   -Dversion=<some version number> \
   -Dpackaging=jar \
   -DgeneratePom=true

Once it is done, use the following in your project pom.xml in the dependency section.

<dependency>
    <groupId>your own custom group id</groupId>
    <artifactId>your own custom artifact id</artifactId>
    <version>some version number</version>
</dependency>

The downside of the above approach is, only you can use it as it installs in your .m2 directory. For other developers, they have to follow the same approach. It is not a suggested approach.

Approach-2: Manually add the location of jar file

Add the following dependency in pom.xml

<dependency>
    <groupId>some.group.id</groupId>
    <artifactId>some.artifat.id</artifactId>
    <version>some.version.no</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/libs/yourActualJarFileName.jar</systemPath>
</dependency>

The downside of the above approach is, you have to put all the jar files in a directory and you have to provide the path. All the jar files should be part of your project, it means all the jar file should be put in source code repository. Although it servers the purposes, still it is not a good approach. If you got a newer/higher version of jar file, again you have to put it inside your lib directory. It means you have manage all the old and new versions of jar files.

Best Approach

Maintain Nexus or Artifactory, or any artifactory management system in the organisation and put all the jar files and provide the definition of your custom jar file. It will provide you pom definition. Based upon this, you have to add the dependencies in your project pom.xml. Here you can maintain n number version of your custom jar files.


问:
How to serve files larger than 32 MB from GCS using GAE and Python 3
I'm serving some files from GCS through a GAE application (using flask), recently I hit the 32 MB limit. It should according to the documentation be possible to serve files from GCS that are larger than 32 MB, but I can't find the correct python3 apis.

Response limits
  Dynamic responses are limited to 32MB. If a script handler generates a response larger than this limit, the server sends back an empty response with a 500 Internal Server Error status code. This limitation does not apply to responses that serve data from the Blobstore or Cloud Storage.

I've found the blobstore API which can serve files from GCS, but unfortunately that library is deprecated and not python3 compatible. This is what I think the code would have looked like in that approach

```<code>blobstore_filename = '/gs/{}/{}'.format(CLOUD_STORAGE_BUCKET, path)
blob_key = blobstore.create_gs_key(blobstore_filename)

response = Response("This should be overriden by App Enginge")
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['X-AppEngine-BlobKey'] = blob_key
return response
</code>```

I think in PHP there is a specific API method that does exactly what I need
CloudStorageTools#serve

I've seen some suggestions for similar problems to use Signed URLs but that seems more like a work-around rather than an actual solution to the problem.

I had expected to find a method to serve content from GCS, I don't know if my search skills are failing me or the method I need doesn't exist for the python3 environment.

答:
You can have a route on your app that returns a redirect to the GCS Signed URL.

This way you can control the access to the route, but the content itself is not served by your app.

Serving through your app will increase your cost and lower your performance, since a dynamic request is not cached by default and AppEngine instance time and egressing data are more expensive than serving from GCS.

The App Engine standard environments that have this feature, like PHP and Python 2, does this redirect internally, so the client do not see the access to GCS, but it is happening similarly.

None of the AppEngine specific APIs are available on Python 3 standard, see here.

In order to create a Signed URL on App Engine standard Python 3 you'll need to create a Service Account key manually. The Application Default Credentials provided on Compute Engine and App Engine cannot be used for digital signing. Python 2, Java, Go and PHP allow it because they use the internal App Identity API to generate the signature.

Although those are not available yet, Google's only remark on this till now that I have seen is:

At this time, App Engine APIs are not available in the Python 3.7 runtime

So we can still have some hope.

Body:
I'm serving some files from GCS through a GAE application (using flask), recently I hit the 32 MB limit. It should according to the documentation be possible to serve files from GCS that are larger than 32 MB, but I can't find the correct python3 apis.

Response limits
  Dynamic responses are limited to 32MB. If a script handler generates a response larger than this limit, the server sends back an empty response with a 500 Internal Server Error status code. This limitation does not apply to responses that serve data from the Blobstore or Cloud Storage.

I've found the blobstore API which can serve files from GCS, but unfortunately that library is deprecated and not python3 compatible. This is what I think the code would have looked like in that approach

blobstore_filename = '/gs/{}/{}'.format(CLOUD_STORAGE_BUCKET, path)
blob_key = blobstore.create_gs_key(blobstore_filename)

response = Response("This should be overriden by App Enginge")
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['X-AppEngine-BlobKey'] = blob_key
return response

I think in PHP there is a specific API method that does exactly what I need
CloudStorageTools#serve

I've seen some suggestions for similar problems to use Signed URLs but that seems more like a work-around rather than an actual solution to the problem.

I had expected to find a method to serve content from GCS, I don't know if my search skills are failing me or the method I need doesn't exist for the python3 environment.