问:
Update image file in django static files
I'm processing video, then saving each frame as an image in my static folder. Every new image frame overwrites the previous one in the static file directory. The frames come at a pace of 1 per 5 seconds or so.

I want to show the frame images on my html file.

But it isn't working. It keeps loading the version of the image that was used when it compiled.

It only updates when I refresh the page.

How can I avoid this?

This is the code that I'm using in javascript. Every time I get a websocket message, it should update. I get one every 5 seconds.

```<code>socket.onmessage = function(e){

   var recData=JSON.parse(e.data);

   image.setAttribute('src', '../static/frame2.jpg');

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

答:
Your image is being cached by browser ( which is default expected behavior)

To say to your browser not to cache it you could add Cache-Control header like in example, or implement ETag

Bit more hack of a solution (this would fill your browser cache unecessary) would be to add randomized number/datetime in get request

```<code>image.setAttribute('src', '../static/frame2.jpg?' + new Date().getTime());
</code>```

Body:
I'm processing video, then saving each frame as an image in my static folder. Every new image frame overwrites the previous one in the static file directory. The frames come at a pace of 1 per 5 seconds or so.

I want to show the frame images on my html file.

But it isn't working. It keeps loading the version of the image that was used when it compiled.

It only updates when I refresh the page.

How can I avoid this?

This is the code that I'm using in javascript. Every time I get a websocket message, it should update. I get one every 5 seconds.

socket.onmessage = function(e){

   var recData=JSON.parse(e.data);

   image.setAttribute('src', '../static/frame2.jpg');

   (...)

Body:
Your image is being cached by browser ( which is default expected behavior)

To say to your browser not to cache it you could add Cache-Control header like in example, or implement ETag

Bit more hack of a solution (this would fill your browser cache unecessary) would be to add randomized number/datetime in get request

image.setAttribute('src', '../static/frame2.jpg?' + new Date().getTime());


来源: stackexchange

问:
Problem in integration of JSF1.2 & Spring Security
I am implementing spring security in my JSF 1.2 project.This deployed successfully in JBoss 5.0.1 but it gives me following exceptions when I try to access login page of my application

```<code>Caused by: java.lang.IllegalArgumentException: FacesContext must not be null
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.jsf.FacesContextUtils.getWebApplicationContext(FacesContextUtils.java:50)
at org.springframework.web.jsf.FacesContextUtils.getRequiredWebApplicationContext(FacesContextUtils.java:81)
at org.springframework.web.jsf.el.SpringBeanFacesELResolver.getWebApplicationContext(SpringBeanFacesELResolver.java:91)
at org.springframework.web.jsf.el.SpringBeanFacesELResolver.getBeanFactory(SpringBeanFacesELResolver.java:79)
at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:50)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
</code>```

From this trace I am guessing that some how spring beans trying to use faces context before it initializes.

Following is my project structure :

```<code>MyEar
|-- lib\ (contains all spring security jar files)
|
|
|-- myWar
       |-- META-INF/MANIFEST.MF (entries for spring security jars)
       |
       |-- WEB-INF
               |-- applicationContext.xml
               |-- lib\ (local jar files jsf,facelets etc)
</code>```

Here one thing is important to mention is that I want all my spring securities jar in ear's lib directory and this exception is not happening when I put all my spring securities jar directly under ear (earcontent) not in lib.

Please suggest me whether this is the issue with structure of my project of something else?

UPDATE:Here is my manifest content:

```<code>   Manifest-Version: 1.0
   Class-Path: lib/aopalliance-1.0.jar
   lib/mysql-connector-java-5.1.7-bin.jar
   lib/org.springframework.aop-3.0.5.RELEASE.jar
   lib/org.springframework.asm-3.0.5.RELEASE.jar
   lib/org.springframework.beans-3.0.5.RELEASE.jar
   lib/org.springframework.context-3.0.5.RELEASE.jar
   lib/org.springframework.core-3.0.5.RELEASE.jar
   lib/org.springframework.expression-3.0.5.RELEASE.jar
   lib/org.springframework.transaction-3.0.5.RELEASE.jar
   lib/org.springframework.web-3.0.5.RELEASE.jar
   lib/spring-security-config-3.0.5.RELEASE.jar
   lib/spring-security-core-3.0.5.RELEASE.jar
   lib/spring-security-taglibs-3.0.5.RELEASE.jar
   lib/spring-security-web-3.0.5.RELEASE.jar
</code>```

here is some part of web.xml entries:

```<code>        <!--  Delegating to a Spring-managed bean that implements the Filter interface -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetBean</param-name>
        <param-value>filterChainProxy</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

    <servlet>
      <servlet-name>Faces Servlet</servlet-name>
      <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>Faces Servlet</servlet-name>
      <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
</code>```

答:
The FacesContext is created by the FacesServlet. So when it is null, then it means that you didn't invoke the FacesServlet. You need to ensure that the browser request URL matches the <url-pattern> of the FacesServlet as you've definied in your web.xml.

If it is for example

```<code><url-pattern>*.jsf</url-pattern>
</code>```

then you need to ensure that you invoke the login page as

http://localhost:8080/myWar/login.jsf

and thus not as

http://localhost:8080/myWar/login.xhtml

ContentLicense: CC BY-SA 3.0

Body:
I am implementing spring security in my JSF 1.2 project.This deployed successfully in JBoss 5.0.1 but it gives me following exceptions when I try to access login page of my application

Caused by: java.lang.IllegalArgumentException: FacesContext must not be null
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.jsf.FacesContextUtils.getWebApplicationContext(FacesContextUtils.java:50)
at org.springframework.web.jsf.FacesContextUtils.getRequiredWebApplicationContext(FacesContextUtils.java:81)
at org.springframework.web.jsf.el.SpringBeanFacesELResolver.getWebApplicationContext(SpringBeanFacesELResolver.java:91)
at org.springframework.web.jsf.el.SpringBeanFacesELResolver.getBeanFactory(SpringBeanFacesELResolver.java:79)
at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:50)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)

From this trace I am guessing that some how spring beans trying to use faces context before it initializes.

Following is my project structure :

MyEar
|-- lib\ (contains all spring security jar files)
|
|
|-- myWar
       |-- META-INF/MANIFEST.MF (entries for spring security jars)
       |
       |-- WEB-INF
               |-- applicationContext.xml
               |-- lib\ (local jar files jsf,facelets etc)

Here one thing is important to mention is that I want all my spring securities jar in ear's lib directory and this exception is not happening when I put all my spring securities jar directly under ear (earcontent) not in lib.

Please suggest me whether this is the issue with structure of my project of something else?

UPDATE:Here is my manifest content:

   Manifest-Version: 1.0
   Class-Path: lib/aopalliance-1.0.jar
   lib/mysql-connector-java-5.1.7-bin.jar
   lib/org.springframework.aop-3.0.5.RELEASE.jar
   lib/org.springframework.asm-3.0.5.RELEASE.jar
   lib/org.springframework.beans-3.0.5.RELEASE.jar
   lib/org.springframework.context-3.0.5.RELEASE.jar
   lib/org.springframework.core-3.0.5.RELEASE.jar
   lib/org.springframework.expression-3.0.5.RELEASE.jar
   lib/org.springframework.transaction-3.0.5.RELEASE.jar
   lib/org.springframework.web-3.0.5.RELEASE.jar
   lib/spring-security-config-3.0.5.RELEASE.jar
   lib/spring-security-core-3.0.5.RELEASE.jar
   lib/spring-security-taglibs-3.0.5.RELEASE.jar
   lib/spring-security-web-3.0.5.RELEASE.jar

here is some part of web.xml entries:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetBean</param-name>
        <param-value>filterChainProxy</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

    <servlet>
      <servlet-name>Faces Servlet</servlet-name>
      <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>Faces Servlet</servlet-name>
      <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

Body:
The FacesContext is created by the FacesServlet. So when it is null, then it means that you didn't invoke the FacesServlet. You need to ensure that the browser request URL matches the <url-pattern> of the FacesServlet as you've definied in your web.xml.

If it is for example

<url-pattern>*.jsf</url-pattern>

then you need to ensure that you invoke the login page as

http://localhost:8080/myWar/login.jsf

and thus not as

http://localhost:8080/myWar/login.xhtml


问:
Merging multiple arrays into a map
I have some data (sample from full table) that looks like this:

```<code>| prov_id | hotel_id | m_id | apis_xml | company_id | yyyy_mm_dd |
|---------|----------|------|----------|------------|------------|
| 945     | 78888    | 3910 | [5]      | 998        | 2020-05-20 |
| 1475    | 78888    | 6676 | [1,2,4]  | 37         | 2020-05-20 |
| 1475    | 78888    | 6670 | [1,2,4]  | 37         | 2020-05-20 |
| 945     | 78888    | 2617 | [5]      | 998        | 2020-05-20 |
</code>```

I want to find the lowest apis_xml value per hotel and have the associated prov_id set as the "primary_prov". I can do this by merging and sorting the array ascending before taking the first row. I've got a query to this:

```<code>SELECT
    yyyy_mm_dd,
    hotel_id,
    prov_id as primary_prov
