问:
Authorization error while connecting to AWS IoT after attaching the device object to connection client
I am trying out the ShadowSample example that comes as part of Java AWS IoT Device SDK - https://github.com/aws/aws-iot-device-sdk-java/blob/master/aws-iot-device-sdk-java-samples/src/main/java/com/amazonaws/services/iot/client/sample/shadow/ShadowSample.java

I am able to run it successfully and it works properly. However, it works properly when I have the following policy attached to the certificate (and certificate in turn to device) -

```<code>{
  "Version": "2012-10-17",
  "Statement": [
  {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe",
        "iot:Receive",
        "iot:Publish",
        "iot:Connect"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}
</code>```

I want to have a generic and strict policy (especially for publish and receive actions) than granting rights to all i.e. "*" resource. So, I update the policy in the below forms and all are not working -

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe",
        "iot:Connect"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": [
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete",
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/accepted",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/rejected",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/delta",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/documents",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/accepted",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/rejected",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/accepted",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/rejected",
      ]
    }
  ]
}

and

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe",
        "iot:Connect"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/*",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/*",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/*",
      ]
    }
  ]
}

Note - For security purpose, I have put xxxx against account number. In real policies, I have proper values.

I even replace the * in topic with #, but the same result continues. The result is -

```<code>Oct 25, 2017 9:32:43 AM com.amazonaws.services.iot.client.mqtt.AwsIotMqttConnectionListener onFailure
WARNING: Connect request failure
Unable to connect to server (32103) - java.net.ConnectException: Connection timed out: connect
    at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:94)
    at org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule.start(SSLNetworkModule.java:103)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:701)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:80)
    ... 9 more

Oct 25, 2017 9:32:43 AM com.amazonaws.services.iot.client.core.AwsIotConnection onConnectionFailure
INFO: Connection temporarily lost
</code>```

On the AWS CloudWatch, under AWS IoT specific logs, I find -

```<code>2017-10-25 04:10:22.633 TRACEID:1db8b391-83c7-faf3-5aeb-c0d106787afe PRINCIPALID:e7ac813cdcbecffebecef9647a166882f93f5a2aa214cb6bbd9a1e41f7832f76 [ERROR] EVENT:MQTT Client Connect MESSAGE:Connect Status: AUTHORIZATION_ERROR
</code>```

What shall be the generic and strict policy for supporting publish and receive actions?

Note that the aforementioned policies which I have tried are working fine when I try out the pub-sub example (also provided in the same SDK). These policies are not working for shadow example because there is an additional step of attaching device to connection client.

Another small query: How will I minimise or restrict topic subscription for subscribe action in generic way as variable replacement like thing type, thing name do not work for subscribe (but work for receive and publish)?

答:
Is your MQTT Client ID the same as your Thing Name?

I recently had a similar issue while trying to create a policy that uses the Thing attributes.  It wasn't picking up the fact that I had attached my Cognito Identity to the Thing as I would have expected it to do.  My policy did not work until I changed my MQTT Client ID and then the thing attributes were pulled in correctly.  I was hoping to have a Thing per customer, but as MQTT Client ID must be unique and it's also what attaches the connection to a Thing, I'll need to create a Thing per customer per device.

I believe the reasoning, behind attaching an identity principal to a Thing and using the MQTT Client ID to attach the connection to the Thing, is because you can actually attach the same identity principal to multiple Things and on the backend it wouldn't know the exact thing you connection should be.  This allows you to reuse the same identity across multiple devices for the same customer, which is more keeping with how Cognito works.  It also prevents a certificate or Cognito identity from attaching to a Thing that it doesn't have permissions.

Let me know if this helps.

Body:
I am trying out the ShadowSample example that comes as part of Java AWS IoT Device SDK - https://github.com/aws/aws-iot-device-sdk-java/blob/master/aws-iot-device-sdk-java-samples/src/main/java/com/amazonaws/services/iot/client/sample/shadow/ShadowSample.java

I am able to run it successfully and it works properly. However, it works properly when I have the following policy attached to the certificate (and certificate in turn to device) -

{
  "Version": "2012-10-17",
  "Statement": [
  {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe",
        "iot:Receive",
        "iot:Publish",
        "iot:Connect"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

I want to have a generic and strict policy (especially for publish and receive actions) than granting rights to all i.e. "*" resource. So, I update the policy in the below forms and all are not working -

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe",
        "iot:Connect"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": [
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete",
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/accepted",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/rejected",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/delta",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/documents",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/accepted",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/rejected",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/accepted",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/rejected",
      ]
    }
  ]
}

and

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe",
        "iot:Connect"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/*",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/*",
        "arn:aws:iot:us-west-2:64867635xxxx:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/*",
      ]
    }
  ]
}

Note - For security purpose, I have put xxxx against account number. In real policies, I have proper values.

I even replace the * in topic with #, but the same result continues. The result is -

Oct 25, 2017 9:32:43 AM com.amazonaws.services.iot.client.mqtt.AwsIotMqttConnectionListener onFailure
WARNING: Connect request failure
Unable to connect to server (32103) - java.net.ConnectException: Connection timed out: connect
    at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:94)
    at org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule.start(SSLNetworkModule.java:103)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:701)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:80)
    ... 9 more

Oct 25, 2017 9:32:43 AM com.amazonaws.services.iot.client.core.AwsIotConnection onConnectionFailure
INFO: Connection temporarily lost

On the AWS CloudWatch, under AWS IoT specific logs, I find -

2017-10-25 04:10:22.633 TRACEID:1db8b391-83c7-faf3-5aeb-c0d106787afe PRINCIPALID:e7ac813cdcbecffebecef9647a166882f93f5a2aa214cb6bbd9a1e41f7832f76 [ERROR] EVENT:MQTT Client Connect MESSAGE:Connect Status: AUTHORIZATION_ERROR

What shall be the generic and strict policy for supporting publish and receive actions?

Note that the aforementioned policies which I have tried are working fine when I try out the pub-sub example (also provided in the same SDK). These policies are not working for shadow example because there is an additional step of attaching device to connection client.

Another small query: How will I minimise or restrict topic subscription for subscribe action in generic way as variable replacement like thing type, thing name do not work for subscribe (but work for receive and publish)?


来源: stackexchange

问:
Problems querying a user defined table with a Parameter in SapB1
I am making a query for an API. I make the query in the query editor. I get there by clicking tools->queries->user queries-> select a query

In the editor I write the following:

```<code>select * from "@FR_RETAILADDR" where "U_FR_STORECODE" = [%code]
</code>```

that does not work. I am given the following error:

```<code>"" (SWEI)
</code>```

Any user defined table does not allow a parameter to be given. I can do the exact save with the OCRD table.

A side note my company just switched to SAP B1 last week. So we are all new here.

答:
It was a trick by SAP B1. The query returns an error in SAP, but if you actually run the query through the API it works fine. So the solution is to try ignoring SAP if the error returned does not exist.

It is a bug in SAP B1

ContentLicense: CC BY-SA 3.0

Body:
I am making a query for an API. I make the query in the query editor. I get there by clicking tools->queries->user queries-> select a query

In the editor I write the following:

select * from "@FR_RETAILADDR" where "U_FR_STORECODE" = [%code]

that does not work. I am given the following error:

"" (SWEI)

Any user defined table does not allow a parameter to be given. I can do the exact save with the OCRD table.

A side note my company just switched to SAP B1 last week. So we are all new here.


问:
Check if tab exists in TabControl c#
I want to dynamically change the Tabs in a Tab Control depending on what options the user selects.

I have followed the example here TabControl.TabPageCollection.Contains Method (TabPage)

My code is as follows;

```<code>private TabPage VulnTab;

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}
</code>```

This is fired on a button click.

On the first run, there is no VulnTab so it creates one successfully. However, on re-clicking the button it creates a new one again, and so on.

I want it to note on the 2nd button click that the tab page already exists and just go there.

How can I achieve this?

答:
Your problem is, that you are creating completely new page every time.
As you are defining private TabPage object, you could move it to the class (Form?) scope and check if it's null, like in example below:

```<code>private TabPage VulnTab;

private void ButtonClicked(object sender, EventArgs args)
{
    if (VulnTab != null)
    {
        tabControl1.SelectedTab = VulnTab;
    }
    else
    {
        VulnTab = new TabPage("Vulnerability");
        tabControl1.TabPages.Add(VulnTab);

        tabControl1.SelectedTab = VulnTab;
        var vuln = new vulnerability();
        tabControl1.SelectedTab.Controls.Add(vuln);
    }
}
</code>```

Of course ButtonClicked is just whatever method fires your action of creating and/or changing the tab.

For your future reference: If you create new object (by using keyword new) you are creating completely new object. They might be identical, but they are not the same thing, like two apples which look the same aren't the same apple. Only under some specific conditions (object being simple type (numbers, DateTime) or having IEquatable implemented) two objects created in two separate places might be equal to .NET.

Title: Check if tab exists in TabControl c#

Body:
I want to dynamically change the Tabs in a Tab Control depending on what options the user selects.

I have followed the example here TabControl.TabPageCollection.Contains Method (TabPage)

My code is as follows;

private TabPage VulnTab;

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}

This is fired on a button click.

On the first run, there is no VulnTab so it creates one successfully. However, on re-clicking the button it creates a new one again, and so on.

I want it to note on the 2nd button click that the tab page already exists and just go there.

How can I achieve this?

Body:
Your problem is, that you are creating completely new page every time.
As you are defining private TabPage object, you could move it to the class (Form?) scope and check if it's null, like in example below:

private TabPage VulnTab;

private void ButtonClicked(object sender, EventArgs args)
{
    if (VulnTab != null)
    {
        tabControl1.SelectedTab = VulnTab;
    }
    else
    {
        VulnTab = new TabPage("Vulnerability");
        tabControl1.TabPages.Add(VulnTab);

        tabControl1.SelectedTab = VulnTab;
        var vuln = new vulnerability();
        tabControl1.SelectedTab.Controls.Add(vuln);
    }
}

Of course ButtonClicked is just whatever method fires your action of creating and/or changing the tab.

For your future reference: If you create new object (by using keyword new) you are creating completely new object. They might be identical, but they are not the same thing, like two apples which look the same aren't the same apple. Only under some specific conditions (object being simple type (numbers, DateTime) or having IEquatable implemented) two objects created in two separate places might be equal to .NET.


问:
How to replicate POST login with NSURLSession
I'm trying to write a iOS app to be my personal front-end to my city library's website.  In effect, I want my app to invisibly visit the library's webpage, enter my username and password, and then send HTTP requests to invisibly browse through the library's web interface to get my list of checked-out items, renew items near their due dates, etc.

The first step is to be able to send in my username and password.  I've stripped down the library's login page to the following:

```<code><html>
<body>
    <form action="http://brown.ent.sirsi.net/client/en_US/home/search/patronlogin.loginpageform/TRAINING" method="post">
        <input name="t:ac" type="hidden" value="http:$002f$002fbrown.ent.sirsi.net"></input>
        <input name="t:formdata" type="hidden" value="gFJQUIXDSUXVXoGv49wm3q8cIUQ=:H4sIAAAAAAAAAFvzloG1XJ5Btjg1sSg5Qz8gsaQoP88nPz0zzyorvrQ4tSgvMTe1uIjBNL8oXS+xIDE5I1WvJLEgtbikqNJULzm/KDUnM0kvKbE4Vc8xCSiYmFzilpmak6ISnFpSWqAaepj7oejxP0wMjD4M3Mn5eUDTc/yAJpYwCPlkJZYl6uck5qXrB5cUZealW1cUlDBwIWwlxlmOpDoroCg/ObW4OLg0KTezuDgzP+/wuhSTtG/zzjExMFQU4LSyILG4uDy/KKW4kKGOgQHsTJgQQT0gLazl0gySWFRlZKakpOYBPeKA1yPJ+bkF+XmpeSXFeh5gHZj+iGpXEK6Q3sGGEdQg6xlBQcsGsQyHS4pBJpWQ4hKw3SWYLpkZ/Ely65YWZyYGJh8GjuScTKBqT3AogFyWmpOaCxRAcRkHxPJ4AyQmABiJtLaZAgAA"></input>
        Library Card #: <input name="j_username" value = "29878001234567" type="text"></input><br/>
        PIN: <input name="j_password" value="1234" type="text"></input><br/>
        <input name="hidden" value="SYMWS" type="hidden"></input>
        <input type="submit"></input>
    </form>
</body>
</html>
</code>```

When I open this HTML file from my hard drive, enter my real library card number and PIN, and submit the form, I successfully log into the library's system.  When I click on "submit" with just the dummy numbers in the code above, I receive the "login failed" screen just as I should.

I've tried to imitate this in my Swift code as follows:

```<code>func loginToLibrary() {
    let request = NSMutableURLRequest(URL: NSURL(string: "http://brown.ent.sirsi.net/client/en_US/home/search/patronlogin.loginpageform/TRAINING")!)
    request.HTTPMethod = "POST"
    var postString = "t:ac=http:$002f$002fbrown.ent.sirsi.net"
    postString += "&t:formdata=gFJQUIXDSUXVXoGv49wm3q8cIUQ=:H4sIAAAAAAAAAFvzloG1XJ5Btjg1sSg5Qz8gsaQoP88nPz0zzyorvrQ4tSgvMTe1uIjBNL8oXS+xIDE5I1WvJLEgtbikqNJULzm/KDUnM0kvKbE4Vc8xCSiYmFzilpmak6ISnFpSWqAaepj7oejxP0wMjD4M3Mn5eUDTc/yAJpYwCPlkJZYl6uck5qXrB5cUZealW1cUlDBwIWwlxlmOpDoroCg/ObW4OLg0KTezuDgzP+/wuhSTtG/zzjExMFQU4LSyILG4uDy/KKW4kKGOgQHsTJgQQT0gLazl0gySWFRlZKakpOYBPeKA1yPJ+bkF+XmpeSXFeh5gHZj+iGpXEK6Q3sGGEdQg6xlBQcsGsQyHS4pBJpWQ4hKw3SWYLpkZ/Ely65YWZyYGJh8GjuScTKBqT3AogFyWmpOaCxRAcRkHxPJ4AyQmABiJtLaZAgAA"
    postString += "&j_username=29878001234567"
    postString += "&j_password=1234"
    postString += "&hidden=SYMWS"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("response to login attempt = \(responseString)")
    }
    task.resume()
}
</code>```

When I run the Swift code, however, the following is printed to the console:

```<code>response to login attempt = Optional(<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml"><head><link rel="shortcut icon" href="/client/assets/4.5.03/ctx/favicon.ico" type="image/vnd.mircrosoft.icon" id="favicon"/><title>Unexpected Error</title><link type="text/css" rel="stylesheet" href="/client/assets/4.5.03/core/default.css"/><meta content="Apache Tapestry Framework (version 5.3.7)" name="generator"/></head><body><div id="exception"><h1>Unexpected Error</h1><div class="pageheading">The system encountered an error while processing the following request:</div><div class="url">/en_US/home/search/patronlogin.loginpageform/TRAINING</div><h2>Error Summary</h2><div class="cause">java.io.IOException: Client data associated with the current request appears to have been tampered with (the HMAC signature does not match).</div><div class="timestamp">Wed May 25 22:51:42 CDT 2016</div></div></body></html>)
</code>```

Interpreting that in a browser, it is:

Unexpected Error
Unexpected Error
The system encountered an error while processing the following request:/en_US/home/search/patronlogin.loginpageform/TRAINING
Error Summary
java.io.IOException: Client data associated with the current request appears to have been tampered with (the HMAC signature does not match).Wed May 25 22:51:42 CDT 2016)

Can anyone please help me figure out how the POST request sent by my Swift code differs from the POST request my browser sends from the stripped-down webpage above?

For what it's worth, I can obtain the same error (HMAC signature not matching) in the browser from my stripped-down webpage if I change the value of the t:formdata input.  I've tried percent-encoding the = (about 30 characters into the t:formdata value) as %3D, and even the /'s as %2F, but that didn't help.

答: URL encode is missing for the data you post to symphony, I have got the same issue you encountered. That is the reason why symphony got a wrong t:formdata</p>

Body:
I'm trying to write a iOS app to be my personal front-end to my city library's website.  In effect, I want my app to invisibly visit the library's webpage, enter my username and password, and then send HTTP requests to invisibly browse through the library's web interface to get my list of checked-out items, renew items near their due dates, etc.

The first step is to be able to send in my username and password.  I've stripped down the library's login page to the following:

    <form action="http://brown.ent.sirsi.net/client/en_US/home/search/patronlogin.loginpageform/TRAINING" method="post">
        <input name="t:ac" type="hidden" value="http:$002f$002fbrown.ent.sirsi.net"></input>
        <input name="t:formdata" type="hidden" value="gFJQUIXDSUXVXoGv49wm3q8cIUQ=:H4sIAAAAAAAAAFvzloG1XJ5Btjg1sSg5Qz8gsaQoP88nPz0zzyorvrQ4tSgvMTe1uIjBNL8oXS+xIDE5I1WvJLEgtbikqNJULzm/KDUnM0kvKbE4Vc8xCSiYmFzilpmak6ISnFpSWqAaepj7oejxP0wMjD4M3Mn5eUDTc/yAJpYwCPlkJZYl6uck5qXrB5cUZealW1cUlDBwIWwlxlmOpDoroCg/ObW4OLg0KTezuDgzP+/wuhSTtG/zzjExMFQU4LSyILG4uDy/KKW4kKGOgQHsTJgQQT0gLazl0gySWFRlZKakpOYBPeKA1yPJ+bkF+XmpeSXFeh5gHZj+iGpXEK6Q3sGGEdQg6xlBQcsGsQyHS4pBJpWQ4hKw3SWYLpkZ/Ely65YWZyYGJh8GjuScTKBqT3AogFyWmpOaCxRAcRkHxPJ4AyQmABiJtLaZAgAA"></input>
        Library Card #: <input name="j_username" value = "29878001234567" type="text"></input>

        PIN: <input name="j_password" value="1234" type="text"></input>

        <input name="hidden" value="SYMWS" type="hidden"></input>
        <input type="submit"></input>
    </form>

When I open this HTML file from my hard drive, enter my real library card number and PIN, and submit the form, I successfully log into the library's system.  When I click on "submit" with just the dummy numbers in the code above, I receive the "login failed" screen just as I should.

I've tried to imitate this in my Swift code as follows:

func loginToLibrary() {
    let request = NSMutableURLRequest(URL: NSURL(string: "http://brown.ent.sirsi.net/client/en_US/home/search/patronlogin.loginpageform/TRAINING")!)
    request.HTTPMethod = "POST"
    var postString = "t:ac=http:$002f$002fbrown.ent.sirsi.net"
    postString += "&t:formdata=gFJQUIXDSUXVXoGv49wm3q8cIUQ=:H4sIAAAAAAAAAFvzloG1XJ5Btjg1sSg5Qz8gsaQoP88nPz0zzyorvrQ4tSgvMTe1uIjBNL8oXS+xIDE5I1WvJLEgtbikqNJULzm/KDUnM0kvKbE4Vc8xCSiYmFzilpmak6ISnFpSWqAaepj7oejxP0wMjD4M3Mn5eUDTc/yAJpYwCPlkJZYl6uck5qXrB5cUZealW1cUlDBwIWwlxlmOpDoroCg/ObW4OLg0KTezuDgzP+/wuhSTtG/zzjExMFQU4LSyILG4uDy/KKW4kKGOgQHsTJgQQT0gLazl0gySWFRlZKakpOYBPeKA1yPJ+bkF+XmpeSXFeh5gHZj+iGpXEK6Q3sGGEdQg6xlBQcsGsQyHS4pBJpWQ4hKw3SWYLpkZ/Ely65YWZyYGJh8GjuScTKBqT3AogFyWmpOaCxRAcRkHxPJ4AyQmABiJtLaZAgAA"
    postString += "&j_username=29878001234567"
    postString += "&j_password=1234"
    postString += "&hidden=SYMWS"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("response to login attempt = \(responseString)")
    }
    task.resume()
}

When I run the Swift code, however, the following is printed to the console:

response to login attempt = Optional(<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><link rel="shortcut icon" href="/client/assets/4.5.03/ctx/favicon.ico" type="image/vnd.mircrosoft.icon" id="favicon"/><title>Unexpected Error</title><link type="text/css" rel="stylesheet" href="/client/assets/4.5.03/core/default.css"/><meta content="Apache Tapestry Framework (version 5.3.7)" name="generator"/>

Unexpected Error

The system encountered an error while processing the following request:

/en_US/home/search/patronlogin.loginpageform/TRAINING

Error Summary

java.io.IOException: Client data associated with the current request appears to have been tampered with (the HMAC signature does not match).

Wed May 25 22:51:42 CDT 2016

)

Interpreting that in a browser, it is:

Unexpected Error
Unexpected Error
The system encountered an error while processing the following request:/en_US/home/search/patronlogin.loginpageform/TRAINING
Error Summary
java.io.IOException: Client data associated with the current request appears to have been tampered with (the HMAC signature does not match).Wed May 25 22:51:42 CDT 2016)

Can anyone please help me figure out how the POST request sent by my Swift code differs from the POST request my browser sends from the stripped-down webpage above?

For what it's worth, I can obtain the same error (HMAC signature not matching) in the browser from my stripped-down webpage if I change the value of the t:formdata input.  I've tried percent-encoding the = (about 30 characters into the t:formdata value) as %3D, and even the /'s as %2F, but that didn't help.


问:
Swift String escaping when serializing to JSON using Codable
I'm trying to serialize my object as following:

```<code>import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

let user = User(username: "John", profileURL: "http://google.com")

let json = try? JSONEncoder().encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}
</code>```

However on macOS I'm getting the following:

```<code>{"profileURL":"http:\/\/google.com","username":"John"}
</code>```

(note escaped '/' character).

While on Linux machines I'm getting:

```<code>{"username":"John","profileURL":"http://google.com"}
</code>```

How can I make JSONEncoder return the unescaped?

I need the string in JSON to be strictly unescaped.

答:
Actually you cannot do that since in macOS and Linux are a bit different escaping systems. On linux // is allowed, macOS - not(it uses NSSerialization). So, you can just add percent encoding on your string, which guarantees you equal strings on macOS and linux, right string posting to a server and right validating. On adding percent escaping set CharacterSet.urlHostAllowed. Could be done like this:

```<code>init(name: String, profile: String){
        username = name
        if let percentedString = profile.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed){
            profileURL = percentedString
        }else{
            profileURL = ""
        }
    }
</code>```

In the same manner, you can removePercentEncoding
AND YOU DONT NEED MODIFY SERVER SIDE!!!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to serialize my object as following:

import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

let user = User(username: "John", profileURL: "http://google.com")

let json = try? JSONEncoder().encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}

However on macOS I'm getting the following:

{"profileURL":"http:\/\/google.com","username":"John"}

(note escaped '/' character).

While on Linux machines I'm getting:

{"username":"John","profileURL":"http://google.com"}

How can I make JSONEncoder return the unescaped?

I need the string in JSON to be strictly unescaped.

Body:
Actually you cannot do that since in macOS and Linux are a bit different escaping systems. On linux // is allowed, macOS - not(it uses NSSerialization). So, you can just add percent encoding on your string, which guarantees you equal strings on macOS and linux, right string posting to a server and right validating. On adding percent escaping set CharacterSet.urlHostAllowed. Could be done like this:

init(name: String, profile: String){
        username = name
        if let percentedString = profile.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed){
            profileURL = percentedString
        }else{
            profileURL = ""
        }
    }

In the same manner, you can removePercentEncoding
AND YOU DONT NEED MODIFY SERVER SIDE!!!


问:
Some view elements won't hide, some won't appear
For some reason some of my view elements won't hide when I set Visibility to Gone, others won't appear when I set it to Visible.

In this example, cmdCallMe won't hide and cmdOk and cmdCancel won't appear. The other elements all behave as expected.

(source shortened slightly)

Activity code:

```<code>    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.p2);
        titleStatusView = FindViewById<TextView>(Resource.Id.lblP2Status);
        outputTextView = FindViewById<TextView>(Resource.Id.lblP2Timer);
        lblConfirm = FindViewById<TextView>(Resource.Id.lblP2Confirm);
        cmdP2Update = FindViewById<Button>(Resource.Id.cmdP2Update);
        cmdP2Arrived = FindViewById<Button>(Resource.Id.cmdP2Arrived);
        cmdP2SelfDeployed = FindViewById<Button>(Resource.Id.cmdP2SelfDeployed);
        cmdP2CallMe = FindViewById<Button>(Resource.Id.cmdP2CallMe);

        cmdOk = FindViewById<Button>(Resource.Id.cmdP2CallMe);
        cmdCancel = FindViewById<Button>(Resource.Id.cmdP2CallMe);

        // hide normal buttons
        // these all hide as expected
        cmdP2Update.Visibility = ViewStates.Gone;
        cmdP2Arrived.Visibility = ViewStates.Gone;
        cmdP2SelfDeployed.Visibility = ViewStates.Gone;
        // this should hide cmdCallMe but it doesn't change
        cmdP2CallMe.Visibility = ViewStates.Gone;
        // show confirm elements
        // this appears as expected
        lblConfirm.Visibility = ViewStates.Visible;
        // the following 2 buttons should appear, but don't
        cmdOk.Visibility = ViewStates.Visible;
        cmdCancel.Visibility = ViewStates.Visible;
</code>```

AXML:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:text="Status: EN-ROUTE"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblP2Status"
        android:gravity="center" />
    <TextView
        android:text="00:00:00"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblP2Timer"
        android:gravity="center"
        android:layout_marginBottom="19.0dp" />
    <Button
        android:text="Update"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2Update"
        android:layout_marginBottom="10.5dp"
        android:background="@android:color/holo_green_dark" />
    <Button
        android:text="ARRIVED"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2Arrived" />
    <Button
        android:text="SELF DEPLOYED"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2SelfDeployed"
        android:layout_marginBottom="10.5dp" />
    <Button
        android:text="CALL ME"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2CallMe"
        android:layout_marginTop="0.0dp" />
    <TextView
        android:text="Are you sure?"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblP2Confirm"
        android:gravity="center"
        android:layout_marginBottom="16.0dp"
        android:visibility="gone" />
    <LinearLayout
        android:orientation="horizontal"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout1">
        <Button
            android:text="OK"
            android:layout_width="190dp"
            android:layout_height="wrap_content"
            android:id="@+id/cmdOk"
            android:visibility="gone" />
        <Button
            android:text="Cancel"
            android:layout_width="190dp"
            android:layout_height="wrap_content"
            android:id="@+id/cmdCancel"
            android:visibility="gone" />
    </LinearLayout>
</LinearLayout>
</code>```

When I step through all values are assigned as I would expect. I can't work out why the elements visibility doesn't always reflect this.

答:
Look at your code :

```<code>cmdP2CallMe = FindViewById<Button>(Resource.Id.cmdP2CallMe);

    cmdOk = FindViewById<Button>(Resource.Id.cmdP2CallMe);    <-- reference error here
    cmdCancel = FindViewById<Button>(Resource.Id.cmdP2CallMe);<-- reference error here
</code>```

:)

Body:
For some reason some of my view elements won't hide when I set Visibility to Gone, others won't appear when I set it to Visible.

In this example, cmdCallMe won't hide and cmdOk and cmdCancel won't appear. The other elements all behave as expected.

(source shortened slightly)

Activity code:

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.p2);
        titleStatusView = FindViewById<TextView>(Resource.Id.lblP2Status);
        outputTextView = FindViewById<TextView>(Resource.Id.lblP2Timer);
        lblConfirm = FindViewById<TextView>(Resource.Id.lblP2Confirm);
        cmdP2Update = FindViewById<Button>(Resource.Id.cmdP2Update);
        cmdP2Arrived = FindViewById<Button>(Resource.Id.cmdP2Arrived);
        cmdP2SelfDeployed = FindViewById<Button>(Resource.Id.cmdP2SelfDeployed);
        cmdP2CallMe = FindViewById<Button>(Resource.Id.cmdP2CallMe);

        cmdOk = FindViewById<Button>(Resource.Id.cmdP2CallMe);
        cmdCancel = FindViewById<Button>(Resource.Id.cmdP2CallMe);

        // hide normal buttons
        // these all hide as expected
        cmdP2Update.Visibility = ViewStates.Gone;
        cmdP2Arrived.Visibility = ViewStates.Gone;
        cmdP2SelfDeployed.Visibility = ViewStates.Gone;
        // this should hide cmdCallMe but it doesn't change
        cmdP2CallMe.Visibility = ViewStates.Gone;
        // show confirm elements
        // this appears as expected
        lblConfirm.Visibility = ViewStates.Visible;
        // the following 2 buttons should appear, but don't
        cmdOk.Visibility = ViewStates.Visible;
        cmdCancel.Visibility = ViewStates.Visible;

AXML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:text="Status: EN-ROUTE"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblP2Status"
        android:gravity="center" />
    <TextView
        android:text="00:00:00"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblP2Timer"
        android:gravity="center"
        android:layout_marginBottom="19.0dp" />
    <Button
        android:text="Update"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2Update"
        android:layout_marginBottom="10.5dp"
        android:background="@android:color/holo_green_dark" />
    <Button
        android:text="ARRIVED"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2Arrived" />
    <Button
        android:text="SELF DEPLOYED"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2SelfDeployed"
        android:layout_marginBottom="10.5dp" />
    <Button
        android:text="CALL ME"
        android:layout_width="match_parent"
        android:layout_height="64.5dp"
        android:id="@+id/cmdP2CallMe"
        android:layout_marginTop="0.0dp" />
    <TextView
        android:text="Are you sure?"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblP2Confirm"
        android:gravity="center"
        android:layout_marginBottom="16.0dp"
        android:visibility="gone" />
    <LinearLayout
        android:orientation="horizontal"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout1">
        <Button
            android:text="OK"
            android:layout_width="190dp"
            android:layout_height="wrap_content"
            android:id="@+id/cmdOk"
            android:visibility="gone" />
        <Button
            android:text="Cancel"
            android:layout_width="190dp"
            android:layout_height="wrap_content"
            android:id="@+id/cmdCancel"
            android:visibility="gone" />
    </LinearLayout>
</LinearLayout>

When I step through all values are assigned as I would expect. I can't work out why the elements visibility doesn't always reflect this.

Body:
Look at your code :

cmdP2CallMe = FindViewById<Button>(Resource.Id.cmdP2CallMe);

    cmdOk = FindViewById<Button>(Resource.Id.cmdP2CallMe);    <-- reference error here
    cmdCancel = FindViewById<Button>(Resource.Id.cmdP2CallMe);<-- reference error here

:)


问:
Find minimum and maximum with where clause inside a query- SQL DB2
I am trying to get minimum and maximum date for area 12. I do not know how to use where clause inside a query.</p>

```<code>SELECT A1.*, Ticket_ID,
min(StartDate) OVER(PARTITION BY Ticket_ID) AS Min_StartDate,
MAX(EndDate) OVER(PARTITION BY Ticket_ID) AS Max_EndDate
WHERE area = '12'
FROM (SELECT T1.Ticket_ID, T1.StartDate,T1.StartDate, t2.title, t1.area,T2.Ticket_TYPE
      FROM Ticket1 t1
      LEFT JOIN Ticket2 t2 on t1.Ticket_ID = t2.Ticket_ID
     ) A1
WHERE Ticket_TYPE = 1 AND StartDate <= '9/30/2017'
AND (EndDate >= '10/01/2017' OR EndDate IS NULL)
ORDER BY Ticket_ID
</code>```

答:
Try to run it as:

```<code>SELECT A1.*, A1.Ticket_ID,
min(StartDate) OVER(PARTITION BY Ticket_ID) AS Min_StartDate,
MAX(EndDate) OVER(PARTITION BY Ticket_ID) AS Max_EndDate
FROM (SELECT T1.Ticket_ID, T1.StartDate,T1.EndDate, t2.title, t1.area,T2.Ticket_TYPE
      FROM Ticket1 t1
      LEFT JOIN Ticket2 t2 on t1.Ticket_ID = t2.Ticket_ID
      WHERE t2.Ticket_TYPE = 1 AND t1.StartDate <= '9/30/2017'
        AND (t1.EndDate >= '10/01/2017' OR t1.EndDate IS NULL)
        AND t1.area = '12'
     ) A1
ORDER BY A1.Ticket_ID
</code>```

*You have a typo of specifying StartDate twice, corrected as EndDate in subquery.

Body:
I am trying to get minimum and maximum date for area 12. I do not know how to use where clause inside a query.

SELECT A1.*, Ticket_ID,
min(StartDate) OVER(PARTITION BY Ticket_ID) AS Min_StartDate,
MAX(EndDate) OVER(PARTITION BY Ticket_ID) AS Max_EndDate
WHERE area = '12'
FROM (SELECT T1.Ticket_ID, T1.StartDate,T1.StartDate, t2.title, t1.area,T2.Ticket_TYPE
      FROM Ticket1 t1
      LEFT JOIN Ticket2 t2 on t1.Ticket_ID = t2.Ticket_ID
     ) A1
WHERE Ticket_TYPE = 1 AND StartDate <= '9/30/2017'
AND (EndDate >= '10/01/2017' OR EndDate IS NULL)
ORDER BY Ticket_ID

Body:
Try to run it as:

SELECT A1.*, A1.Ticket_ID,
min(StartDate) OVER(PARTITION BY Ticket_ID) AS Min_StartDate,
MAX(EndDate) OVER(PARTITION BY Ticket_ID) AS Max_EndDate
FROM (SELECT T1.Ticket_ID, T1.StartDate,T1.EndDate, t2.title, t1.area,T2.Ticket_TYPE
      FROM Ticket1 t1
      LEFT JOIN Ticket2 t2 on t1.Ticket_ID = t2.Ticket_ID
      WHERE t2.Ticket_TYPE = 1 AND t1.StartDate <= '9/30/2017'
        AND (t1.EndDate >= '10/01/2017' OR t1.EndDate IS NULL)
        AND t1.area = '12'
     ) A1
ORDER BY A1.Ticket_ID

*You have a typo of specifying StartDate twice, corrected as EndDate in subquery.


问:
Can't resolve all parameters -getting this error in browser angular2
I am trying to create a movie finder website using api key .Everything looks perfect as far as code as well as the api key -i could access the values  just by hitting the api request but getting error in browser.Appreciate if some one can help me

Error:

Error Image

This is My  movies.service.ts

```<code> import {Injectable} from  '@angular/core';
import {Jsonp,JsonpModule} from '@angular/http';
import 'rxjs/Rx';

Injectable()

export class MovieService
{
apikey:string;
constructor(private _jsonp:Jsonp)
    {
this.apikey='##';
console.log('Movie Service Initialized');
    }

getPopular()
{

return this._jsonp.get('https://api.themoviedb.org/3/discover/movie?callback=JSONP_CALLBACK&sort_by=popularity.desc&api_key=##')
.map(res=>res.json());
}

}
</code>```

This is my movies.components.ts where i am calling the service

```<code>import { Component } from '@angular/core';
import {MovieService} from 'app/services/movies.service';

@Component({
  selector: 'Movies',
  templateUrl: 'movies.components.html',

})
export class MoviesComponent {

    constructor(private _movieservice:MovieService)
    {
           this._movieservice.getPopular().subscribe(res=>{

               console.log(res.results)
           });

    }

}
</code>```

This is my app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule,JsonpModule } from '@angular/http';

import { AppComponent } from './app.component';
import {MoviesComponent} from 'app/components/movies/movies.components';
import {MovieService} from  'app/services/movies.service';

@NgModule({
  declarations: [
    AppComponent,
    MoviesComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,

  ],
  providers: [MovieService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答: You've probably solved this already. The only thing I see is that you're missing an '@' symbol before your Injectable in the MovieService. Hope that helps!</p>

Body:
I am trying to create a movie finder website using api key .Everything looks perfect as far as code as well as the api key -i could access the values  just by hitting the api request but getting error in browser.Appreciate if some one can help me

Error:

Error Image

This is My  movies.service.ts

 import {Injectable} from  '@angular/core';
import {Jsonp,JsonpModule} from '@angular/http';
import 'rxjs/Rx';

Injectable()

export class MovieService
{
apikey:string;
constructor(private _jsonp:Jsonp)
    {
this.apikey='##';
console.log('Movie Service Initialized');
    }

getPopular()
{

return this._jsonp.get('https://api.themoviedb.org/3/discover/movie?callback=JSONP_CALLBACK&sort_by=popularity.desc&api_key=##')
.map(res=>res.json());
}

}

This is my movies.components.ts where i am calling the service

import { Component } from '@angular/core';
import {MovieService} from 'app/services/movies.service';

@Component({
  selector: 'Movies',
  templateUrl: 'movies.components.html',

})
export class MoviesComponent {

    constructor(private _movieservice:MovieService)
    {
           this._movieservice.getPopular().subscribe(res=>{

               console.log(res.results)
           });

    }

}

This is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule,JsonpModule } from '@angular/http';

import { AppComponent } from './app.component';
import {MoviesComponent} from 'app/components/movies/movies.components';
import {MovieService} from  'app/services/movies.service';

@NgModule({
  declarations: [
    AppComponent,
    MoviesComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,

  ],
  providers: [MovieService],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Positioning issue not working for me
Probably a simple fix, but after messing with this issue for 2 hours I'm turning to you guys...

Below is a link to what I'm playing with. My issue is, the side content is not aligning correctly.

http://back2lifedesigns.com/WordPress-Client-Test/

I need the left aside to move left so it is not blocked by the rollover image. Everything I tried either did nothing, made it worse, or messed up other parts of the site.

答:
Add this CSS:

```<code>#bar-left {
  left: -15px;
}
</code>```

adjust the pixel value as needed...

Title: Positioning issue not working for me

Body:
Add this CSS:

#bar-left {
  left: -15px;
}

adjust the pixel value as needed...


问:
Is Google API's access token never expiring?
I don't know if there is a problem with my code but; using google-apis nodejs client for Drive REST API.

However, when I refresh my access token with the refresh token provided, it gives me an expiry time as seconds. (3600 more seconds from request)

I store them in a text file. Then I set credentials before a new request.

```<code>oauth2Client.setCredentials({
  access_token: gTokens[0],
  refresh_token: gTokens[1],
  expiry_date: gTokens[2]
});

var expiryDate = oauth2Client.credentials.expiry_date;

var isTokenExpired = expiryDate ? expiryDate <= (new Date()).getTime() : false;
</code>```

Then I check wheter access token is expired or not. The code above gives me true for isTokenExpired. Even If my access token is expired, I can upload a file to Google Drive with an access token which is expired long time ago.

What's the problem?

答:
There is no problem - you're also saving the refresh_token, it sounds like, and the client library has logic that uses the refresh_token to get a new access_token if the first one you use fails.

What it does not do, however, is save this token automatically. You need to take action to setup hooks to do the save if necessary.

Body:
I don't know if there is a problem with my code but; using google-apis nodejs client for Drive REST API.

However, when I refresh my access token with the refresh token provided, it gives me an expiry time as seconds. (3600 more seconds from request)

I store them in a text file. Then I set credentials before a new request.

oauth2Client.setCredentials({
  access_token: gTokens[0],
  refresh_token: gTokens[1],
  expiry_date: gTokens[2]
});

var expiryDate = oauth2Client.credentials.expiry_date;

var isTokenExpired = expiryDate ? expiryDate <= (new Date()).getTime() : false;

Then I check wheter access token is expired or not. The code above gives me true for isTokenExpired. Even If my access token is expired, I can upload a file to Google Drive with an access token which is expired long time ago.

What's the problem?


问:
Do I need to buy a developer certificate if inside developer team organization (enrollment)?
Do I need to buy a indiviudual developer certificate if I'm on the development team of an organization and want to publish and test applications on behalf of the organization.
I do not have my own certificate and I can not test the application on a real device, I indicate that I am inside the team of the organization from which the certificate was purchased.</p>

答:
No, you do not need to purchase an individual certificate; you develop under the organization's certificate, and release under the organization's certificate as well. In XCode, under the General tab, look for the Signing section, where you can specify your Team (organization). The application will be signed with the organization's certirficate.

Do note, however, that an 'Organization' developer certificate cannot publish apps to the Apple App Store, only in-house. If you want to publish to the App Store, you need an 'Enterprise' certificate. If you want to publish both to the store and in-house, you'll need both certificates!

Also, note that not only do you need to be a team member of your organization in Apple's Developer Program, but also in iTunes Connect! Those are separate registrations, and you will need to be invited to join the iTunes Connect team by the person who set up the team account, or an existing administrator:

Initially, only the team agent (the person who joins the Apple Developer Program) can sign in to iTunes Connect and perform these steps. [...] If you are the team agent, use the Apple ID you used to join the Apple Developer Program and add other users to your iTunes Connect organization.

You'll need to be in both teams before being able to sign applications with your organization's certificate.

Hope this helps! :)


问:
Installing Django on Ubuntu 16.04, python3
I am unable to install django on python3 in ubuntu 16.04.
Here is what I have tried:

```<code>1. pip3 install django
2. pip3 install --trusted-host pypi.python.org django
3. pip3 install --index-url=http://pypi.python.org/simple --trusted-host pypi.python.org django
</code>```

I keep getting the same error:

```<code>Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping
Could not find a version that satisfies the requirement django (from versions: )
No matching distribution found for django
</code>```

I have Django installed on python 2.7, but I need it on python 3.6.

When I run

```<code>sudo apt-get install python3-django
</code>```

it says

```<code>python3-django is already the newest version (1.8.7-1ubuntu5.5).
</code>```

I believe this is because I have python3.5 installed with Django on python3.5, but I need it on 3.6. Python3 refers python3.6. My pip3 is up to date.

Any help is appreciated.

答:
1st: You didn't explicitly say so, but I am assuming you are using linux based on your mention of apt-get

The simplest way to get django on your python 3.6 is to fix pip.  This is a pretty good overview of how to get the libraries that pip needs based on error messages such as yours.  You just need to apt install a few packages.

Once you have all the dependencies installed for pip3 to run, try installing django again.

Note: since you have python3 already, I'd make sure you are calling the right pip3, you can do this by calling:

```<code>pip3 -V
</code>```

If the 'pip3' command is calling the pip3 in 3.5, then use the full path of the pip3 in python 3.6 instead.

Alternatively

You can try copying django from your lib/site-packages folder from your python3.5 installation to your python3.6 installation.  The big gotcha is that you need to make sure to copy all the dependencies for django as well.  You can ether look them up in the django config or you can try and use it and copy them over one at a time based on the error messages.

Unsolicited Advice:
I would strongly suggest using virtualenvs to make this process much easier.  I use pyenv and pyenv-virtualenv here, and have really loved them.

Body:
I am unable to install django on python3 in ubuntu 16.04.
Here is what I have tried:

1. pip3 install django
2. pip3 install --trusted-host pypi.python.org django
3. pip3 install --index-url=http://pypi.python.org/simple --trusted-host pypi.python.org django

I keep getting the same error:

Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping
Could not find a version that satisfies the requirement django (from versions: )
No matching distribution found for django

I have Django installed on python 2.7, but I need it on python 3.6.

When I run

sudo apt-get install python3-django

it says

python3-django is already the newest version (1.8.7-1ubuntu5.5).

I believe this is because I have python3.5 installed with Django on python3.5, but I need it on 3.6. Python3 refers python3.6. My pip3 is up to date.

Any help is appreciated.

Body:
1st: You didn't explicitly say so, but I am assuming you are using linux based on your mention of apt-get

The simplest way to get django on your python 3.6 is to fix pip.  This is a pretty good overview of how to get the libraries that pip needs based on error messages such as yours.  You just need to apt install a few packages.

Once you have all the dependencies installed for pip3 to run, try installing django again.

Note: since you have python3 already, I'd make sure you are calling the right pip3, you can do this by calling:

pip3 -V

If the 'pip3' command is calling the pip3 in 3.5, then use the full path of the pip3 in python 3.6 instead.

Alternatively

You can try copying django from your lib/site-packages folder from your python3.5 installation to your python3.6 installation.  The big gotcha is that you need to make sure to copy all the dependencies for django as well.  You can ether look them up in the django config or you can try and use it and copy them over one at a time based on the error messages.

Unsolicited Advice:
I would strongly suggest using virtualenvs to make this process much easier.  I use pyenv and pyenv-virtualenv here, and have really loved them.


问:
HTML for Email - Change position in CSS doesn't Work
This is my first time coding HTML for e-mail. I saw some tutorials to guide me, but I'm having a problem that I don't know how I can fix it. Basically. all my code is inside of
s. At the end of the page, the footer is also a
. But it doesn't matter how I change the CSS values for the position the result is always this inside the email:

The problem is in this code:

```<code><tr>
  <table id="footer" border="0" align="center" cellpadding="0" cellspacing="0" width="100%" style="background-color: #fe3a35; opacity: 0.9">
    <tr>
      <td valign="top" align="center">
        <p style="font-family: 'Arial'; font-size: 16px; font-weight: 300; text-align: center; position: relative; left: -163px; top: 35px; line-height: 2px; color: white;">® Someone, somewhere 2013</p>
        <p style="font-family: 'Arial'; text-align: center; font-weight: 300;position: relative; left: -132px; top: 25px;ine-height: 2px; color: white;"><a href="" style="font-family: 'Arial'; color: white;">Unsubscribe</a> to this newsletter instantly</p>
        <a href="https://twitter.com/realdonaldtrump" target="_blank" style="position: relative; left: 220px; top: -25px;"><img src="https://i.imgur.com/bgssIwP.png" width="30"></a>
        <a href="https://www.facebook.com/gustavo.olegario" target="_blank" style="position: relative; left: 220px; top: -25px;"><img src="https://i.imgur.com/JQ19LU9.png" width="30"></a>
      </td>
    </tr>
  </table>
</tr>
</code>```

What I would like to do, in fact, is to approximatte the letters to the twitter and the facebook links in the middle.

答:
The basics of email is to you tables just as you have started. I have fixed up your code so it should work on all email clients now.

fix ups:

added tables for your social media icons with slight padding

removed position CSS

images should have display block

      ® Someone, somewhere 2013

      Unsubscribe to this newsletter instantly

```

Let me know if this is the solution you were after.

Cheers

Body:
This is my first time coding HTML for e-mail. I saw some tutorials to guide me, but I'm having a problem that I don't know how I can fix it. Basically. all my code is inside of
s. At the end of the page, the footer is also a
. But it doesn't matter how I change the CSS values for the position the result is always this inside the email:

The problem is in this code:

® Someone, somewhere 2013

Unsubscribe to this newsletter instantly

What I would like to do, in fact, is to approximatte the letters to the twitter and the facebook links in the middle.

Body:
The basics of email is to you tables just as you have started. I have fixed up your code so it should work on all email clients now.

fix ups:

added tables for your social media icons with slight padding

removed position CSS

images should have display block

<table id="footer" border="0" align="center" cellpadding="0" cellspacing="0" width="100%" style="background-color: #fe3a35; opacity: 0.9">
    <tr>
      <td valign="top" align="center"style="font-family: 'Arial'; font-size: 16px; font-weight: 300; text-align: center;color: white;padding:10px 0px;">&reg; Someone, somewhere 2013</td>
    </tr>
    <tr>
      <td valign="top" align="center" style="font-family: 'Arial'; text-align: center; font-weight: 300; color: white;padding:5px 0px 10px 0px;"><a href="" style="font-family: 'Arial'; color: white;">Unsubscribe</a> to this newsletter instantly</td>
    </tr>
    <tr>
      <td valign="top" align="center">

  <table border="0" align="center" cellspacing="0" cellpadding="0">
  <tbody>
    <tr>
      <td style="padding-right:5px;"><a href="https://twitter.com/realdonaldtrump" target="_blank" style=""><img src="https://i.imgur.com/bgssIwP.png" width="30" style="display:block;"></a></td>
      <td style="padding-left:5px;"><a href="https://www.facebook.com/gustavo.olegario" target="_blank" style=""><img src="https://i.imgur.com/JQ19LU9.png" width="30" style="display:block;"></a>
  </td>
    </tr>
  </tbody>
</table>

Let me know if this is the solution you were after.

Cheers


问:
Access Webcam in Jupyter Notebook on Xilinx Pynq FPGA
Hey guys I want to get the live video frames from my usb webcam connected to my Pynq FPGA. The goal is to make motion detection on each frame but I've been struggling to get a live video. I've tried the first example in this link but I get a really bad frame rate. I tried to get a better rate by adding the following line:vc.set(cv2.CAP_PROP_FPS, 60) but it didn't change anything. I tried an example in MATLAB and I had no problems connecting to the webcam and I had a smooth frame rate.

I've read that OpenCV can't be used together with Python3 yet but I still get images in the notebook what I don't understand. I also don't know how to install other packages or libraries like pygame for jupyter notebooks on the pynq, it says everywhere that I have to enter pip install "name" and put the library in the site-packages directory but I haven't seen that directory on jupyter notebooks. So I'm trying to find a way without installing new libraries.

I really need your help guys, do you have some suggestions how to get a live video stream from my webcam on jupyter notebooks?

答:
OpenCV can work with python3. I am using that
at first you need to install pip, it is pretty easy flow.
After that connect the board to the web and use pip install</p>


问:
How to replace vector values with certain proportional weights in igraph?
I have a standard graph with 3 node attributes: "a", "b", and "c". I have code that causes the values of "a" and "b" to change constantly and "c" is dependent on these values. To accommodate the changing values I have the following code running in a for loop.

```<code>V(g)$c[V(g)$a <= V(g)$b] <- sample(c(0, 1), vcount(g), replace = TRUE, prob = c(.9, .1))
</code>```

However it returns the warning:
 number of items to replace is not a multiple of replacement length. and although the code runs, it doesn't take into account the weights for the values. How would I go about fixing this code?

答:
The problem is that your sample statement generates vcount(g) values - one for every node in your graph. But you are trying to store these values into V(g)$c[V(g)$a <= V(g)$b].  Presumably sometimes not every node has V(g)$a <= V(g)$b so there are fewer spots to store the data.  The simple way to fix this is to generate only the right number of values for the attribute c.  One way to do that would be

```<code>V(g)$c[V(g)$a <= V(g)$b] <-
    sample(c(0, 1), sum(V(g)$a <= V(g)$b), replace = TRUE, prob = c(.9, .1))
</code>```

This is just your original statement except that I have replaced vcount(g) with sum(V(g)$a <= V(g)$b) which counts the number of nodes for which V(g)$a <= V(g)$b .

Body:
I have a standard graph with 3 node attributes: "a", "b", and "c". I have code that causes the values of "a" and "b" to change constantly and "c" is dependent on these values. To accommodate the changing values I have the following code running in a for loop.

V(g)$c[V(g)$a <= V(g)$b] <- sample(c(0, 1), vcount(g), replace = TRUE, prob = c(.9, .1))

However it returns the warning:
 number of items to replace is not a multiple of replacement length. and although the code runs, it doesn't take into account the weights for the values. How would I go about fixing this code?

Body:
The problem is that your sample statement generates vcount(g) values - one for every node in your graph. But you are trying to store these values into V(g)$c[V(g)$a <= V(g)$b].  Presumably sometimes not every node has V(g)$a <= V(g)$b so there are fewer spots to store the data.  The simple way to fix this is to generate only the right number of values for the attribute c.  One way to do that would be

V(g)$c[V(g)$a <= V(g)$b] <-
    sample(c(0, 1), sum(V(g)$a <= V(g)$b), replace = TRUE, prob = c(.9, .1))

This is just your original statement except that I have replaced vcount(g) with sum(V(g)$a <= V(g)$b) which counts the number of nodes for which V(g)$a <= V(g)$b .


问:
Can You Get a Transparent Gradient using PHP ImageMagick?
Something to the tune of:

```<code>$gradient->newPseudoImage($width, $height, "gradient:transparent-transparent");
</code>```

Basically I'm looking to create a wet floor effect for uploaded images. So far, it seems you can only create a gradient into a solid color.

答:
The color code for a transparent gradient is "none".

For example, this program saves a gradient from transparent (top) to red (bottom) in a 100x100 pixel PNG image:

```<code>$gradient = new Imagick();
$width = 100;
$height = 100;
$gradient->newPseudoImage($width, $height, 'gradient:none-red');
$gradient->setImageFormat('png');
$gradient->writeImage('test.png');
</code>```

See ImageMagick Canvas documentation for further details on rendering gradients.

ContentLicense: CC BY-SA 2.5

Body:
Something to the tune of:

$gradient->newPseudoImage($width, $height, "gradient:transparent-transparent");

Basically I'm looking to create a wet floor effect for uploaded images. So far, it seems you can only create a gradient into a solid color.

Body:
The color code for a transparent gradient is "none".

For example, this program saves a gradient from transparent (top) to red (bottom) in a 100x100 pixel PNG image:

$gradient = new Imagick();
$width = 100;
$height = 100;
$gradient->newPseudoImage($width, $height, 'gradient:none-red');
$gradient->setImageFormat('png');
$gradient->writeImage('test.png');

See ImageMagick Canvas documentation for further details on rendering gradients.


问:
Need to fire completion block immediately after CloudKit query
I'm stuck on the idea of how to write a CloudKit completion block. My issue is I am loading data, then putting the data in a tableView. The problem is I have to refresh the tableView manually with a button instead of it loading the data to it automatically. What I need is a completion block at the end of my query to reload the table data. Below is my query function:

```<code>func loadGroupPage() {
    print("should go")
    // let pred = NSPredicate(format: "Username = %@", usernameText)
    let pred = NSPredicate(format: "groupName = %@", "\(selectedCellName)")
    let query = CKQuery(recordType: "Group", predicate: pred)
    let operation = CKQueryOperation(query: query)
    //operation.resultsLimit = CKQueryOperationMaximumResults
    operation.recordFetchedBlock = { (record: CKRecord!) in
       operation.qualityOfService = .default

        if record != nil{

            // setup screen after loading data

            self.recordToUpdate = record

            if creatingNewPost == true{
                print(feed)
                //create new post record (modify record)
                feed.append(postText)
                creatingNewPost = false
                self.saveNewPost()
            }

            self.publicOrPrivate = (record.object(forKey: "PublicOrPrivate") as! String)
            if self.publicOrPrivate == "Public"{
                // public
                //print("you have joined")

            }else if self.publicOrPrivate == "Private"{
                // private
                //print("requestSent")
                // self.sendRequest()
                 self.requests = (record.object(forKey: "Requests") as! Array)
            }
            if self.groupMembs.contains(username) || members.contains(username){
                self.joinBtn.alpha = 0
                // in group
            }else{
                self.joinBtn.alpha = 1
            }
            if self.leaders.contains(username) && self.publicOrPrivate == "Private"{
                // leader
                self.requestsTableView.alpha = 1
            }else{
                self.requestsTableView.alpha = 0
            }
            if self.groupMembs.contains(username) || self.publicOrPrivate == "Public"{
                // leader

                feed = (record.object(forKey: "groupFeed") as! Array)
                print(feed)
            }else{

            }
            self.groupMembs = (record.object(forKey: "memberUsernames") as! Array)

            print(self.groupMembs)
            self.numberOfMembersInGroup = self.groupMembs.count
            self.groupNameLbl.text = selectedCellName
            self.numberOfMembersLbl.text = "\(self.numberOfMembersInGroup) Members"
            self.leaders = (record.object(forKey: "leaders") as! Array)

            //****************************************************
            // this does nothing until I refresh it manually!
            self.requestsTableView.reloadData()
            self.groupFeedTableView.reloadData()
            //****************************************************
            //Need completion block so the above two lines will fire directly after data is done loading!
        }

    }
    database.add(operation)
}
</code>```

As I documented in the code above, refreshing the table there will not load anything in the actual UI. Can someone please write a completion block that simply reloads the tableView(s) for me?  Thanks!

答:
UPDATE:

I used the following code to add a completion:

```<code>operation.queryCompletionBlock = { [unowned self] (cursor, error) in
        DispatchQueue.main.async {
            if error == nil {

                self.tableView.reloadData()

            }
        }
    }
</code>```

Works like a charm!

Body:
I'm stuck on the idea of how to write a CloudKit completion block. My issue is I am loading data, then putting the data in a tableView. The problem is I have to refresh the tableView manually with a button instead of it loading the data to it automatically. What I need is a completion block at the end of my query to reload the table data. Below is my query function:

func loadGroupPage() {
    print("should go")
    // let pred = NSPredicate(format: "Username = %@", usernameText)
    let pred = NSPredicate(format: "groupName = %@", "\(selectedCellName)")
    let query = CKQuery(recordType: "Group", predicate: pred)
    let operation = CKQueryOperation(query: query)
    //operation.resultsLimit = CKQueryOperationMaximumResults
    operation.recordFetchedBlock = { (record: CKRecord!) in
       operation.qualityOfService = .default

        if record != nil{

            // setup screen after loading data

            self.recordToUpdate = record

            if creatingNewPost == true{
                print(feed)
                //create new post record (modify record)
                feed.append(postText)
                creatingNewPost = false
                self.saveNewPost()
            }

            self.publicOrPrivate = (record.object(forKey: "PublicOrPrivate") as! String)
            if self.publicOrPrivate == "Public"{
                // public
                //print("you have joined")

            }else if self.publicOrPrivate == "Private"{
                // private
                //print("requestSent")
                // self.sendRequest()
                 self.requests = (record.object(forKey: "Requests") as! Array)
            }
            if self.groupMembs.contains(username) || members.contains(username){
                self.joinBtn.alpha = 0
                // in group
            }else{
                self.joinBtn.alpha = 1
            }
            if self.leaders.contains(username) && self.publicOrPrivate == "Private"{
                // leader
                self.requestsTableView.alpha = 1
            }else{
                self.requestsTableView.alpha = 0
            }
            if self.groupMembs.contains(username) || self.publicOrPrivate == "Public"{
                // leader

                feed = (record.object(forKey: "groupFeed") as! Array)
                print(feed)
            }else{

            }
            self.groupMembs = (record.object(forKey: "memberUsernames") as! Array)

            print(self.groupMembs)
            self.numberOfMembersInGroup = self.groupMembs.count
            self.groupNameLbl.text = selectedCellName
            self.numberOfMembersLbl.text = "\(self.numberOfMembersInGroup) Members"
            self.leaders = (record.object(forKey: "leaders") as! Array)

            //****************************************************
            // this does nothing until I refresh it manually!
            self.requestsTableView.reloadData()
            self.groupFeedTableView.reloadData()
            //****************************************************
            //Need completion block so the above two lines will fire directly after data is done loading!
        }

    }
    database.add(operation)
}

As I documented in the code above, refreshing the table there will not load anything in the actual UI. Can someone please write a completion block that simply reloads the tableView(s) for me?  Thanks!

Body:
UPDATE:

I used the following code to add a completion:

operation.queryCompletionBlock = { [unowned self] (cursor, error) in
        DispatchQueue.main.async {
            if error == nil {

                self.tableView.reloadData()

            }
        }
    }

Works like a charm!


问:
exclude headers on different path
I am running haproxy 1.6.3 and I have the X-Frame-Origin headers set on the frontent. I just come across the situation when the site is loaded in a iframe and the content is blocked because of that header. I have tried to setting an acl rule which looks as the following:

```<code>acl is_embeded path_beg /?embeded=1
http-response set-header x-frame-options "SAMEORIGIN" if !is_embeded
</code>```

when I run haproxy -f /etc/haproxy/haproxy.conf -c I for the following error:

```<code>[WARNING] 316/145915 (23701) : parsing [/etc/haproxy/haproxy.cfg:42] : acl 'is_embeded' will never match because it only involves keywords that are incompatible with 'frontend http-response header rule'
</code>```

Is there a way to get this work?

答:
Because you are using a request acl in response stage.

You need to stroe the url like this:

```<code>http-request set-var(txn.urlEmbeded) url
acl is_embeded var(txn.urlEmbeded) -m beg /?embeded=1
http-response set-header x-frame-options "SAMEORIGIN" if !is_embeded
</code>```

also you are using path, it does not include the query. you might need to use url or query(embeded) with found method. You get the idea.

Title: exclude headers on different path

Body:
I am running haproxy 1.6.3 and I have the X-Frame-Origin headers set on the frontent. I just come across the situation when the site is loaded in a iframe and the content is blocked because of that header. I have tried to setting an acl rule which looks as the following:

acl is_embeded path_beg /?embeded=1
http-response set-header x-frame-options "SAMEORIGIN" if !is_embeded

when I run haproxy -f /etc/haproxy/haproxy.conf -c I for the following error:

[WARNING] 316/145915 (23701) : parsing [/etc/haproxy/haproxy.cfg:42] : acl 'is_embeded' will never match because it only involves keywords that are incompatible with 'frontend http-response header rule'

Is there a way to get this work?

Body:
Because you are using a request acl in response stage.

You need to stroe the url like this:

http-request set-var(txn.urlEmbeded) url
acl is_embeded var(txn.urlEmbeded) -m beg /?embeded=1
http-response set-header x-frame-options "SAMEORIGIN" if !is_embeded

also you are using path, it does not include the query. you might need to use url or query(embeded) with found method. You get the idea.


问:
How to change a Python 3 module to a package without changing the imports?
Is it possible to change a Python module to a package without changing the import statements in other files?

Example: other files in the project use import x, and x is x.py, but I want to move it to something like ./x/x.py without changing the import statements in other files to from x import x.

Even if I use __all__ = ["x"] in __init__.py, it needs from x import x to work.

Is there a way or do I have to update the import statements in the other files?

答:
The cleanest solution to this problem would be having a proper namespace package so your imports won't be implicit ones.

Now, that said, another alternative to achieve what you're asking for would be modifying PYTHONPATH so the imports will be resolved properly, to do this there are basically few ways:

Change PYTHONPATH by hardcoding sys.path or os.environ['PYTHONPATH'] in your python code

Change PYTHONPATH system-wide

Use .pth files on your system-wide python distribution

Use .pth files on your virtualenv

But I strongly discourage these ones, only reason you want to modify PYTHONPATH could happen if you want to import non-installable pypi packages or pointing out to an external package (in this case you got full control over your package) which is not installable (setup.py) and resolved by the current PYTHONPATH.

Although my best advice, follow https://www.python.org/dev/peps/pep-0008/#imports


问:
Netbeans cannot recognize TODO items in .cu file
I am using Netbeans to develop CUDA but it seems that Netbeans cannot recognize the TODO items in .cu file. Is there any way to fix this?

答: Go to Tools > Options > Team > Action Items and add the comment syntax for .cu file.


问:
Async function not behaving as I expect with Jest
The Javascript Jest testing framework documentation says that I need to add done() in my callback to test an asynchronous function, as otherwise the function will return after the test completes and so the test will fail. I have Jest added to my package.json, and the following two files:

src.js:

```<code>function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut butter')
}

module.exports = fetchData
</code>```

src.test.js:

```<code>const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    // no done() method!
  }

  fetchData(callback);
})
</code>```

I get passing tests with the above code, but I think I should get a failing test since I don't have done() in my test file. Is my fetchData() method not asynchronous?

EDIT: Following Nicholas' answer, I changed the code to this:

src.js:

```<code>function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut')
}

module.exports = fetchData
</code>```

src.test.js:

```<code>const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    done()
  }

  fetchData(callback);
})
</code>```

The test runner should evaluate the expectation/assertion per the Jest documentation and fail (peanut being passed, peanut butter expected), but still shows a passing test.

Also, the Jest documentation says:

```<code>If done() is never called, the test will fail, which is what you want to happen
</code>```

The test passes both with and without the done() method in the callback, and both with and without a correct (peanut butter) argument passed to the callback (i.e. all four variants pass).

答:
Your fetchData is asynchronous on its own and Jest has no influence on that. On the other hand, Jest needs to know when a test finishes, which is generally when the test functions exits, but that only covers synchronous code. In your case, when your test function exits, you haven't called any assertions and Jest considers this a success (because there was no failure).

To demonstrate that no assertion was called, I will use expect.assertions(number) to only pass the test if it called exactly number assertions. For example if you set it to 1 in your example:

```<code>test('the data is peanut butter', () => {
  // Require exactly 1 assertion to pass the test
  expect.assertions(1)

  function callback(data) {
    expect(data).toBe('peanut butter')
  }

  fetchData(callback)
})
</code>```

You will see the error message:

```<code>● the data is peanut butter

  expect.assertions(1)

  Expected one assertion to be called but received zero assertion calls.
</code>```

As you can see, no assertion was called. Apart from the demonstration purpose, you could use expect.assertions to make sure your test fails when the assertions weren't called.

For any asynchronous tasks, you need to let Jest know that the test is asynchronous and you need to notify Jest when it finished. One way is with the done callback. When your test function takes one argument (usually called done), Jest will treat it as an asynchronous test and wait until you call the done() callback, or when the timeout threshold is reached (default: 5s). In your edited example your function takes zero arguments, and your call to done() is not Jest's callback.

```<code>test('done callback', done => {
  //                  ^^^^ 1 argument
  // Jest waits until this callback is called or the timeout was reached.
  // ...
})

test('no callback argument', () => {
  //                         ^^ no argument
  // Test finishes as soon as the function exits
  // ...
})
</code>```

This is rarely used anymore, because promises are much more common nowadays and they make this a lot simpler, as you can return the promise and Jest will wait for its completion without any extra setup. Additionally, you can use async and await to make it even nicer, as it's syntactic sugar on top of promises.

See also Testing Asynchronous Code - Promises and Testing Asynchronous Code - Async/Await

Body:
The Javascript Jest testing framework documentation says that I need to add done() in my callback to test an asynchronous function, as otherwise the function will return after the test completes and so the test will fail. I have Jest added to my package.json, and the following two files:

src.js:

function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut butter')
}

module.exports = fetchData

src.test.js:

const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    // no done() method!
  }

  fetchData(callback);
})

I get passing tests with the above code, but I think I should get a failing test since I don't have done() in my test file. Is my fetchData() method not asynchronous?

EDIT: Following Nicholas' answer, I changed the code to this:

src.js:

function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut')
}

module.exports = fetchData

src.test.js:

const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    done()
  }

  fetchData(callback);
})

The test runner should evaluate the expectation/assertion per the Jest documentation and fail (peanut being passed, peanut butter expected), but still shows a passing test.

Also, the Jest documentation says:

If done() is never called, the test will fail, which is what you want to happen

The test passes both with and without the done() method in the callback, and both with and without a correct (peanut butter) argument passed to the callback (i.e. all four variants pass).

Body:
Your fetchData is asynchronous on its own and Jest has no influence on that. On the other hand, Jest needs to know when a test finishes, which is generally when the test functions exits, but that only covers synchronous code. In your case, when your test function exits, you haven't called any assertions and Jest considers this a success (because there was no failure).

To demonstrate that no assertion was called, I will use expect.assertions(number) to only pass the test if it called exactly number assertions. For example if you set it to 1 in your example:

test('the data is peanut butter', () => {
  // Require exactly 1 assertion to pass the test
  expect.assertions(1)

  function callback(data) {
    expect(data).toBe('peanut butter')
  }

  fetchData(callback)
})

You will see the error message:

● the data is peanut butter

  expect.assertions(1)

  Expected one assertion to be called but received zero assertion calls.

As you can see, no assertion was called. Apart from the demonstration purpose, you could use expect.assertions to make sure your test fails when the assertions weren't called.

For any asynchronous tasks, you need to let Jest know that the test is asynchronous and you need to notify Jest when it finished. One way is with the done callback. When your test function takes one argument (usually called done), Jest will treat it as an asynchronous test and wait until you call the done() callback, or when the timeout threshold is reached (default: 5s). In your edited example your function takes zero arguments, and your call to done() is not Jest's callback.

test('done callback', done => {
  //                  ^^^^ 1 argument
  // Jest waits until this callback is called or the timeout was reached.
  // ...
})

test('no callback argument', () => {
  //                         ^^ no argument
  // Test finishes as soon as the function exits
  // ...
})

This is rarely used anymore, because promises are much more common nowadays and they make this a lot simpler, as you can return the promise and Jest will wait for its completion without any extra setup. Additionally, you can use async and await to make it even nicer, as it's syntactic sugar on top of promises.

See also Testing Asynchronous Code - Promises and Testing Asynchronous Code - Async/Await


问:
Integer data type with more that 10 digits
I am using the long type for storing values but it doesn't store a number with more than 10 digits.

Is there any way to make a new integer type with extended memory size (e.g. 12 bytes or more)?

答:
You can write an implementation of arbitrary precision, which will allow you to store as many digits as you want, <s>or use Python</s>. You will have to implement basic arithmetics from scratch, but once you get its point, it won't be too hard.

The standard guarantees long long to be at least 8 bytes long. If you want a 8-byte integer, try this:

```<code>#include <stdint.h>
int64_t a;
uint64_t b; // Unsigned 64-bit int
</code>```

If your compiler complains that it doesn't know what int64_t is, then there's no luck unless you implement an AP.

Body:
You can write an implementation of arbitrary precision, which will allow you to store as many digits as you want, <s>or use Python</s>. You will have to implement basic arithmetics from scratch, but once you get its point, it won't be too hard.

The standard guarantees long long to be at least 8 bytes long. If you want a 8-byte integer, try this:

#include <stdint.h>
int64_t a;
uint64_t b; // Unsigned 64-bit int

If your compiler complains that it doesn't know what int64_t is, then there's no luck unless you implement an AP.


问:
mod_rewrite configuration fails to route to the PHP file that runs Zend Expressive
I am trying to set up Zend Expressive and following this tutorial:
https://zend-expressive.readthedocs.io/en/latest/cookbook/using-a-base-path/

It appears to me that my mod_rewrite directives are not being honored.

How can I ensure that Apache honors directives in my .htaccess file?

答:
Adding this to Apache configuration file and restarting apache service seems to be making it work:</p>

```<code><Directory /var/www/html>
   AllowOverride All
   Require all granted
</Directory>
</code>```

Body:
Adding this to Apache configuration file and restarting apache service seems to be making it work:

<Directory /var/www/html>
   AllowOverride All
   Require all granted
</Directory>


答:
You can use enter https://github.com/cerevra/int/tree/master/v2

It`s a proposal to C++20, but it could be useful with modern c++14 compatible compilers too

Title: Integer data type with more that 10 digits

Body:
I am using the long type for storing values but it doesn't store a number with more than 10 digits.

Is there any way to make a new integer type with extended memory size (e.g. 12 bytes or more)?


问:
Incorrect syntax on icon tag in manifest?
I have been trying to create a chrome extension but when I try and link to the icon files it just says that there is a syntax error in the manifest file (left side of image). I suspect is has something to do with white space because I copied the icon tags from a working extension and changed the file names and it is still not working. Any help would be greatly appreciated.

https://imgur.com/a/s7SOQ

答: You are missing , after your "version_name".


问:
How do I search through process memory for specific string filters (I already have a memory class)
I know how I can search for a specific memory address/offset, i'm just not sure how to search via a string filter and then display all memory addresses which contains the filter.

Using a program like ProcessHacker, I can select a process to read it's memory, then insert a string filter which will display all strings and memory addresses which contains that specific string. (picture example below)

Example:
String Filter = "This is a test"
Now anything which contains the filter (non case sensitive) would be displayed in a listbox along with their memory address, so if there was a string in memory which was "dsfdsff This is a test dsfsdfsdfsd", that string would be displayed along with their memory address.

How would I achieve this?
Here's the memory class that i'm using: https://pastebin.com/ZC9p4B3X
(Post would be too long if I posted it here)

And here's how I can read memory segments using their memory address

[which is what i'm trying to automatically find from the specified filter]

```<code>Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    mem.Setup("name") 'select process name without extension
End Sub

Private Sub BtnReadAddress_Click(sender As Object, e As EventArgs) Handles BtnReadAddress.Click
    TxtBoxMemResult.Text = mem.rdString(TxtBoxMemAddress.Text) 'TxtBoxMemAddress would contain the memory address which I obtained from ProcessHacker
    'This method however only shows part of the string (if possible i'd like the full string to be displayed like in processhacker)
End Sub

End Class
</code>```

Here's a picture of a string I searched for in Explorer.exe
https://gyazo.com/a89bf66e3ea8d737fdda83b784b09aaf

I searched for this is the filter and a file which was named dfsssssssss this is the filter dsffffffffffffff was then displayed with their memory address.

Now I can read the top result from their memory address using the memory class like this (top result was 0x29EAF0A):

```<code> mem.Setup("explorer")
 TxtBoxMemResult.Text = mem.rdString(&H29EAF0A)'Replace 0x with &H
</code>```

Which outputted dfsssssssss th, some of it got cut off after a certain amount of characters.

I searched online before posting, but I could only find posts where you'd have to specifiy the memory address, which is what i'm trying to find automatically from a string filter.

If possible/if anyone's willing, I'd like it to be something like this:

```<code>    Dim Filter As String = "this is a test filter"
    For Each MemoryString As String In ProcessMemory

        If MemoryString.ToLower.Contains(Filter.ToLower) Then
            ListBox1.items.add(MemoryAddressLocation & " - " & MemoryString)
        End If

    Next
</code>```

I would really appreciate it if somebody could help me achieve this.

答:
You may need to change the class definition. Some array's sizes are hardcoded. Here is an example, and you will have to modify the related code:</p>

```<code>Public Shared Function rdString(address As Integer, size as uShort) As String
    Dim buffer As Byte() = New Byte(size ) {}
    ReadProcessMemory(ProcHandle, address, buffer, buffer.Length, 0)
    Return Encoding.Unicode.GetString(buffer).Trim
End Function
</code>```

Body:
I know how I can search for a specific memory address/offset, i'm just not sure how to search via a string filter and then display all memory addresses which contains the filter.

Using a program like ProcessHacker, I can select a process to read it's memory, then insert a string filter which will display all strings and memory addresses which contains that specific string. (picture example below)

Example:
String Filter = "This is a test"
Now anything which contains the filter (non case sensitive) would be displayed in a listbox along with their memory address, so if there was a string in memory which was "dsfdsff This is a test dsfsdfsdfsd", that string would be displayed along with their memory address.

How would I achieve this?
Here's the memory class that i'm using: https://pastebin.com/ZC9p4B3X
(Post would be too long if I posted it here)

And here's how I can read memory segments using their memory address

[which is what i'm trying to automatically find from the specified filter]

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    mem.Setup("name") 'select process name without extension
End Sub

Private Sub BtnReadAddress_Click(sender As Object, e As EventArgs) Handles BtnReadAddress.Click
    TxtBoxMemResult.Text = mem.rdString(TxtBoxMemAddress.Text) 'TxtBoxMemAddress would contain the memory address which I obtained from ProcessHacker
    'This method however only shows part of the string (if possible i'd like the full string to be displayed like in processhacker)
End Sub

End Class

Here's a picture of a string I searched for in Explorer.exe
https://gyazo.com/a89bf66e3ea8d737fdda83b784b09aaf

I searched for this is the filter and a file which was named dfsssssssss this is the filter dsffffffffffffff was then displayed with their memory address.

Now I can read the top result from their memory address using the memory class like this (top result was 0x29EAF0A):

 mem.Setup("explorer")
 TxtBoxMemResult.Text = mem.rdString(&H29EAF0A)'Replace 0x with &H

Which outputted dfsssssssss th, some of it got cut off after a certain amount of characters.

I searched online before posting, but I could only find posts where you'd have to specifiy the memory address, which is what i'm trying to find automatically from a string filter.

If possible/if anyone's willing, I'd like it to be something like this:

    Dim Filter As String = "this is a test filter"
    For Each MemoryString As String In ProcessMemory

        If MemoryString.ToLower.Contains(Filter.ToLower) Then
            ListBox1.items.add(MemoryAddressLocation & " - " & MemoryString)
        End If

    Next

I would really appreciate it if somebody could help me achieve this.

Body:
You may need to change the class definition. Some array's sizes are hardcoded. Here is an example, and you will have to modify the related code:

Public Shared Function rdString(address As Integer, size as uShort) As String
    Dim buffer As Byte() = New Byte(size ) {}
    ReadProcessMemory(ProcHandle, address, buffer, buffer.Length, 0)
    Return Encoding.Unicode.GetString(buffer).Trim
End Function