FROM(
    SELECT
        yyyy_mm_dd,
        hotel_id,
        prov_id,
        apis_xml,
        ROW_NUMBER() OVER(PARTITION BY yyyy_mm_dd, hotel_id ORDER BY apis_xml) rn
    FROM(
        SELECT
            t.yyyy_mm_dd,
            t.hotel_id,
            t.prov_id,
            t.apis_xml,
            CAST(e.apis_xml AS INT) AS api
        FROM
            my_table t
        LATERAL VIEW EXPLODE(apis_xml) e AS apis_xml
    )s
)s
WHERE rn=1
</code>```

The above query works for getting the primary_prov which maps to the lowest apis_xml value. However, I want to have an extra column which contains the additional xml values for reference. Maybe a map is not the best use case here but it's what comes to mind. The key would be the prov_id while the value would be the apis_xml values. Output would look like this as I need to keep it to one row per hotel_id:

```<code>| hotel_id | primary_prov | detailed_prov            | yyyy_mm_dd |
|----------|--------------|--------------------------|------------|
| 78888    | 1475         | {1475: [1,2,4], 945: [5] | 2020-05-20 |
</code>```

答:
You can build map using brickhouse CollectUDAF. Read instructions how to build JAR, add jar, create function and use it:

```<code>add jar /path/to/jar/brickhouse-0.7.1.jar;
create temporary function collect as 'brickhouse.udf.collect.CollectUDAF';

SELECT yyyy_mm_dd,
       hotel_id,
       primary_prov,
       collect(prov_id, prov_id_api ) as detailed_prov
  FROM
(
SELECT
    yyyy_mm_dd,
    hotel_id,
    max(case when rn=1 then prov_id else null end) over(partition by yyyy_mm_dd, hotel_id) as primary_prov,
    collect_set(api) over (partition by yyyy_mm_dd, hotel_id, prov_id) prov_id_api, --re-assemple array to include all elements from multiple initial arrays if there are different arrays per prov_id
    prov_id
FROM(
    SELECT
        yyyy_mm_dd,
        hotel_id,
        prov_id,
        apis_xml,
        api,
        ROW_NUMBER() OVER(PARTITION BY yyyy_mm_dd, hotel_id ORDER BY api) rn
    FROM(
        SELECT
            t.yyyy_mm_dd,
            t.hotel_id,
            t.prov_id,
            t.apis_xml,
            CAST(e.apis_xml_element AS INT) AS api
        FROM
            my_table t
        LATERAL VIEW EXPLODE(apis_xml) e AS apis_xml_element
    )s
)s
)s
group by yyyy_mm_dd,
         hotel_id,
         primary_prov
</code>```

ContentLicense: CC BY-SA 4.0

Title: Merging multiple arrays into a map

Body:
I have some data (sample from full table) that looks like this:

| prov_id | hotel_id | m_id | apis_xml | company_id | yyyy_mm_dd |
|---------|----------|------|----------|------------|------------|
| 945     | 78888    | 3910 | [5]      | 998        | 2020-05-20 |
| 1475    | 78888    | 6676 | [1,2,4]  | 37         | 2020-05-20 |
| 1475    | 78888    | 6670 | [1,2,4]  | 37         | 2020-05-20 |
| 945     | 78888    | 2617 | [5]      | 998        | 2020-05-20 |

I want to find the lowest apis_xml value per hotel and have the associated prov_id set as the "primary_prov". I can do this by merging and sorting the array ascending before taking the first row. I've got a query to this:

SELECT
    yyyy_mm_dd,
    hotel_id,
    prov_id as primary_prov
FROM(
    SELECT
        yyyy_mm_dd,
        hotel_id,
        prov_id,
        apis_xml,
        ROW_NUMBER() OVER(PARTITION BY yyyy_mm_dd, hotel_id ORDER BY apis_xml) rn
    FROM(
        SELECT
            t.yyyy_mm_dd,
            t.hotel_id,
            t.prov_id,
            t.apis_xml,
            CAST(e.apis_xml AS INT) AS api
        FROM
            my_table t
        LATERAL VIEW EXPLODE(apis_xml) e AS apis_xml
    )s
)s
WHERE rn=1

The above query works for getting the primary_prov which maps to the lowest apis_xml value. However, I want to have an extra column which contains the additional xml values for reference. Maybe a map is not the best use case here but it's what comes to mind. The key would be the prov_id while the value would be the apis_xml values. Output would look like this as I need to keep it to one row per hotel_id:

| hotel_id | primary_prov | detailed_prov            | yyyy_mm_dd |
|----------|--------------|--------------------------|------------|
| 78888    | 1475         | {1475: [1,2,4], 945: [5] | 2020-05-20 |

Body:
You can build map using brickhouse CollectUDAF. Read instructions how to build JAR, add jar, create function and use it:

add jar /path/to/jar/brickhouse-0.7.1.jar;
create temporary function collect as 'brickhouse.udf.collect.CollectUDAF';

SELECT yyyy_mm_dd,
       hotel_id,
       primary_prov,
       collect(prov_id, prov_id_api ) as detailed_prov
  FROM
(
SELECT
    yyyy_mm_dd,
    hotel_id,
    max(case when rn=1 then prov_id else null end) over(partition by yyyy_mm_dd, hotel_id) as primary_prov,
    collect_set(api) over (partition by yyyy_mm_dd, hotel_id, prov_id) prov_id_api, --re-assemple array to include all elements from multiple initial arrays if there are different arrays per prov_id
    prov_id
FROM(
    SELECT
        yyyy_mm_dd,
        hotel_id,
        prov_id,
        apis_xml,
        api,
        ROW_NUMBER() OVER(PARTITION BY yyyy_mm_dd, hotel_id ORDER BY api) rn
    FROM(
        SELECT
            t.yyyy_mm_dd,
            t.hotel_id,
            t.prov_id,
            t.apis_xml,
            CAST(e.apis_xml_element AS INT) AS api
        FROM
            my_table t
        LATERAL VIEW EXPLODE(apis_xml) e AS apis_xml_element
    )s
)s
)s
group by yyyy_mm_dd,
         hotel_id,
         primary_prov


问:
Insert object to specific list index
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

```<code>list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)
</code>```

Output:

```<code>['String1', None, None, 'String2']
</code>```

答:
First of all, please, fix your error with indexing.

```<code>x = 4
</code>```

it is not the 4th element, it is the 5th. So you code and result

```<code>['String1', None, None, 'String2']
</code>```

are not compatible.

And you should keep in mind that linked list is not a C-type array stored as one row in memory. You should initialize the range and values, to construct and use it. Consider as a solution:

```<code>list = ['String1',None,None,None,None]
x = 4
list[x] = 'String2'
#or (where x - the place where to insert, but not the index!):
#list.insert(x, 'String2')

print(list)
</code>```

Of course you can automate it generating it with lambda or "*".

Other way - to use arrays or dicts, not lists, and in your case it sounds as right idea, but you are asking for help namely with the list.

Title: Insert object to specific list index

Body:
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)

Output:

['String1', None, None, 'String2']

Body:
First of all, please, fix your error with indexing.

x = 4

it is not the 4th element, it is the 5th. So you code and result

['String1', None, None, 'String2']

are not compatible.

And you should keep in mind that linked list is not a C-type array stored as one row in memory. You should initialize the range and values, to construct and use it. Consider as a solution:

list = ['String1',None,None,None,None]
x = 4
list[x] = 'String2'
#or (where x - the place where to insert, but not the index!):
#list.insert(x, 'String2')

print(list)

Of course you can automate it generating it with lambda or "*".

Other way - to use arrays or dicts, not lists, and in your case it sounds as right idea, but you are asking for help namely with the list.


问:
Updating fields only if file was modified
I have a JSON file containing some configuration data. Parsing it works all well, but I am trying to achieve a live update of the configuration. Thus, I set a scheduler to do the task every few seconds, and it works all well either. However, if no modification was made to the configuration since the latest parsing, I want to avoid the overhead of parsing the file once again.

I have written the following code to achieve that, however the field variable timestamp remains at zero despite this.timestamp = latestTimestamp; is executed while latestTimestamp holds the latest timestamp. I am confused now as it makes absolutely no sense to me. What am I missing here?

@NonNull private String configFilePath;
@Getter private JSONObject configuration;
private long timestamp = 0;

  /**
   * update the fields
   * @throws IOException if an error occurred while opening / reading the file
   * @throws ParseException if an error occurred parsing the JSON file
   */
  public void update() throws IOException, ParseException {
    long latestTimestamp = getLatestTimestamp(this.configFilePath);
    if (this.timestamp == latestTimestamp)
      return;

    this.configuration = this.parse(this.configFilePath);
    this.timestamp = latestTimestamp;
    // the above condition results in `false` when called again despite file is not modified
    // because this.timestamp somehow remains 0
  }
```

The above code is a simplified version. The complete Class can be found here.

答: So I think "the field variable timestamp remains at zero" is only possible if your scheduler is creating a new object of your class JSONUpdater, which resets the timestamp variable to 0 again. Try making it Singleton.

Body:
I have a JSON file containing some configuration data. Parsing it works all well, but I am trying to achieve a live update of the configuration. Thus, I set a scheduler to do the task every few seconds, and it works all well either. However, if no modification was made to the configuration since the latest parsing, I want to avoid the overhead of parsing the file once again.

I have written the following code to achieve that, however the field variable timestamp remains at zero despite this.timestamp = latestTimestamp; is executed while latestTimestamp holds the latest timestamp. I am confused now as it makes absolutely no sense to me. What am I missing here?

@NonNull private String configFilePath;
@Getter private JSONObject configuration;
private long timestamp = 0;

  /**
   * update the fields
   * @throws IOException if an error occurred while opening / reading the file
   * @throws ParseException if an error occurred parsing the JSON file
   */
  public void update() throws IOException, ParseException {
    long latestTimestamp = getLatestTimestamp(this.configFilePath);
    if (this.timestamp == latestTimestamp)
      return;

    this.configuration = this.parse(this.configFilePath);
    this.timestamp = latestTimestamp;
    // the above condition results in `false` when called again despite file is not modified
    // because this.timestamp somehow remains 0
  }

The above code is a simplified version. The complete Class can be found here.


问:
add an attachment in Xero using php Xero api
Can anyone help me add a pdf to a Xero Invoice using the official (non calcanai) PHP SDK. I'm connected with oAuth2 and have previously created a draft invoice.

I then update the invoice to Authorised and try to add an attachment to the invoice. At this point I am not getting any luck, the attachments is sent but comes back in the respose as null. The docs are not at all useful and do not give any examples of adding an attachment or even minimal fields. So this is what I have:

```<code>...
        $attachments = $apiResponse->getInvoices()[0]->getAttachments();
        $attachment = new XeroAPI\XeroPHP\Models\Accounting\Attachment;
        $attachment->setFileName( $filename )
            ->setIncludeOnline( true )
            ->setMimeType( 'application/pdf' );
        $attachments[] = $attachment;
        $apiResponse->getInvoices()[0]->setAttachments( $attachments );
        $apiResult = $accountingApi->updateOrCreateInvoices( $xeroTenantId, $apiAuth );
            if ( !$apiResult->getInvoices()[0]->getHasAttachments() ) {
                $errors[] = 'Pdf file was not added to Xero.';
            }
            $errorList = array();
            $errList = $apiResult->getInvoices()[0]->getValidationErrors()[0];
            if ( !is_null( $errList ) ) {
                $errorList = $errList;
            }
            foreach ( $errorList as $err ) {
                $errors[] = $err->getMessage();
            }
            if ( count( $errors ) == 0 ) {
                $result['message'] = 'New Invoice Authorised: ' . $xeroInvoice->getReference();
                $result['apiResult'] = $apiResult;
                $result['success'] = true;
            } else {
                $result['message'] = print_r( $errors );
                $result['success'] = false;
            }
...
</code>```

any ideas?

thanks

* CODE AFTER *

```<code>public function attachPDF( $xeroTenantId, $accountingApi, $invoice ) {
        $filename = 'AUTH#' . sprintf( '%08d', $invoice->id ) . '.pdf';
        $guid     = $invoice->invoice_id;
        $content  = $invoice->getPDF( \Mpdf\Output\Destination::FILE, true, $filename );
        $handle = fopen( $filename, "r" );
        $contents = fread( $handle, filesize( $filename ) );
        fclose( $handle );
        unlink( $filename );
        return $accountingApi->createInvoiceAttachmentByFileName( $xeroTenantId, $guid, $filename, $contents, true );
    }
</code>```

答:
Adding an attachment requires two API calls.

// Create or Get your Invoice ID, then create Attachment

```<code>    $invoices = $apiInstance->getInvoices($xeroTenantId);
    $guid = $invoices->getInvoices()[0]->getInvoiceId();

    // file in the same dir.
    $filename = "./helo-heros.jpg";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);

    $result = $apiInstance->createInvoiceAttachmentByFileName($xeroTenantId,$guid,"helo-heros.jpg",$contents);

</code>```

Body:
Can anyone help me add a pdf to a Xero Invoice using the official (non calcanai) PHP SDK. I'm connected with oAuth2 and have previously created a draft invoice.

I then update the invoice to Authorised and try to add an attachment to the invoice. At this point I am not getting any luck, the attachments is sent but comes back in the respose as null. The docs are not at all useful and do not give any examples of adding an attachment or even minimal fields. So this is what I have:

...
        $attachments = $apiResponse->getInvoices()[0]->getAttachments();
        $attachment = new XeroAPI\XeroPHP\Models\Accounting\Attachment;
        $attachment->setFileName( $filename )
            ->setIncludeOnline( true )
            ->setMimeType( 'application/pdf' );
        $attachments[] = $attachment;
        $apiResponse->getInvoices()[0]->setAttachments( $attachments );
        $apiResult = $accountingApi->updateOrCreateInvoices( $xeroTenantId, $apiAuth );
            if ( !$apiResult->getInvoices()[0]->getHasAttachments() ) {
                $errors[] = 'Pdf file was not added to Xero.';
            }
            $errorList = array();
            $errList = $apiResult->getInvoices()[0]->getValidationErrors()[0];
            if ( !is_null( $errList ) ) {
                $errorList = $errList;
            }
            foreach ( $errorList as $err ) {
                $errors[] = $err->getMessage();
            }
            if ( count( $errors ) == 0 ) {
                $result['message'] = 'New Invoice Authorised: ' . $xeroInvoice->getReference();
                $result['apiResult'] = $apiResult;
                $result['success'] = true;
            } else {
                $result['message'] = print_r( $errors );
                $result['success'] = false;
            }
...

any ideas?

thanks

* CODE AFTER *

public function attachPDF( $xeroTenantId, $accountingApi, $invoice ) {
        $filename = 'AUTH#' . sprintf( '%08d', $invoice->id ) . '.pdf';
        $guid     = $invoice->invoice_id;
        $content  = $invoice->getPDF( \Mpdf\Output\Destination::FILE, true, $filename );
        $handle = fopen( $filename, "r" );
        $contents = fread( $handle, filesize( $filename ) );
        fclose( $handle );
        unlink( $filename );
        return $accountingApi->createInvoiceAttachmentByFileName( $xeroTenantId, $guid, $filename, $contents, true );
    }

Body:
Adding an attachment requires two API calls.

// Create or Get your Invoice ID, then create Attachment

    $invoices = $apiInstance->getInvoices($xeroTenantId);
    $guid = $invoices->getInvoices()[0]->getInvoiceId();

    // file in the same dir.
    $filename = "./helo-heros.jpg";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);

    $result = $apiInstance->createInvoiceAttachmentByFileName($xeroTenantId,$guid,"helo-heros.jpg",$contents);


问:
$_POST undefined from remote server POST
I am writing a Drupal 7 module which is listening for HTTP POST messages to be sent by a 3rd party remote application. For testing I am sending messages using the Firefox Poster extension.

If I POST the message, the following code fails to place any value in my local vars (I get 'undefined index'):

```<code>$transId = urldecode($_POST['c2s_transaction_id']);
</code>```

However, if I send the message using GET, the vars get populated fine with the following code:

```<code>$transId = urldecode($_REQUEST['c2s_transaction_id']);
</code>```

This is true on both my local WAMP setup and on a shared hosting package.

I have never worked with HTTP POST messages before and have no idea where the problem might be. Could it be Drupal, the web server, or my code? Can anyone suggest how I might resolve this?

Many thanks,

Polly

答: Drupal removes the $_POST/$_GET in the system, just use $_REQUEST instead.</p>

Body:
I am writing a Drupal 7 module which is listening for HTTP POST messages to be sent by a 3rd party remote application. For testing I am sending messages using the Firefox Poster extension.

If I POST the message, the following code fails to place any value in my local vars (I get 'undefined index'):

$transId = urldecode($_POST['c2s_transaction_id']);

However, if I send the message using GET, the vars get populated fine with the following code:

$transId = urldecode($_REQUEST['c2s_transaction_id']);

This is true on both my local WAMP setup and on a shared hosting package.

I have never worked with HTTP POST messages before and have no idea where the problem might be. Could it be Drupal, the web server, or my code? Can anyone suggest how I might resolve this?

Many thanks,

Polly


问:
Outlook add in On-Send event is firing
Im trying to get a simple function to append some data to the mail body using the on-send function.

in my manifest file, I have this setting the extension point

```<code><ExtensionPoint xsi:type="Events">
    <Event Type="ItemSend" FunctionExecution="synchronous" FunctionName="setItemBody" />
</ExtensionPoint>
</code>```

my javascript is taken from https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/outlook-on-send-addins?tabs=windows

```<code>function validateBody(event) {
    console.log('validateBody');
    item.body.getAsync("html", { asyncContext: event }, checkBodyOnlyOnSendCallBack);
}

// <param name="asyncResult">MessageSend event passed from the calling function.</param>
function checkBodyOnlyOnSendCallBack(asyncResult) {
    var listOfBlockedWords = new Array("blockedword", "blockedword1", "blockedword2");
    var wordExpression = listOfBlockedWords.join('|');

    // \b to perform a "whole words only" search using a regular expression in the form of \bword\b.
    // i to perform case-insensitive search.
    var regexCheck = new RegExp('\\b(' + wordExpression + ')\\b', 'i');
    var checkBody = regexCheck.test(asyncResult.value);

    if (checkBody) {
        mailboxItem.notificationMessages.addAsync('NoSend', { type: 'errorMessage', message: 'Blocked words have been found in the body of this email. Please remove them.' });
        // Block send.
        asyncResult.asyncContext.completed({ allowEvent: false });
    }

    // Allow send.
    asyncResult.asyncContext.completed({ allowEvent: true });
}

</code>```

But when i hit send on the email i just keep getting 'The add-in has prevented this item from being sent.'

and looking in the browser debugger i cannot see that it has written out the console.log in the validateBody event.

Any body any ideas what I have done wrong?

答:
As an update to this, as I have now solved it, its due to where the called function (in my case setItemBody) resides in your Function.js (or what ever is set as your function file)

The method being called by the ItemSend needs to be at the very root, even before the Office.initialize function. This at least solved it for me as I found it by reading this article https://theofficecontext.com/2017/06/12/the-most-anticipated-officejs-feature-is-here/

Title: Outlook add in On-Send event is firing

Body:
Im trying to get a simple function to append some data to the mail body using the on-send function.

in my manifest file, I have this setting the extension point

<ExtensionPoint xsi:type="Events">
    <Event Type="ItemSend" FunctionExecution="synchronous" FunctionName="setItemBody" />
</ExtensionPoint>

my javascript is taken from https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/outlook-on-send-addins?tabs=windows

function validateBody(event) {
    console.log('validateBody');
    item.body.getAsync("html", { asyncContext: event }, checkBodyOnlyOnSendCallBack);
}

// <param name="asyncResult">MessageSend event passed from the calling function.</param>
function checkBodyOnlyOnSendCallBack(asyncResult) {
    var listOfBlockedWords = new Array("blockedword", "blockedword1", "blockedword2");
    var wordExpression = listOfBlockedWords.join('|');

    // \b to perform a "whole words only" search using a regular expression in the form of \bword\b.
    // i to perform case-insensitive search.
    var regexCheck = new RegExp('\\b(' + wordExpression + ')\\b', 'i');
    var checkBody = regexCheck.test(asyncResult.value);

    if (checkBody) {
        mailboxItem.notificationMessages.addAsync('NoSend', { type: 'errorMessage', message: 'Blocked words have been found in the body of this email. Please remove them.' });
        // Block send.
        asyncResult.asyncContext.completed({ allowEvent: false });
    }

    // Allow send.
    asyncResult.asyncContext.completed({ allowEvent: true });
}

But when i hit send on the email i just keep getting 'The add-in has prevented this item from being sent.'

and looking in the browser debugger i cannot see that it has written out the console.log in the validateBody event.

Any body any ideas what I have done wrong?


问:
How to compare text password to password that is hashed using spring data jpa?
I have password which is hashed in database while saving it. But I am now implementing login module and not able to compare two passwords in spring [boot] data jpa. This is trying comparing text password that I enter to the password that is hashed in database which obviously fails.

I know this has been answered here using java  for general case but not for spring boot.

I somehow need to manipulate logic in this code

```<code>@Override
public boolean getLoggedinUser(User user) {

    String uname = user.getUsername();
    String email = user.getEmail();
    String password = user.getPassword();

    System.out.println("sanity check username----- " + uname  +
            " password ------- " + password);

    if ((userRepo.findByUsername(uname) != null && userRepo.findByPassword(password) != null)
            || (userRepo.findByPassword(password) != null && userRepo.findByEmail(email) != null)) {

        return true;
    }
    else return false;
}
</code>```

Now, how to compare them ? Any solution is appreciated.

答:
I'm using this as an out of the box solution it's all managed by spring</p>

```<code>@RestController
@RequestMapping("/api")
public class UserJWTController {

private final AuthenticationManagerBuilder authenticationManagerBuilder;

public UserJWTController( AuthenticationManagerBuilder authenticationManagerBuilder,
....other dependancies) {
    //other dependancies
    this.authenticationManagerBuilder = authenticationManagerBuilder;
}

@PostMapping("/authenticate")
public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {

    String authenticateWith = loginVM.getEmail()==null?
  loginVM.getUsername():loginVM.getEmail();
    if(authenticateWith==null||authenticateWith.trim().isEmpty()) {
        return ResponseEntity.badRequest().build();
    }

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(authenticateWith.toLowerCase(),
   loginVM.getPassword());

    Authentication authentication =
  authenticationManagerBuilder.getObject().authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
</code>```

Body:
I have password which is hashed in database while saving it. But I am now implementing login module and not able to compare two passwords in spring [boot] data jpa. This is trying comparing text password that I enter to the password that is hashed in database which obviously fails.

I know this has been answered here using java  for general case but not for spring boot.

I somehow need to manipulate logic in this code

@Override
public boolean getLoggedinUser(User user) {

    String uname = user.getUsername();
    String email = user.getEmail();
    String password = user.getPassword();

    System.out.println("sanity check username----- " + uname  +
            " password ------- " + password);

    if ((userRepo.findByUsername(uname) != null && userRepo.findByPassword(password) != null)
            || (userRepo.findByPassword(password) != null && userRepo.findByEmail(email) != null)) {

        return true;
    }
    else return false;
}

Now, how to compare them ? Any solution is appreciated.

Body:
I'm using this as an out of the box solution it's all managed by spring

@RestController
@RequestMapping("/api")
public class UserJWTController {

private final AuthenticationManagerBuilder authenticationManagerBuilder;

public UserJWTController( AuthenticationManagerBuilder authenticationManagerBuilder,
....other dependancies) {
    //other dependancies
    this.authenticationManagerBuilder = authenticationManagerBuilder;
}

@PostMapping("/authenticate")
public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {

    String authenticateWith = loginVM.getEmail()==null?
  loginVM.getUsername():loginVM.getEmail();
    if(authenticateWith==null||authenticateWith.trim().isEmpty()) {
        return ResponseEntity.badRequest().build();
    }

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(authenticateWith.toLowerCase(),
   loginVM.getPassword());

    Authentication authentication =
  authenticationManagerBuilder.getObject().authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);


问:
How do I optimize a "latest sales" sql query?
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

```<code>create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)
</code>```

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

```<code>select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId
</code>```

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

```<code>create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)
</code>```

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
</code>```

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId
</code>```

or

```<code>select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1
</code>```

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

```<code>select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId
</code>```

I tested this idea but the query optimizer still chooses to do a full table scan.

答:
"
      create unique nonclustered index IX_Sales on Sales
      (
        SalesmanId asc,
        SaleId asc
      )

Now it should be trivial (for a human,
  anyway) to find the most recent values
  because we use the values of the first
  column of the index to identify all
  possible salesmen and the last entries
  of the second column to locate each
  salesman's latest sale. Unfortunately,
  the query optimizer still does an
  index seek over the entire index (all
  10^100 rows) in this case, so it takes
  just as long."

Of course, but I bet you the computer still does it faster than a human being could.

Anyway, consider this other index declaration:

```<code>create unique nonclustered index IX_Sales on Sales
    (
      SalesmanId asc,
      SaleId DESC
    )
</code>```

Now the MAX(SaleId) is the first row in the index for each Salesman.  That should be a lot faster. You may think devoting an entire index to solving one query is pretty extravagant but defeating one's nemesis sometimes requires desperate measures!

I say solving just one query because this index won't help with those other queries you mention in a comment:

"What is the latest sale per salesman
  for amounts greater than $1,000?" or
  "What is the latest sale per salesman
  for each of the last 12 months?"

Alas, you cannot have a single solution to all your date-related queries on such a huge table.  Solving these things is the reason why organisations build data warehouses, with baroque structures called dimensions and fact tables, and big grunt servers which can run queries in parallel.

Body:
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

select max(SaleId)
from Sales
where SalesmanId = 1

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId

or

select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId

I tested this idea but the query optimizer still chooses to do a full table scan.

Body:
"
      create unique nonclustered index IX_Sales on Sales
      (
        SalesmanId asc,
        SaleId asc
      )

Now it should be trivial (for a human,
  anyway) to find the most recent values
  because we use the values of the first
  column of the index to identify all
  possible salesmen and the last entries
  of the second column to locate each
  salesman's latest sale. Unfortunately,
  the query optimizer still does an
  index seek over the entire index (all
  10^100 rows) in this case, so it takes
  just as long."

Of course, but I bet you the computer still does it faster than a human being could.

Anyway, consider this other index declaration:

create unique nonclustered index IX_Sales on Sales
    (
      SalesmanId asc,
      SaleId DESC
    )

Now the MAX(SaleId) is the first row in the index for each Salesman.  That should be a lot faster. You may think devoting an entire index to solving one query is pretty extravagant but defeating one's nemesis sometimes requires desperate measures!

I say solving just one query because this index won't help with those other queries you mention in a comment:

"What is the latest sale per salesman
  for amounts greater than $1,000?" or
  "What is the latest sale per salesman
  for each of the last 12 months?"

Alas, you cannot have a single solution to all your date-related queries on such a huge table.  Solving these things is the reason why organisations build data warehouses, with baroque structures called dimensions and fact tables, and big grunt servers which can run queries in parallel.


问:
How to reinitialize ExoPlayer after releasing?
I have ExoPlayerWrapper class which is wrapper for ExoPlayer and is singleton injected by Dagger. Init block in ExoPlayerWrapper class looks in the following way:

```<code>@Singleton
class ExoPlayerWrapper @Inject constructor(
    context: Context,
    userAgentInfo: UserAgentInfo
) {
    private val exoPlayer: ExoPlayer
    private val httpDataSource: HttpDataSource
    private val mediaSourceFactory: ExtractorMediaSource.Factory

    override val exoPlayerInstance: ExoPlayer
        get() = exoPlayer

   init {
        ...
        exoPlayer = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector)
        httpDataSource = CustomHttpDataSource(userAgentInfo.userAgent, null)
        mediaSourceFactory = ExtractorMediaSource.Factory { httpDataSource }
        state = Player.STATE_IDLE
    }

   override fun playFromUrl(uri: Uri, headers: Map<String, String>) {
        reset()
        ...
        val mediaSource = mediaSourceFactory.createMediaSource(uri)
        exoPlayer.prepare(mediaSource)
        exoPlayer.playWhenReady = true
    }

    override fun pause() {
        exoPlayer.playWhenReady = false
    }

    override fun reset() {
       stop()
       state = Player.STATE_IDLE
    }

    override fun stop() {
       exoPlayer.stop()
       exoPlayer.seekTo(0)
    }

    override fun seekTo(position: Long) {
       exoPlayer.seekTo(position)
    }

    ...

    override fun release() {
        exoPlayer.release()
        state = Player.STATE_RELEASED
    }
</code>```

And in onCreate() method of Activity I have the following code:

```<code>public override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_video_player)
    ...
    if (savedInstanceState != null) {
        initialized = savedInstanceState.getBoolean(INITIALIZED)
    }
    if (!initialized) {
        val uri = Uri.parse(attachedVideo?.uri)
        player.playFromUrl(uri, sessionStore.sessionHeaders)
        videoView.requestFocus()
        initialized = true
    }

    videoView.player = player.exoPlayerInstance

    backBtn.setOnClickListener{ _ ->
        player.release()
        finish()
    }
}
</code>```

But in this case I can play only one video after click on backBtn button, other videos after that aren't played until I close app and reopen app again. And if I change backBtn's OnClickListener in the following way:

```<code>backBtn.setOnClickListener{ _ ->
    player.pause()
    finish()
}
</code>```

all works fine, other videos are played after click on backBtn button. So it seems to be problem with reinitializing ExoPlayer after release() method invocation. And how correctly to reinitialize ExoPlayer after releasing?

UPD
And after release() invocation and after attempt to open video again I see the following error in Logcat:

```<code>java.lang.IllegalStateException: Handler (android.os.Handler) {81fa8ef} sending message to a Handler on a dead thread
    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:545)
    at android.os.Handler.enqueueMessage(Handler.java:661)
    at android.os.Handler.sendMessageAtTime(Handler.java:630)
    at android.os.Handler.sendMessageDelayed(Handler.java:600)
    at android.os.Handler.sendMessage(Handler.java:537)
    at android.os.Message.sendToTarget(Message.java:418)
    at com.google.android.exoplayer2.ExoPlayerImplInternal.stop(ExoPlayerImplInternal.java:207)
    at com.google.android.exoplayer2.ExoPlayerImpl.stop(ExoPlayerImpl.java:357)
    at com.google.android.exoplayer2.SimpleExoPlayer.stop(SimpleExoPlayer.java:777)
    at com.google.android.exoplayer2.SimpleExoPlayer.stop(SimpleExoPlayer.java:772)
    at package.ExoPlayerWrapper.stop(ExoPlayerWrapper.kt:xx)
    at package.ExoPlayerWrapper.reset(ExoPlayerWrapper.kt:xx)
    at package.ExoPlayerWrapper.playFromUrl(ExoPlayerWrapper.kt:xx)
    at package.VideoPlayerActivity.onCreate(VideoPlayerActivity.kt:xx)
</code>```

答:
The issue arises from trying to use a player whose resources have already been released. Because:

```<code>exoPlayer = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector)
</code>```

only gets called once, during the initialization of ExoPlayerWrapper. If your activity is not restarted, then that instance of ExoPlayerWrapper sticks around with the released player.

Either create a new instance of ExoPlayerWrapper whenever you go to play your video, or create a player initialization method inside ExoPlayerWrapper, which you can call just before playing the video.

Body:
I have ExoPlayerWrapper class which is wrapper for ExoPlayer and is singleton injected by Dagger. Init block in ExoPlayerWrapper class looks in the following way:

@Singleton
class ExoPlayerWrapper @Inject constructor(
    context: Context,
    userAgentInfo: UserAgentInfo
) {
    private val exoPlayer: ExoPlayer
    private val httpDataSource: HttpDataSource
    private val mediaSourceFactory: ExtractorMediaSource.Factory

    override val exoPlayerInstance: ExoPlayer
        get() = exoPlayer

   init {
        ...
        exoPlayer = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector)
        httpDataSource = CustomHttpDataSource(userAgentInfo.userAgent, null)
        mediaSourceFactory = ExtractorMediaSource.Factory { httpDataSource }
        state = Player.STATE_IDLE
    }

   override fun playFromUrl(uri: Uri, headers: Map<String, String>) {
        reset()
        ...
        val mediaSource = mediaSourceFactory.createMediaSource(uri)
        exoPlayer.prepare(mediaSource)
        exoPlayer.playWhenReady = true
    }

    override fun pause() {
        exoPlayer.playWhenReady = false
    }

    override fun reset() {
       stop()
       state = Player.STATE_IDLE
    }

    override fun stop() {
       exoPlayer.stop()
       exoPlayer.seekTo(0)
    }

    override fun seekTo(position: Long) {
       exoPlayer.seekTo(position)
    }

    ...

    override fun release() {
        exoPlayer.release()
        state = Player.STATE_RELEASED
    }

And in onCreate() method of Activity I have the following code:

public override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_video_player)
    ...
    if (savedInstanceState != null) {
        initialized = savedInstanceState.getBoolean(INITIALIZED)
    }
    if (!initialized) {
        val uri = Uri.parse(attachedVideo?.uri)
        player.playFromUrl(uri, sessionStore.sessionHeaders)
        videoView.requestFocus()
        initialized = true
    }

    videoView.player = player.exoPlayerInstance

    backBtn.setOnClickListener{ _ ->
        player.release()
        finish()
    }
}

But in this case I can play only one video after click on backBtn button, other videos after that aren't played until I close app and reopen app again. And if I change backBtn's OnClickListener in the following way:

backBtn.setOnClickListener{ _ ->
    player.pause()
    finish()
}

all works fine, other videos are played after click on backBtn button. So it seems to be problem with reinitializing ExoPlayer after release() method invocation. And how correctly to reinitialize ExoPlayer after releasing?

UPD
And after release() invocation and after attempt to open video again I see the following error in Logcat:

java.lang.IllegalStateException: Handler (android.os.Handler) {81fa8ef} sending message to a Handler on a dead thread
    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:545)
    at android.os.Handler.enqueueMessage(Handler.java:661)
    at android.os.Handler.sendMessageAtTime(Handler.java:630)
    at android.os.Handler.sendMessageDelayed(Handler.java:600)
    at android.os.Handler.sendMessage(Handler.java:537)
    at android.os.Message.sendToTarget(Message.java:418)
    at com.google.android.exoplayer2.ExoPlayerImplInternal.stop(ExoPlayerImplInternal.java:207)
    at com.google.android.exoplayer2.ExoPlayerImpl.stop(ExoPlayerImpl.java:357)
    at com.google.android.exoplayer2.SimpleExoPlayer.stop(SimpleExoPlayer.java:777)
    at com.google.android.exoplayer2.SimpleExoPlayer.stop(SimpleExoPlayer.java:772)
    at package.ExoPlayerWrapper.stop(ExoPlayerWrapper.kt:xx)
    at package.ExoPlayerWrapper.reset(ExoPlayerWrapper.kt:xx)
    at package.ExoPlayerWrapper.playFromUrl(ExoPlayerWrapper.kt:xx)
    at package.VideoPlayerActivity.onCreate(VideoPlayerActivity.kt:xx)

Body:
The issue arises from trying to use a player whose resources have already been released. Because:

exoPlayer = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector)

only gets called once, during the initialization of ExoPlayerWrapper. If your activity is not restarted, then that instance of ExoPlayerWrapper sticks around with the released player.

Either create a new instance of ExoPlayerWrapper whenever you go to play your video, or create a player initialization method inside ExoPlayerWrapper, which you can call just before playing the video.


问:
Comparison operator problem, when template variable is zero
On a content.php page I have the following:

```<code>$html_videos = '';
if (!empty($videos)) {
    foreach ($videos as $key => $video) {
        $video = PT_GetVideoByID($video, 0, 0, 0);
        $html_videos .= PT_LoadPage('videos/list', array(
            'SELL_VIDEO' => $video->sell_video,
            'RENT_PRICE' => $video->rent_price
        ));
    }
}
</code>```

On the list.html page that it loads, I have

```<code>            <?php $affitta = '{{RENT_PRICE}}'; echo $affitta; if (!empty($affitta) && $affitta !== 0) { ?><span class="bold">|</span> {{LANG rent}} <span style='color:#a84849;font-weight:500;'>$ {{RENT_PRICE}}</span><?php } else { echo "FREE"; } ?>
</code>```

{{LANG rent}} equals to "Rent"

Var $affitta echoes fine all the times; however, be it 0 or 5 it always returns the span, hence "Rent $affitta value" while instead when $affitta equals zero I want it to return "FREE".

I have tried to use && $affitta !== '0' with quotes but same behavior.
If it may help, column in database is integer and default value is 0. So, what I'm trying to do is to show FREE if RENT_PRICE ($affitta) is zero or rent price if different than zero, but no matter what I try I can never get it to recognize $affitta as zero, although the echo shows that it is zero.

I have extensively searched for an answer and tried various other suggested solution, but with no success.

I hope I have been clear and if not, please, let me know and allow me to clarify. What is it that I'm doing wrong?

答:
Your life would be easier if, with the last line of code there (in list.html), you didn't jump in and out of PHP over and over. This line:

```<code><?php $affitta = '{{RENT_PRICE}}'; echo $affitta; if (!empty($affitta) && $affitta !== 0) { ?><span class="bold">|</span> {{LANG rent}} <span style='color:#a84849;font-weight:500;'>$ {{RENT_PRICE}}</span><?php } else { echo "FREE"; } ?>
</code>```

Is simply this:

```<code><?php
$affitta = '{{RENT_PRICE}}';
echo $affitta;
if (!empty($affitta) && $affitta !== 0) {
    echo '<span class="bold">|</span> {{LANG rent}} <span style="color:#a84849;font-weight:500;">$ {{RENT_PRICE}}</span>';
} else {
    echo "FREE";
}
</code>```

Then, with something more readable, it's very easy to see where your problem lies. You define the value of $affitta as '{{RENT_PRICE}}', which obviously doesn't equal 0 or whatever the price may be. Your templating system will substitute {{RENT_PRICE}} with the actual value, but here it's not a number. You are in fact evaluating: if ('{{RENT_PRICE}}' !== 0) {...

You need to instead compare with the value in $video->rent_price earlier up your code. How you access that value depends entirely on what's happening inside your PT_LoadPage function.

Body:
On a content.php page I have the following:

$html_videos = '';
if (!empty($videos)) {
    foreach ($videos as $key => $video) {
        $video = PT_GetVideoByID($video, 0, 0, 0);
        $html_videos .= PT_LoadPage('videos/list', array(
            'SELL_VIDEO' => $video->sell_video,
            'RENT_PRICE' => $video->rent_price
        ));
    }
}

On the list.html page that it loads, I have

            <?php $affitta = '{{RENT_PRICE}}'; echo $affitta; if (!empty($affitta) && $affitta !== 0) { ?>| {{LANG rent}} $ {{RENT_PRICE}}<?php } else { echo "FREE"; } ?>

{{LANG rent}} equals to "Rent"

Var $affitta echoes fine all the times; however, be it 0 or 5 it always returns the span, hence "Rent $affitta value" while instead when $affitta equals zero I want it to return "FREE".

I have tried to use && $affitta !== '0' with quotes but same behavior.
If it may help, column in database is integer and default value is 0. So, what I'm trying to do is to show FREE if RENT_PRICE ($affitta) is zero or rent price if different than zero, but no matter what I try I can never get it to recognize $affitta as zero, although the echo shows that it is zero.

I have extensively searched for an answer and tried various other suggested solution, but with no success.

I hope I have been clear and if not, please, let me know and allow me to clarify. What is it that I'm doing wrong?

Body:
Your life would be easier if, with the last line of code there (in list.html), you didn't jump in and out of PHP over and over. This line:

<?php $affitta = '{{RENT_PRICE}}'; echo $affitta; if (!empty($affitta) && $affitta !== 0) { ?><span class="bold">|</span> {{LANG rent}} <span style='color:#a84849;font-weight:500;'>$ {{RENT_PRICE}}</span><?php } else { echo "FREE"; } ?>

Is simply this:

<?php
$affitta = '{{RENT_PRICE}}';
echo $affitta;
if (!empty($affitta) && $affitta !== 0) {
    echo '<span class="bold">|</span> {{LANG rent}} <span style="color:#a84849;font-weight:500;">$ {{RENT_PRICE}}</span>';
} else {
    echo "FREE";
}

Then, with something more readable, it's very easy to see where your problem lies. You define the value of $affitta as '{{RENT_PRICE}}', which obviously doesn't equal 0 or whatever the price may be. Your templating system will substitute {{RENT_PRICE}} with the actual value, but here it's not a number. You are in fact evaluating: if ('{{RENT_PRICE}}' !== 0) {...

You need to instead compare with the value in $video->rent_price earlier up your code. How you access that value depends entirely on what's happening inside your PT_LoadPage function.


问:
How do I expand a macro containing commas inside a BOOST_PP_IF
I asked the following question earlier, but the solution doesn't seem to work in this particular case.

How do I print out a comma multiple times using Boost Preprocessor

I am trying to expand a macro containing a comma conditionally. Here is an example illustrating the problem:

```<code>#define TEST(...)\
    BOOST_PP_REPEAT( \
        BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
        MACRO, \
        BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__))

#define MACRO(z, n, data) BOOST_PP_IF(1,MACRO_CONTAINING_COMMA(z, z),MACRO_CONTAINING_COMMA(z, z))

#define MACRO_CONTAINING_COMMA(_NAME, _NAME2) _NAME TIBRA_EATEN_COMMA() _NAME2

#define EATEN_COMMA BOOST_PP_IF(1,BOOST_PP_COMMA,BOOST_PP_TUPLE_EAT())
TEST(1,2,3,4)
</code>```

This expands to

BOOST_PP_IIF BOOST_PP_IIF BOOST_PP_IIF BOOST_PP_IIF

When it should expand to

0,0 1,1 2,2 3,3

答:
It turns out that you can do this without __VA_ARGS__. In this simple example I used a comma which is in the template argument of function toString<int,int>() Working demo:

```<code>#include <boost/lexical_cast.hpp>
#include <boost/preprocessor.hpp>
#include <iostream>
#include <string>

#define SEQUENCE (1)(2)(3)(4)(5)(6)(7)(8)(9)(10)

#define IGNORE_ARG(arg)
#define GET_NAME(data) BOOST_PP_SEQ_ELEM(0, data)
#define GET_BELOW(data) BOOST_PP_SEQ_ELEM(1, data)

#define PARSE_SEQUENCE(r, data, elem)                  \
    BOOST_PP_IF(                                       \
        BOOST_PP_GREATER_EQUAL(elem, GET_BELOW(data)), \
            GET_NAME(data), IGNORE_ARG)                \
    (elem)

#define SKIP_NUMBERS_BELOW(name, below)                \
    BOOST_PP_SEQ_FOR_EACH(PARSE_SEQUENCE, (name)(below), SEQUENCE)

#define TEST(name) SKIP_NUMBERS_BELOW(name, 4)

#define MACRO_CONTAINING_COMMA(N) toString<N, 2 * N>() <<

template <int a, int b> // whatever, I just need a comma here.
std::string toString() {
    return boost::lexical_cast<std::string>(a) + ":" + boost::lexical_cast<std::string>(b) + " ";
}

int main() {
    std::cout << TEST(MACRO_CONTAINING_COMMA) "\n";
}
</code>```

Body:
I asked the following question earlier, but the solution doesn't seem to work in this particular case.

How do I print out a comma multiple times using Boost Preprocessor

I am trying to expand a macro containing a comma conditionally. Here is an example illustrating the problem:

#define TEST(...)\
    BOOST_PP_REPEAT( \
        BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
        MACRO, \
        BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__))

#define MACRO(z, n, data) BOOST_PP_IF(1,MACRO_CONTAINING_COMMA(z, z),MACRO_CONTAINING_COMMA(z, z))

#define MACRO_CONTAINING_COMMA(_NAME, _NAME2) _NAME TIBRA_EATEN_COMMA() _NAME2

#define EATEN_COMMA BOOST_PP_IF(1,BOOST_PP_COMMA,BOOST_PP_TUPLE_EAT())
TEST(1,2,3,4)

This expands to

BOOST_PP_IIF BOOST_PP_IIF BOOST_PP_IIF BOOST_PP_IIF

When it should expand to

0,0 1,1 2,2 3,3

Body:
It turns out that you can do this without __VA_ARGS__. In this simple example I used a comma which is in the template argument of function toString<int,int>() Working demo:

#include <boost/lexical_cast.hpp>
#include <boost/preprocessor.hpp>
#include <iostream>
#include <string>

#define SEQUENCE (1)(2)(3)(4)(5)(6)(7)(8)(9)(10)

#define IGNORE_ARG(arg)
#define GET_NAME(data) BOOST_PP_SEQ_ELEM(0, data)
#define GET_BELOW(data) BOOST_PP_SEQ_ELEM(1, data)

#define PARSE_SEQUENCE(r, data, elem)                  \
    BOOST_PP_IF(                                       \
        BOOST_PP_GREATER_EQUAL(elem, GET_BELOW(data)), \
            GET_NAME(data), IGNORE_ARG)                \
    (elem)

#define SKIP_NUMBERS_BELOW(name, below)                \
    BOOST_PP_SEQ_FOR_EACH(PARSE_SEQUENCE, (name)(below), SEQUENCE)

#define TEST(name) SKIP_NUMBERS_BELOW(name, 4)

#define MACRO_CONTAINING_COMMA(N) toString<N, 2 * N>() <<

template <int a, int b> // whatever, I just need a comma here.
std::string toString() {
    return boost::lexical_cast<std::string>(a) + ":" + boost::lexical_cast<std::string>(b) + " ";
}

int main() {
    std::cout << TEST(MACRO_CONTAINING_COMMA) "\n";
}


问:
tuneRF vs caret tunning for random forest
I've trying to tune a random forest model using the tuneRF tool included in the randomForest Package and I'm also using the caret package to tune my model. The issue is that I'm tunning to get mtry and I'm getting different results for each approach. The question is how do I know which is the best approach and base on what? I'm not clear if I should expect similar or different results.

tuneRF: with this approach I'm getting the best mtry is 3

```<code>t <- tuneRF(train[,-12], train[,12],
        stepFactor = 0.5,
        plot = TRUE,
        ntreeTry = 100,
        trace = TRUE,
        improve = 0.05)
</code>```

caret: With this approach I'm always getting that the best mtry is all variables in this case 6

```<code>control <- trainControl(method="cv", number=5)
tunegrid <- expand.grid(.mtry=c(2:6))
set.seed(2)
custom <- train(CRTOT_03~., data=train, method="rf", metric="rmse",
                tuneGrid=tunegrid, ntree = 100, trControl=control)
</code>```

答:
There are a few differences, for each mtry parameters, tuneRF fits one model on the whole dataset, and you get the OOB error from each of these fit. tuneRF then takes the lowest OOB error. For each value of mtry, you have one score (or RMSE value) and this will change with different runs.

In caret, you actually do cross-validation, so the test data from the fold was not used at all in the model. Though in principle it should be similar to OOB, you should be aware of the differences.

A evaluation with a better picture on the error might be to run tuneRF a few rounds, and we can use cv in caret:

```<code>library(randomForest)
library(mlbench)
data(BostonHousing)
train <- BostonHousing

tuneRF_res = lapply(1:10,function(i){

tr = tuneRF(train[,-14], train[,14],mtryStart=2,step=0.9,ntreeTry = 100,trace = TRUE,improve=1e-5)
tr = data.frame(tr)
tr$RMSE = sqrt(tr[,2])
tr
})

tuneRF_res = do.call(rbind,tuneRF_res)

control <- trainControl(method="cv", number=10,returnResamp="all")
tunegrid <- expand.grid(.mtry=c(2:7))
caret_res <- train(medv ~., data=train, method="rf", metric="RMSE",
                tuneGrid=tunegrid, ntree = 100, trControl=control)

library(ggplot2)
df = rbind(
data.frame(tuneRF_res[,c("mtry","RMSE")],test="tuneRF"),
data.frame(caret_res$resample[,c("mtry","RMSE")],test="caret")
)
df = df[df$mtry!=1,]

ggplot(df,aes(x=mtry,y=RMSE,col=test))+
stat_summary(fun.data=mean_se,geom="errorbar",width=0.2) +
stat_summary(fun=mean,geom="line") + facet_wrap(~test)
</code>```

You can see the trend is more or less similar. My suggestion would be to use tuneRF to quickly check the range of mtrys to train over, then use caret, cross-validation to properly evaluate this.

Body:
I've trying to tune a random forest model using the tuneRF tool included in the randomForest Package and I'm also using the caret package to tune my model. The issue is that I'm tunning to get mtry and I'm getting different results for each approach. The question is how do I know which is the best approach and base on what? I'm not clear if I should expect similar or different results.

tuneRF: with this approach I'm getting the best mtry is 3

t <- tuneRF(train[,-12], train[,12],
        stepFactor = 0.5,
        plot = TRUE,
        ntreeTry = 100,
        trace = TRUE,
        improve = 0.05)

caret: With this approach I'm always getting that the best mtry is all variables in this case 6

control <- trainControl(method="cv", number=5)
tunegrid <- expand.grid(.mtry=c(2:6))
set.seed(2)
custom <- train(CRTOT_03~., data=train, method="rf", metric="rmse",
                tuneGrid=tunegrid, ntree = 100, trControl=control)

Body:
There are a few differences, for each mtry parameters, tuneRF fits one model on the whole dataset, and you get the OOB error from each of these fit. tuneRF then takes the lowest OOB error. For each value of mtry, you have one score (or RMSE value) and this will change with different runs.

In caret, you actually do cross-validation, so the test data from the fold was not used at all in the model. Though in principle it should be similar to OOB, you should be aware of the differences.

A evaluation with a better picture on the error might be to run tuneRF a few rounds, and we can use cv in caret:

library(randomForest)
library(mlbench)
data(BostonHousing)
train <- BostonHousing

tuneRF_res = lapply(1:10,function(i){

tr = tuneRF(train[,-14], train[,14],mtryStart=2,step=0.9,ntreeTry = 100,trace = TRUE,improve=1e-5)
tr = data.frame(tr)
tr$RMSE = sqrt(tr[,2])
tr
})

tuneRF_res = do.call(rbind,tuneRF_res)

control <- trainControl(method="cv", number=10,returnResamp="all")
tunegrid <- expand.grid(.mtry=c(2:7))
caret_res <- train(medv ~., data=train, method="rf", metric="RMSE",
                tuneGrid=tunegrid, ntree = 100, trControl=control)

library(ggplot2)
df = rbind(
data.frame(tuneRF_res[,c("mtry","RMSE")],test="tuneRF"),
data.frame(caret_res$resample[,c("mtry","RMSE")],test="caret")
)
df = df[df$mtry!=1,]

ggplot(df,aes(x=mtry,y=RMSE,col=test))+
stat_summary(fun.data=mean_se,geom="errorbar",width=0.2) +
stat_summary(fun=mean,geom="line") + facet_wrap(~test)

You can see the trend is more or less similar. My suggestion would be to use tuneRF to quickly check the range of mtrys to train over, then use caret, cross-validation to properly evaluate this.


问:
Adding the new images loaded through ajax to opened lightbox pop-up
i am facing a issue.
I have created a images gallery in which the 18 images are showing by default and if user scroll down to the end of page then more images are adding to the gallery through ajax.

Now suppose when user have 18 images and he opens a lightbox then the opend lightbox has 18 images that he can navigate back and forth.

Now if user scroll the page to end the new images are added to the page and i want to add those images to theopened lightbox.

Please suggest a way to acheive this.

Thanks in advance.

答:
Background

When the user clicks an image, the Lightbox script's start() method is called. This will compile the list of images to show, either a single one, or a set if data-lightbox is specified, by going through the page. These are stored in a an array called album on the lightbox object.

If you dynamically load images, then the user click an image to open Lightbox, things should work as expected, as the compilation of images happens on open.

Solution

In your scenario, the Lightbox is already open, and I'm assuming you have a set of images being browsed. You want to let the user continue scrolling while the Lightbox is open and this scrolling will dynamically load more images onto the page that are part of this set.

There is no documented way of doing this. But, you can fix your issue by digging into the internals pretty easily. This is normally not recommended, but no major changes to the Lightbox2 API are expected, so this should be safe (no guarantees though).

On scroll, once new images are loaded, add them to the Lightbox object's album property manually. Then call updateDetails() to refresh the UI.

```<code>lightbox.album.push({
  link: 'fruit-roll-ups.jpg'
});
lightbox.updateDetails();
</code>```

Body:
Background

When the user clicks an image, the Lightbox script's start() method is called. This will compile the list of images to show, either a single one, or a set if data-lightbox is specified, by going through the page. These are stored in a an array called album on the lightbox object.

If you dynamically load images, then the user click an image to open Lightbox, things should work as expected, as the compilation of images happens on open.

Solution

In your scenario, the Lightbox is already open, and I'm assuming you have a set of images being browsed. You want to let the user continue scrolling while the Lightbox is open and this scrolling will dynamically load more images onto the page that are part of this set.

There is no documented way of doing this. But, you can fix your issue by digging into the internals pretty easily. This is normally not recommended, but no major changes to the Lightbox2 API are expected, so this should be safe (no guarantees though).

On scroll, once new images are loaded, add them to the Lightbox object's album property manually. Then call updateDetails() to refresh the UI.

lightbox.album.push({
  link: 'fruit-roll-ups.jpg'
});
lightbox.updateDetails();


问:
Is a good practice to used shifted unsigned numbers as an index number of array
Defining the enum as flags in the following way

```<code>    typedef enum
    {
        NOT_PID = 0,
        PID1 = (1U << 0),
        PID2 = (1U << 1),
        NUM_PID = 3

    } pid_t;

    float m_derivative[pid_t::NUM_PID];
</code>```

and using it as follows:

```<code>    m_derivative[pid_t::PID1] = 4.0
    m_derivative[pid_t::PID2] = 3.0
</code>```

Is good practice to used shifted unsigned numbers as a index number of array in this way?

答:
What happens if you go one further?

```<code>typedef enum
{
    NOT_PID = 0,
    PID1 = (1U << 0),
    PID2 = (1U << 1),
    PID3 = (1U << 2),
    NUM_PID = 4
} pid_t;

float m_derivative[pid_t::NUM_PID];
m_derivative[pid_t::PID3] = 4.0; // out of bounds
</code>```

Here, PID3 = 4 which is not less than NUM_PID. This causes an out of bounds access.

If you define NUM_PID to be large enough, then it's no longer the number of PIDs as the name implies. Moreover, if you have a relatively large number of PIDs, then you are going to waste a lot of memory. For example, with 20 PIDs, you need an array of 2^20 = 1048576 elements, which is 4MB assuming 32-bit enumerators.

If you actually need the powers of two somewhere, produce them whenever you need them:

```<code>enum pid_t { NOT_PID, PID1, PID2, PID3, NUM_PID };
auto pid_bit(pid_t pid) -> unsigned int {
    if (pid == NOT_PID) {
        return 0;
    }
    return 1u << (pid-1);
}
</code>```

Also note that, in C++, you don't need to typedef your enum.

Body:
Defining the enum as flags in the following way

    typedef enum
    {
        NOT_PID = 0,
        PID1 = (1U << 0),
        PID2 = (1U << 1),
        NUM_PID = 3

    } pid_t;

    float m_derivative[pid_t::NUM_PID];

and using it as follows:

    m_derivative[pid_t::PID1] = 4.0
    m_derivative[pid_t::PID2] = 3.0

Is good practice to used shifted unsigned numbers as a index number of array in this way?

Body:
What happens if you go one further?

typedef enum
{
    NOT_PID = 0,
    PID1 = (1U << 0),
    PID2 = (1U << 1),
    PID3 = (1U << 2),
    NUM_PID = 4
} pid_t;

float m_derivative[pid_t::NUM_PID];
m_derivative[pid_t::PID3] = 4.0; // out of bounds

Here, PID3 = 4 which is not less than NUM_PID. This causes an out of bounds access.

If you define NUM_PID to be large enough, then it's no longer the number of PIDs as the name implies. Moreover, if you have a relatively large number of PIDs, then you are going to waste a lot of memory. For example, with 20 PIDs, you need an array of 2^20 = 1048576 elements, which is 4MB assuming 32-bit enumerators.

If you actually need the powers of two somewhere, produce them whenever you need them:

enum pid_t { NOT_PID, PID1, PID2, PID3, NUM_PID };
auto pid_bit(pid_t pid) -> unsigned int {
    if (pid == NOT_PID) {
        return 0;
    }
    return 1u << (pid-1);
}

Also note that, in C++, you don't need to typedef your enum.


问:
"Trust relationship between ... and the primary domain failed" in MVC5 Authentication
I have a ASP .NET MVC5 application in which I am not using Windows Authentication.

Everything was working fine until I tried running the application outside of the Domain in which it was being developed and (for whatever reason) got a:

```<code>The trust relationship between this workstation and the primary domain failed.
</code>```

when I'm trying to do User.IsInRole("Admin").

I am using custom Identity, Role, IdentityStore, RoleStore, etc. from .NET's Identity and I can see that the User and Role data is being retrieved from the (MongoDB) database correctly.

There are plenty of questions regarding this issue, but they're from people who want to use Windows Auth. and impersonation in their MVC applications:

With windows authentication, The trust relationship between the primary domain and the trusted domain failed, when calling IsInRole

How to configure Windows Authentication / Impersonation + IIS 7 + MVC

The trust relationship between the primary domain and the trusted domain failed

My.User.IsInRole("Role Name") throws a Trust Relationship error on Windows 7

So why exactly am I getting this SystemException if I'm not using Active Directory and (as far as I know) not doing anything that might depend on the PC's domain? Am I missing some configuration (either in my Web.config or IIS Express)?

EDIT:

Ok, so narrowing it down a bit...

My User.IsInRole("Admin") line is inside an if() statement in my _Layout.cshtml View (i.e., to know what to show in the nav. bar depending on the role).

I now know I only get the error above when no user is authenticated and I'm not in the domain I used for dev. If I place a breakpoint on that line, I can see that the User object is is a System.Security.Principal.WindowsIdentity and its underlying Identity is System.Security.Principal.WindowsIdentity.

On the other hand, if the user is authenticated, then the User object and ts Identity are System.Security.Claims.ClaimsPrincipal and System.Security.Claims.ClaimsIdentity.

Why is it using Windows Identity at all (when unauthenticated) and how can I disable it?

答:
On my case, I am not using  User.Identity but rather Thread.CurrentPrincipal.Identity.Name

So when I approach this line of code:

```<code>Thread.CurrentPrincipal.IsInRole("admin");
</code>```

That's where I will encounter the same error message of:

The trust relationship between this workstation and the primary domain failed.

There are two cases why I encountered the same issue and of course the fixes I made:

I was disconnected with my VPN. This will look for the role that doesn't exist since I am not connected with my VPN and not connecting with my AD accounts.

If I am connected with my VPN and the role admin doesn't exist based on my code above, it will certainly trigger the same error message.

Body:
I have a ASP .NET MVC5 application in which I am not using Windows Authentication.

Everything was working fine until I tried running the application outside of the Domain in which it was being developed and (for whatever reason) got a:

The trust relationship between this workstation and the primary domain failed.

when I'm trying to do User.IsInRole("Admin").

I am using custom Identity, Role, IdentityStore, RoleStore, etc. from .NET's Identity and I can see that the User and Role data is being retrieved from the (MongoDB) database correctly.

There are plenty of questions regarding this issue, but they're from people who want to use Windows Auth. and impersonation in their MVC applications:

With windows authentication, The trust relationship between the primary domain and the trusted domain failed, when calling IsInRole

How to configure Windows Authentication / Impersonation + IIS 7 + MVC

The trust relationship between the primary domain and the trusted domain failed

My.User.IsInRole("Role Name") throws a Trust Relationship error on Windows 7

So why exactly am I getting this SystemException if I'm not using Active Directory and (as far as I know) not doing anything that might depend on the PC's domain? Am I missing some configuration (either in my Web.config or IIS Express)?

EDIT:

Ok, so narrowing it down a bit...

My User.IsInRole("Admin") line is inside an if() statement in my _Layout.cshtml View (i.e., to know what to show in the nav. bar depending on the role).

I now know I only get the error above when no user is authenticated and I'm not in the domain I used for dev. If I place a breakpoint on that line, I can see that the User object is is a System.Security.Principal.WindowsIdentity and its underlying Identity is System.Security.Principal.WindowsIdentity.

On the other hand, if the user is authenticated, then the User object and ts Identity are System.Security.Claims.ClaimsPrincipal and System.Security.Claims.ClaimsIdentity.

Why is it using Windows Identity at all (when unauthenticated) and how can I disable it?

Body:
On my case, I am not using  User.Identity but rather Thread.CurrentPrincipal.Identity.Name

So when I approach this line of code:

Thread.CurrentPrincipal.IsInRole("admin");

That's where I will encounter the same error message of:

The trust relationship between this workstation and the primary domain failed.

There are two cases why I encountered the same issue and of course the fixes I made:

I was disconnected with my VPN. This will look for the role that doesn't exist since I am not connected with my VPN and not connecting with my AD accounts.

If I am connected with my VPN and the role admin doesn't exist based on my code above, it will certainly trigger the same error message.


问:
C# unsafe value type array to byte array conversions
I use an extension method to convert float arrays into byte arrays:

```<code>public static unsafe byte[] ToByteArray(this float[] floatArray, int count)
{
    int arrayLength = floatArray.Length > count ? count : floatArray.Length;
    byte[] byteArray = new byte[4 * arrayLength];
    fixed (float* floatPointer = floatArray)
    {
        fixed (byte* bytePointer = byteArray)
        {
            float* read = floatPointer;
            float* write = (float*)bytePointer;
            for (int i = 0; i < arrayLength; i++)
            {
                *write++ = *read++;
            }
        }
    }
    return byteArray;
}
</code>```

I understand that an array is a pointer to memory associated with information on the type and number of elements. Also, it seems to me that there is no way of doing a conversion from and to a byte array without copying the data as above.

Have I understood this? Would it even be impossible to write IL to create an array from a pointer, type and length without copying data?

EDIT: Thanks for the answers, I learned some fundamentals and got to try out new tricks!

After initially accepting Davy Landman's answer I found out that while his brilliant StructLayout hack does convert byte arrays into float arrays, it does not work the other way around. To demonstrate:

```<code>[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public Byte[] Bytes;

    [FieldOffset(0)]
    public float[] Floats;
}

static void Main(string[] args)
{
    // From bytes to floats - works
    byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 };
    UnionArray arry = new UnionArray { Bytes = bytes };
    for (int i = 0; i < arry.Bytes.Length / 4; i++)
        Console.WriteLine(arry.Floats[i]);

    // From floats to bytes - index out of range
    float[] floats = { 0.1f, 0.2f, 0.3f };
    arry = new UnionArray { Floats = floats };
    for (int i = 0; i < arry.Floats.Length * 4; i++)
        Console.WriteLine(arry.Bytes[i]);
}
</code>```

It seems that the CLR sees both arrays as having the same length. If the struct is created from float data, the byte array's length is just too short.

答:
This question is the reverse of What is the fastest way to convert a float[] to a byte[]?.

I've answered with a union kind of hack to skip the whole copying of the data. You could easily reverse this (length = length *sizeof(Double).

OwnerDisplayName: Ville Koskinen

ContentLicense: CC BY-SA 2.5

Body:
I use an extension method to convert float arrays into byte arrays:

public static unsafe byte[] ToByteArray(this float[] floatArray, int count)
{
    int arrayLength = floatArray.Length > count ? count : floatArray.Length;
    byte[] byteArray = new byte[4 * arrayLength];
    fixed (float* floatPointer = floatArray)
    {
        fixed (byte* bytePointer = byteArray)
        {
            float* read = floatPointer;
            float* write = (float*)bytePointer;
            for (int i = 0; i < arrayLength; i++)
            {
                *write++ = *read++;
            }
        }
    }
    return byteArray;
}

I understand that an array is a pointer to memory associated with information on the type and number of elements. Also, it seems to me that there is no way of doing a conversion from and to a byte array without copying the data as above.

Have I understood this? Would it even be impossible to write IL to create an array from a pointer, type and length without copying data?

EDIT: Thanks for the answers, I learned some fundamentals and got to try out new tricks!

After initially accepting Davy Landman's answer I found out that while his brilliant StructLayout hack does convert byte arrays into float arrays, it does not work the other way around. To demonstrate:

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public Byte[] Bytes;

    [FieldOffset(0)]
    public float[] Floats;
}

static void Main(string[] args)
{
    // From bytes to floats - works
    byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 };
    UnionArray arry = new UnionArray { Bytes = bytes };
    for (int i = 0; i < arry.Bytes.Length / 4; i++)
        Console.WriteLine(arry.Floats[i]);

    // From floats to bytes - index out of range
    float[] floats = { 0.1f, 0.2f, 0.3f };
    arry = new UnionArray { Floats = floats };
    for (int i = 0; i < arry.Floats.Length * 4; i++)
        Console.WriteLine(arry.Bytes[i]);
}

It seems that the CLR sees both arrays as having the same length. If the struct is created from float data, the byte array's length is just too short.

LastEditorDisplayName: Ville Koskinen

OwnerDisplayName: Davy Landman


问:
Missing Request parameters with UTF-8 when javascript escape() is used
I am using jquery ajax api to submit (POST/GET) a text as parameter to a processing page.

```<code><input type="text" id="txtboxdata" name="txtboxdata" >

var dataString = "tmpVar="+ escape( $("#txtboxdata").val() );
$.ajax({ type: "POST",
                  url: "processing.jsp",
                  data: dataString ,
                  dataType: "json",
                  success: function(){}
        });

//dataString holds the parameter and value to be passed. Value is retrieved from a text box.
</code>```

If the text box

contains UTF-8 characters

and

apply the javascript "escape" on the text box value

then the parameter tmpVar goes disappears from the request object in the processing page(processing.jsp).

I used the debugger, and checked the request object. The parameter called "tmpVar" never shows up.

This works correctly when the following conditions are met

tmpVar shows up in the request object of processing.jsp when

there are no UTF-8 characters.

I do not apply "escape" before making the ajax call.

My Question
I would like to understand why does applying escape on a text containing UTF-8 not show up in the request object?

PS: I used "form serialize()" to solve the problem, just trying to understand why the issue occured.

Firebug: looks fine, this always shows up correctly. No missing data before the actual POST/GET.

答:
Using the answer provided by @SLaks did some more research and found a satisfactory answer.

Explains why "escape" shouldn't be used and compares it with other method which can be used.

encodeURIComponent()

encodeURI()

http://xkr.us/articles/javascript/encode-compare/

Body:
I am using jquery ajax api to submit (POST/GET) a text as parameter to a processing page.

<input type="text" id="txtboxdata" name="txtboxdata" >

var dataString = "tmpVar="+ escape( $("#txtboxdata").val() );
$.ajax({ type: "POST",
                  url: "processing.jsp",
                  data: dataString ,
                  dataType: "json",
                  success: function(){}
        });

//dataString holds the parameter and value to be passed. Value is retrieved from a text box.

If the text box

contains UTF-8 characters

and

apply the javascript "escape" on the text box value

then the parameter tmpVar goes disappears from the request object in the processing page(processing.jsp).

I used the debugger, and checked the request object. The parameter called "tmpVar" never shows up.

This works correctly when the following conditions are met

tmpVar shows up in the request object of processing.jsp when

there are no UTF-8 characters.

I do not apply "escape" before making the ajax call.

My Question
I would like to understand why does applying escape on a text containing UTF-8 not show up in the request object?

PS: I used "form serialize()" to solve the problem, just trying to understand why the issue occured.

Firebug: looks fine, this always shows up correctly. No missing data before the actual POST/GET.


问:
Reed-Solomon in file recovery
A piece of software I'm working on outputs quite a lot of files which are the stored on a server. During its runtime I've had one file go corrupt on me. These files are critical to the operation, so this cannot happen. I'm therefore trying to come up with a way of adding error correction to the files to prevent this from ever happening again.

I've read up on Reed-Solomon, which encodes k blocks of data plus m blocks of parity, and can then reconstruct up to m missing blocks. So what I'm thinking is taking the data stream, split it into these blocks, and then store them in sequence on disk, first the data blocks, then the parity blocks. Repeat until entire file is stored. k, m, and block sizes are of course variables I'll have to investigate and play with.

However, it's my understanding that Reed-Solomon requires you to know which blocks are corrupt. How could I possibly know that? My thinking is I'd have to add some extra, simpler, error detection code to each of the blocks as I write them, otherwise I can't know if they're corrupted. Like CRC32 or something.

Have I understood this correctly, or is there a better way to accomplish this?

答:
This is a bit of an older question, but (in my mind) is always something that is useful and in some cases necessary. Bit rot will never be completely cured (hush ZFS community; ZFS only has control of what's on it's filesystem while it's there), so we always have to come up with proactive prevention and recovery plans.

While it was designed to facilitate piracy (specifically storing and extracting multi-GB files in chunks on newsgroups where any chunk could go missing or be corrupted), "Parchives" are actually exactly what you're looking for (see the white paper, though don't implement that scheme directly as it has a bug and newer schemes are available), and they work in practice as follows:

The complete file is input in to the encoder

Blocks are processed and Reed-Solomon blocks are generated

.par files containing those blocks are output along side the original file

When integrity is checked (typically on the other end of a file transfer), the blocks are rechecked and any blocks that need to be used to reconstruct missing data are pulled from the .par files.

Things eventually settled in to "PAR2" (essentially a rewrite with additional features) with the following scheme:

Large file compressed with RAR and split in to chunks (typically around 100MB each as that was a "usually safe" max of usenet)

An "index" file is placed along side the file (for example bigfile.PAR2). This has no recovery chunks.

A series of par files totaling 10% of the original data size are along side in increasingly larger filesizes (bigfile.vol029+25.PAR2, bigfile.vol104+88.PAR2, etc)

The person on the other end can then gets all .rar files

An integrity check is run, and returns a MB count of out how much data needs recovery

.PAR2 files are downloaded in an amount equal to or greater than the need

Recovery is done and integrity verified

RAR is extracted, and the original file is successfully transferred

Now without a filesystem layer this system is still fairly trivial to implement using the Parchive tools, but it has two requirements:

That the files do not change (as any change to the file on-disk will invalidate the parity data (of course you could do this and add complexity with a copy-on-change writing scheme))

That you run both the file generation and integrity check/recovery when appropriate.

Since all the math and methods are both known and battle-tested, you can also roll your own to meet whatever needs to have (as a hook in to file read/write, spanning arbitrary path depths, storing recovery data on a separate drive, etc). For initial tips, refer to the pros: https://www.backblaze.com/blog/reed-solomon/

Edit: The same research that led me to this question led me to a whole subset of already-done work that I was previously unaware of

https://crates.io/crates/solana-reed-solomon-erasure (as well as a bunch of other implementations in the Rust crate registry)

https://github.com/klauspost/reedsolomon (based on the BackBlaze code, and processes 1Gbps per core)

Etc. Look for "Reed-Solomon file recovery "

Title: Reed-Solomon in file recovery


问:
Pass Data From Node/Express to Front-End Javascript
I am unsure how this would work exactly, and I am unable to find my answer from searching for it.  I am working with a node and express server, and have been passing data to my front end ejs without issues.  Now, I am trying to implement charts.js in my front-end, and that requires the data to be in a front-end javascript file.  I know that to pass data to my ejs file, I use something like this:

```<code>res.render("dashboard", {data: data});
</code>```

and to display the data in the ejs file, I use

```<code><%= data %>
</code>```

Now, what I would like to do, is basically the same thing, but instead of passing the data into an ejs file, I want to pass it into a javascript file, while still displaying the ejs file.  Right now, I can't seem to figure out how I go from having my data in the express server, and returning it into a front-end javascript file.  The flow I am looking for would be something like this:

In node:

```<code>data = []:
res.render("dashboard", {data: data});
</code>```

and then the ejs file is rendered and data is passed into the front-end javascript file that is being used within the ejs file:

```<code>let data = <%= (data array passed from the node server here) %>
</code>```

Of course, this is not the correct way to write the code, but this is the basic logic I am trying to implement.

I am sure this is something simple, but I can't seem to find the answer within my context here.  Are there any resources where I can learn to do what I am trying to do?  Thanks.

Body:
I am unsure how this would work exactly, and I am unable to find my answer from searching for it.  I am working with a node and express server, and have been passing data to my front end ejs without issues.  Now, I am trying to implement charts.js in my front-end, and that requires the data to be in a front-end javascript file.  I know that to pass data to my ejs file, I use something like this:

res.render("dashboard", {data: data});

and to display the data in the ejs file, I use

<%= data %>

Now, what I would like to do, is basically the same thing, but instead of passing the data into an ejs file, I want to pass it into a javascript file, while still displaying the ejs file.  Right now, I can't seem to figure out how I go from having my data in the express server, and returning it into a front-end javascript file.  The flow I am looking for would be something like this:

In node:

data = []:
res.render("dashboard", {data: data});

and then the ejs file is rendered and data is passed into the front-end javascript file that is being used within the ejs file:

let data = <%= (data array passed from the node server here) %>

Of course, this is not the correct way to write the code, but this is the basic logic I am trying to implement.

I am sure this is something simple, but I can't seem to find the answer within my context here.  Are there any resources where I can learn to do what I am trying to do?  Thanks.

Body:
You can't respond to a single request with both an HTML document and a seperate JavaScript file.

So you need to either:

Store the data somewhere and, in a separate endpoint, serve up some generated JavaScript and have a mechanism which identifies which data to serve up when the request is made. (NB: This is stupidly complex. Don't do it.)

Generate the JavaScript inline in the HTML document inside a <script> element. (You'll need to properly escape the data as JS to make sure you aren't subject to XSS).

Output the data into the HTML document (e.g. with data-* attributes or <meta> elements) and read it with static JavaScript.

Again, using a seperate endpoint: Serve up JSON with the data in it and read that with Ajax from a static JS file. (Again, you'll need a way to determine which data to send for that particular request).