问:
SELECT query where two fields do NOT match not working
I have an VBA script which looks through a table that is a join of two different tables (a and b), where there may be fields that don't match between the table (table a is the original, table b is the same table, but a new export file).

The goal is to find which field(s) differ and update one field in the shared field with a list of fields that did not match between the two tables (a and b).

But one field is not passing its test.  I tried separately querying this table to see if I could use a simple SQL query to determine if Access was recognizing the difference.

I cannot understand why this is not working, as if I try other fields in the same manner, it returns the expected result.  I have confirmed that both fields are Short Text data type, both fields have the same "General Properties", "Lookup Properties" and the "Property Sheet" also matches not only between the two fields, but all other similar fields.

This query:

```<code>SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE ID = 18;
</code>```

Results in:

```<code>[a_Address 2] = (NULL)
[b_Address 2] = xasdf
</code>```

But when I try this query:

```<code>SELECT *
FROM Staging_LOG_ExportDifferences
WHERE [a_Address 2] <> [b_Address 2];
</code>```

Results in:

```<code>No results
</code>```

答:
As an alternative, you could use this approach, preventing you from having to use multiple if statements in VBA:</p>

```<code>SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE Len(Nz([a_Address 2],"")) <> Len(Nz([b_Address 2],""))
</code>```

Body:
I have an VBA script which looks through a table that is a join of two different tables (a and b), where there may be fields that don't match between the table (table a is the original, table b is the same table, but a new export file).

The goal is to find which field(s) differ and update one field in the shared field with a list of fields that did not match between the two tables (a and b).

But one field is not passing its test.  I tried separately querying this table to see if I could use a simple SQL query to determine if Access was recognizing the difference.

I cannot understand why this is not working, as if I try other fields in the same manner, it returns the expected result.  I have confirmed that both fields are Short Text data type, both fields have the same "General Properties", "Lookup Properties" and the "Property Sheet" also matches not only between the two fields, but all other similar fields.

This query:

SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE ID = 18;

Results in:

[a_Address 2] = (NULL)
[b_Address 2] = xasdf

But when I try this query:

SELECT *
FROM Staging_LOG_ExportDifferences
WHERE [a_Address 2] <> [b_Address 2];

Results in:

No results

Body:
As an alternative, you could use this approach, preventing you from having to use multiple if statements in VBA:

SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE Len(Nz([a_Address 2],"")) <> Len(Nz([b_Address 2],""))


来源: stackexchange

问:
How to ensure application/hal+json is the first supported media type
I have created a Hateoas enabled Rest service using spring-boot-starter-data-rest, works well.

I then created a client of that rest service in another spring boot module: this is a dependency that can be included in other projects that want to use the rest service. It uses a restTemplate under the hood.
It took a bit of mucking around with HttpMessageConverters and TypeConstrainedMappingJackson2HttpMessageConverter to get it to work but it does.

I tried using this dependency in my main application but it failed to populate the links in ResponseEntity< Resource< Myclass> >, leading to null pointer exceptions.

I couldn't track down the problem so I created a basic Spring Boot application 2.1.5.RELEASE and got the client working, then traced back the problem to this configuration in my main application which unfortunately is need for another problem:

```<code>spring:
  main:
    web-application-type: none
</code>```

If this configuration is present it seems that hal+json isn't the first accepted media type

```<code>org.springframework.core.log.CompositeLog.debug(CompositeLog.java:147) : Accept=[application/json, application/hal+json, application/octet-stream, application/*+json]
</code>```

When the configuration is removed I see

```<code>org.springframework.core.log.CompositeLog.debug(CompositeLog.java:147) : Accept=[application/hal+json, application/json, application/octet-stream, application/*+json]
</code>```

and I can see this logged which fixes the issue I assume ( it isn't logged when the error happens)

```<code>      - @ConditionalOnProperty (spring.hateoas.use-hal-as-default-json-media-type) matched (OnPropertyCondition)
</code>```

I have tried adding this configuration to force the issue but it doesn't work

```<code>spring:
  hateoas:
    use-hal-as-default-json-media-type: true
</code>```

This is my code in the rest client to configure the message converters:

```<code>@Configuration
public class MessageConverterConfiguration {

  @Bean public TypeConstrainedMappingJackson2HttpMessageConverter myhalJacksonHttpMessageConverter(){
    return new TypeConstrainedMappingJackson2HttpMessageConverter( ResourceSupport.class );
  }

  /**
   * Add {@link TypeConstrainedMappingJackson2HttpMessageConverter} to the list of {@link HttpMessageConverter}s
   * configured in the {@link  RestTemplate} in first position ( this position  is critical ).
   * @param halJacksonHttpMessageConverter automagically configured by spring-boot-starter-hateoas
   * @return List of {@link HttpMessageConverter}s
   */
  @Bean( name = "hal-jackson" ) public List< HttpMessageConverter<?> > mymessageConverters( TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter ) {

    final List<HttpMessageConverter<?>> all = new ArrayList<>(  );
    all.add( halJacksonHttpMessageConverter );
    all.add( jacksonConverterWithOctetStreamSupport( ) );
    all.addAll( new RestTemplate().getMessageConverters() );

    return all;
  }

  /**
   * This allows converting octet stream responses into {@link LastApplicationRun} ,
   * when we create a last run by posting with {@link RestTemplate#postForObject(URI , Object, Class)}
   * : without it we get a
   * ```org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter
   * found for response type [class com.sparknz.ced.spark.sampling.rest.tobesampled.client.domain.LastApplicationRun]
   * and content type [application/octet-stream]```.
   * <p></p>
   * I could find no better solution: it is not needed when we make a get call, don't understand why we get an octet stream response.
   * It may only now be useful for tests.
   */
  private MappingJackson2HttpMessageConverter jacksonConverterWithOctetStreamSupport( ) {

    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    converter.setSupportedMediaTypes(
        asList(new MediaType[]{
            MediaType.valueOf( "application/hal+json" ) ,
            MediaType.APPLICATION_JSON,
            MediaType.APPLICATION_OCTET_STREAM }));

    return converter;
  }

}
</code>```

What is 'web-application-type: none' doing and how can I get HypermediaHttpMessageConverterConfiguration to run?

答:
I found that adding this to my configuration class did the trick:
    @Import( RepositoryRestMvcConfiguration.class )

RepositoryRestMvcConfiguration seems to be responsible for making hal+json the highest priority by adding RepositoryRestMvcConfiguration.ResourceSupportHttpMessageConverter at position 0 in the list of HttpMessageConverters.

ContentLicense: CC BY-SA 4.0

Body:
I have created a Hateoas enabled Rest service using spring-boot-starter-data-rest, works well.

I then created a client of that rest service in another spring boot module: this is a dependency that can be included in other projects that want to use the rest service. It uses a restTemplate under the hood.
It took a bit of mucking around with HttpMessageConverters and TypeConstrainedMappingJackson2HttpMessageConverter to get it to work but it does.

I tried using this dependency in my main application but it failed to populate the links in ResponseEntity< Resource< Myclass> >, leading to null pointer exceptions.

I couldn't track down the problem so I created a basic Spring Boot application 2.1.5.RELEASE and got the client working, then traced back the problem to this configuration in my main application which unfortunately is need for another problem:

spring:
  main:
    web-application-type: none

If this configuration is present it seems that hal+json isn't the first accepted media type

org.springframework.core.log.CompositeLog.debug(CompositeLog.java:147) : Accept=[application/json, application/hal+json, application/octet-stream, application/*+json]

When the configuration is removed I see

org.springframework.core.log.CompositeLog.debug(CompositeLog.java:147) : Accept=[application/hal+json, application/json, application/octet-stream, application/*+json]

and I can see this logged which fixes the issue I assume ( it isn't logged when the error happens)

      - @ConditionalOnProperty (spring.hateoas.use-hal-as-default-json-media-type) matched (OnPropertyCondition)

I have tried adding this configuration to force the issue but it doesn't work

spring:
  hateoas:
    use-hal-as-default-json-media-type: true

This is my code in the rest client to configure the message converters:

@Configuration
public class MessageConverterConfiguration {

  @Bean public TypeConstrainedMappingJackson2HttpMessageConverter myhalJacksonHttpMessageConverter(){
    return new TypeConstrainedMappingJackson2HttpMessageConverter( ResourceSupport.class );
  }

  /**
   * Add {@link TypeConstrainedMappingJackson2HttpMessageConverter} to the list of {@link HttpMessageConverter}s
   * configured in the {@link  RestTemplate} in first position ( this position  is critical ).
   * @param halJacksonHttpMessageConverter automagically configured by spring-boot-starter-hateoas
   * @return List of {@link HttpMessageConverter}s
   */
  @Bean( name = "hal-jackson" ) public List< HttpMessageConverter<?> > mymessageConverters( TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter ) {

    final List<HttpMessageConverter<?>> all = new ArrayList<>(  );
    all.add( halJacksonHttpMessageConverter );
    all.add( jacksonConverterWithOctetStreamSupport( ) );
    all.addAll( new RestTemplate().getMessageConverters() );

    return all;
  }

  /**
   * This allows converting octet stream responses into {@link LastApplicationRun} ,
   * when we create a last run by posting with {@link RestTemplate#postForObject(URI , Object, Class)}
   * : without it we get a
   *
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter
   * found for response type [class com.sparknz.ced.spark.sampling.rest.tobesampled.client.domain.LastApplicationRun]
   * and content type [application/octet-stream]
.
   *

   * I could find no better solution: it is not needed when we make a get call, don't understand why we get an octet stream response.
   * It may only now be useful for tests.
   */
  private MappingJackson2HttpMessageConverter jacksonConverterWithOctetStreamSupport( ) {

    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    converter.setSupportedMediaTypes(
        asList(new MediaType[]{
            MediaType.valueOf( "application/hal+json" ) ,
            MediaType.APPLICATION_JSON,
            MediaType.APPLICATION_OCTET_STREAM }));

    return converter;
  }

}

What is 'web-application-type: none' doing and how can I get HypermediaHttpMessageConverterConfiguration to run?


问:
Can I create a new folder/directory under Windows Certificates and import all my self signed CA certificates in it
I am unable to find a solution where I can create a new folder/directory under Windows Certificates so that I can import all my self signed CA certificates into that folder.

I know that we can import our self signed CA certificates under Windows ROOT Trusted Root CA. But I have a requirement where we need to create a new Folder/Directory under the Windows Certificates so that I can import all of my self signed CA certificates under that folder.
We have lot of self signed CA certificates and my project requirement states that they be grouped under one folder.
I opened the certmgr.msc and checked for options but I could not find the option to create a new directory under the Windows Certificates. Is it possible to achieve this requirement?

答:
If you’re working in C, CertOpenStore, without the existing-only flag, will create a store.

In C# you can get the same by

```<code>X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
// the store should now appear in MMC (after a refresh)
</code>```

Adding to that store object works like any other store.

In my experience MMC won’t display private key management options for the custom store. Maybe there are options to let it do so, but any commandline utilities (or custom code) will probably see it just as any other store. (In MMC’s defense, it’s treating it like “any other store”... it thinks only the “My” store has private keys associated).

Body:
If you’re working in C, CertOpenStore, without the existing-only flag, will create a store.

In C# you can get the same by

X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
// the store should now appear in MMC (after a refresh)

Adding to that store object works like any other store.

In my experience MMC won’t display private key management options for the custom store. Maybe there are options to let it do so, but any commandline utilities (or custom code) will probably see it just as any other store. (In MMC’s defense, it’s treating it like “any other store”... it thinks only the “My” store has private keys associated).


问:
I have no experience with XML. How do i understand what is written in this XML file?
I have to start creating an android application. However, I have no experience with XML and understand the language. This XML file has data stored that I must use to create a Java program. I do not understand what I am looking at or how to read this language. I want to interpret the data so I can start coding it in Java. Please help.

I have tried to watch videos and learn XML but I cannot seem to apply the basics to interpret the information given to me in this file.

```<code><task name="neddle decompression" steps="8">

    <step
        description="Obtain a 14 gauge needle with catheter
        from your first aid kit.">
        <aid aid="needle.jpg">
        </aid>
        <aid aid="needle.avi">
        </aid>
    </step>

    <step description="Locate position on chest.">
        <aid aid="position.jpg">
        </aid>
    </step>

    <step description="Prepare chest area with antiseptic.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Insert the needle at a 90 degree angle.">
        <aid aid="insert.jpg">
        </aid>
    </step>

    <step
        description="Stop advancing the needle once a hiss of pop of air is heard. You should feel a 'pop' as the needle enters the chest cavity.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Hold the catheter in place and remove the needle.">
        <aid aid="catheter.jpg">
        </aid>
    </step>

    <step description="Leave the catheter and safely dispose of the needle.">
        <aid aid="dispose.jpg">
        </aid>
    </step>

    <step
        description="Tape the catheter in place and monitor the casualty until the medivac is available to insert a chest tube.">
        <aid image="tape.jpg">
        </aid>
    </step>

</task>

<task name="task2" steps="2">

    <step description="step1">
        <aid image="image1.png">
        </aid>
    </step>

    <step destription="step2">
        <aid aid="image.png">
        </aid>
        <aid aid="image3.avi">
        </aid>
    </step>

</task>
</code>```

I expect to get a guide of the classes and attributes I need to have in the Java program from this file.

答:
XML is just a format of your data, the content is inside open tag (Ex: <person>) and end tag (Ex: </person>). When your parent tag has child tags, just put these child tags between parent open tag and end tag and so on. Generally speaking, XML is a nested structure.

Simple example: A family (parent tag) has two members: Member 1 (level 1 child tag), Member 2 (level 1 child tag). Member 1 names Alice (level 2 child tag) and 24 year olds (level 2 child tag), Member 2 names Bob (level 2 child tag) and 27 year olds (level 2 child tag) then you have XML to store such data:

```<code><family>
    <member>
        <name>Alice</name>
        <age>24</age>
    </member>
    <member>
        <name>Bob</name>
        <age>27</age>
    </member>
</family>
</code>```

The easy way to parse XML format in Java is using DOM Parse, you can start with an simple example here

Good luck!

Body:
I have to start creating an android application. However, I have no experience with XML and understand the language. This XML file has data stored that I must use to create a Java program. I do not understand what I am looking at or how to read this language. I want to interpret the data so I can start coding it in Java. Please help.

I have tried to watch videos and learn XML but I cannot seem to apply the basics to interpret the information given to me in this file.

<task name="neddle decompression" steps="8">

    <step
        description="Obtain a 14 gauge needle with catheter
        from your first aid kit.">
        <aid aid="needle.jpg">
        </aid>
        <aid aid="needle.avi">
        </aid>
    </step>

    <step description="Locate position on chest.">
        <aid aid="position.jpg">
        </aid>
    </step>

    <step description="Prepare chest area with antiseptic.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Insert the needle at a 90 degree angle.">
        <aid aid="insert.jpg">
        </aid>
    </step>

    <step
        description="Stop advancing the needle once a hiss of pop of air is heard. You should feel a 'pop' as the needle enters the chest cavity.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Hold the catheter in place and remove the needle.">
        <aid aid="catheter.jpg">
        </aid>
    </step>

    <step description="Leave the catheter and safely dispose of the needle.">
        <aid aid="dispose.jpg">
        </aid>
    </step>

    <step
        description="Tape the catheter in place and monitor the casualty until the medivac is available to insert a chest tube.">
        <aid image="tape.jpg">
        </aid>
    </step>

</task>

<task name="task2" steps="2">

    <step description="step1">
        <aid image="image1.png">
        </aid>
    </step>

    <step destription="step2">
        <aid aid="image.png">
        </aid>
        <aid aid="image3.avi">
        </aid>
    </step>

</task>

I expect to get a guide of the classes and attributes I need to have in the Java program from this file.

Body:
XML is just a format of your data, the content is inside open tag (Ex: <person>) and end tag (Ex: </person>). When your parent tag has child tags, just put these child tags between parent open tag and end tag and so on. Generally speaking, XML is a nested structure.

Simple example: A family (parent tag) has two members: Member 1 (level 1 child tag), Member 2 (level 1 child tag). Member 1 names Alice (level 2 child tag) and 24 year olds (level 2 child tag), Member 2 names Bob (level 2 child tag) and 27 year olds (level 2 child tag) then you have XML to store such data:

<family>
    <member>
        <name>Alice</name>
        <age>24</age>
    </member>
    <member>
        <name>Bob</name>
        <age>27</age>
    </member>
</family>

The easy way to parse XML format in Java is using DOM Parse, you can start with an simple example here

Good luck!


问:
How to bring ajax search onkeyup with jquery
My Script to call ajax

```<code><script language="javascript">
function search_func(value)
{
    $.ajax({
       type: "GET",
       url: "sample.php",
       data: {'search_keyword' : value},
       dataType: "text",
       success: function(msg){
                   //Receiving the result of search here
       }
    });
}
</script>
</code>```

HTML

```<code>   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</code>```

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

答:
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?

```
$(function(){

   // Document is ready

   $("#sample_search").keyup(function()
   {

       $.ajax({
          type: "GET",
          url: "sample.php",
          data: {'search_keyword' : value},
          dataType: "text",
          success: function(msg)
          {
               //Receiving the result of search here
          }
       });

   });

});
```

I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.

ContentLicense: CC BY-SA 3.0

Body:
My Script to call ajax

HTML

   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

Body:
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?

$(function(){

   // Document is ready

   $("#sample_search").keyup(function()
   {

       $.ajax({
          type: "GET",
          url: "sample.php",
          data: {'search_keyword' : value},
          dataType: "text",
          success: function(msg)
          {
               //Receiving the result of search here
          }
       });

   });

});

I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.


问:
Problem with nested ifelse function to subtract specific dates from a date vector
I have the following problem. I have two vectors on with characters (c.vec), one with dates(d.vec). I want to calculate a certain time interval if the char vector has a certain attribute. As the if-statement should check each row, I read that I need to use nested ifelse statements (as for certain months in the date vector, a specific date should be used to calculate the time interval). My ifelse statement should calculate as follows:

1) If the c.vec == 'Tree' and the month of d.vec is after October – then calculate 15.07.YearAfterd.vec - date of d.vec   and overwrite another vector called d.diff (this vector already has numeric values stored in it) with the outcome

2) If the c.vec == 'Tree' and the month of d.vec is after May– then calculate 15.02.YearAfterd.vec - date of d.vec   and overwrite d.diff with the outcome

3) If the c.vec == 'Tree' and the month of d.vec before May – then calculate 15.07.YearOfd.vec- date of d.vec   and overwrite d.diff with the outcome

4) If c.vec =! 'Tree' then just use the value already stored in d.diff and do not overwrite anything

Here is what I tried (however, it just returns NAs) - with an example:

```<code>c.vec <- c('tree','tree','tree','flower','flower')
d.diff <- c(150,80,97,52,74)
d.vec <- as.Date(c('2016-11-24','2017-06-14','2016-02-21','2017-05-07','2016-04-18'))

d.diff <- ifelse(c.vec=='tree',
             # Check if date is after October. The as.Date() part should return 15.07. of the year after d.vec
             ifelse(month(d.vec)>10,d.diff <- as.numeric(as.Date(
               capture.output(cat(year(d.vec)+1,'-07-15')),'%Y -%m-%d')-d.vec),
               # Check if date is after May
               ifelse(month(d.vec)>5,d.diff <- as.numeric(as.Date(
                 capture.output(cat(year(d.vec)+1,'-02-15')),'%Y -%m-%d')-d.vec),
                 # Else, use 15.07. of the year of d.vec to calculate the time difference
                 d.diff <- as.Date(capture.output(cat(year(d.vec),'-07-15')),'%Y -%m-%d')-d.vec)),
             # if c.vec =! tree just use the existing values in d.diff
             d.diff <- d.diff)
</code>```

How do I need to adjust it that I get the specific time differences in the d.diff vector?
I also tried to use store the vectors in a data frame and then use df.name$... to use the entries of the vectors but it just returns NAs as well. Thanks for the help!

答:
We can do this with a simple for loop using only base R

```<code>for (i in seq_along(d.vec)) {
   if (c.vec[i] == "tree") {
     current_date <- d.vec[i]
     current_month <- as.integer(format(current_date, "%m"))
     current_year <- as.integer(format(current_date, "%Y"))

    if (current_month > 10)
      d.diff[i] <-  as.numeric(as.Date(paste0(current_year + 1, "-07-15")) - current_date)
    else if (current_month > 5)
       d.diff[i] <- as.numeric(as.Date(paste0(current_year + 1, "-02-15")) - current_date)
    else
       d.diff[i] <- as.numeric(as.Date(paste0(current_year, "-07-15")) - current_date)
    }
}

d.diff
#[1] 233 246 145  52  74
</code>```

Body:
I have the following problem. I have two vectors on with characters (c.vec), one with dates(d.vec). I want to calculate a certain time interval if the char vector has a certain attribute. As the if-statement should check each row, I read that I need to use nested ifelse statements (as for certain months in the date vector, a specific date should be used to calculate the time interval). My ifelse statement should calculate as follows:

1) If the c.vec == 'Tree' and the month of d.vec is after October – then calculate 15.07.YearAfterd.vec - date of d.vec   and overwrite another vector called d.diff (this vector already has numeric values stored in it) with the outcome

2) If the c.vec == 'Tree' and the month of d.vec is after May– then calculate 15.02.YearAfterd.vec - date of d.vec   and overwrite d.diff with the outcome

3) If the c.vec == 'Tree' and the month of d.vec before May – then calculate 15.07.YearOfd.vec- date of d.vec   and overwrite d.diff with the outcome

4) If c.vec =! 'Tree' then just use the value already stored in d.diff and do not overwrite anything

Here is what I tried (however, it just returns NAs) - with an example:

c.vec <- c('tree','tree','tree','flower','flower')
d.diff <- c(150,80,97,52,74)
d.vec <- as.Date(c('2016-11-24','2017-06-14','2016-02-21','2017-05-07','2016-04-18'))

d.diff <- ifelse(c.vec=='tree',
             # Check if date is after October. The as.Date() part should return 15.07. of the year after d.vec
             ifelse(month(d.vec)>10,d.diff <- as.numeric(as.Date(
               capture.output(cat(year(d.vec)+1,'-07-15')),'%Y -%m-%d')-d.vec),
               # Check if date is after May
               ifelse(month(d.vec)>5,d.diff <- as.numeric(as.Date(
                 capture.output(cat(year(d.vec)+1,'-02-15')),'%Y -%m-%d')-d.vec),
                 # Else, use 15.07. of the year of d.vec to calculate the time difference
                 d.diff <- as.Date(capture.output(cat(year(d.vec),'-07-15')),'%Y -%m-%d')-d.vec)),
             # if c.vec =! tree just use the existing values in d.diff
             d.diff <- d.diff)

How do I need to adjust it that I get the specific time differences in the d.diff vector?
I also tried to use store the vectors in a data frame and then use df.name$... to use the entries of the vectors but it just returns NAs as well. Thanks for the help!

Body:
We can do this with a simple for loop using only base R

for (i in seq_along(d.vec)) {
   if (c.vec[i] == "tree") {
     current_date <- d.vec[i]
     current_month <- as.integer(format(current_date, "%m"))
     current_year <- as.integer(format(current_date, "%Y"))

    if (current_month > 10)
      d.diff[i] <-  as.numeric(as.Date(paste0(current_year + 1, "-07-15")) - current_date)
    else if (current_month > 5)
       d.diff[i] <- as.numeric(as.Date(paste0(current_year + 1, "-02-15")) - current_date)
    else
       d.diff[i] <- as.numeric(as.Date(paste0(current_year, "-07-15")) - current_date)
    }
}

d.diff
#[1] 233 246 145  52  74


问:
Julia: Call previous value within Map function
I have been acclimating myself with the higher order functions like map, filter, and reduce. Honestly, I feel like I'm cheating because the code is so clean! Anyway...

Say I am preforming a map function on an array and the output of anonymous function is dependent on the preceding value. How would i call the previous value?

For instance:

A statement to check if each value has a factor of 3

```<code>julia> A
4-element Array{Int64,1}:
  3
  6
  9
 36

julia> reduce(&, map(x-> x%3 == 0, A))
true
</code>```

How would I call the previous value to check if it is a factor of the current value?

```<code>julia> reduce(&, map( x -> x==A[1] ? true : x % 3 == 0, A))
true

#I want to change the 3 to the previous value like..
psuedo code> reduce(&, map( x -> x==A[1] ? true : x % x[i-1] == 0, A))
</code>```

Any ideas? Or, am I pushing the limits on this?

答:
The map function can take a multivariate function and apply it to multiple arrays. So you can apply your function to properly shifted versions of your array:

```<code>julia> A = [3, 6, 9, 36];

julia> map((x, y) -> x % y == 0, A[2:end], A[1:end-1])
3-element Array{Bool,1}:
  true
 false
  true
</code>```

The ShiftedArrays.jl package provides lead and lag functions to make shifting arrays more convenient:

```<code>julia> using ShiftedArrays

julia> lag(A)
4-element ShiftedArray{Int64,Missing,1,Array{Int64,1}}:
  missing
 3
 6
 9

julia> map((x, x_lag) -> x % x_lag == 0, A, lag(A))
4-element Array{Union{Missing, Bool},1}:
      missing
  true
 false
  true
</code>```

Note that lag introduces a missing value at the beginning of the shifted array. If you want to ensure that your function returns true for the first element of the array, you could modify it like this:

```<code>julia> map((x, y) -> ismissing(y) ? true : x % y == 0, A, lag(A))
4-element Array{Bool,1}:
  true
  true
 false
  true
</code>```

Body:
I have been acclimating myself with the higher order functions like map, filter, and reduce. Honestly, I feel like I'm cheating because the code is so clean! Anyway...

Say I am preforming a map function on an array and the output of anonymous function is dependent on the preceding value. How would i call the previous value?

For instance:

A statement to check if each value has a factor of 3

julia> A
4-element Array{Int64,1}:
  3
  6
  9
 36

julia> reduce(&, map(x-> x%3 == 0, A))
true

How would I call the previous value to check if it is a factor of the current value?

julia> reduce(&, map( x -> x==A[1] ? true : x % 3 == 0, A))
true

#I want to change the 3 to the previous value like..
psuedo code> reduce(&, map( x -> x==A[1] ? true : x % x[i-1] == 0, A))

Any ideas? Or, am I pushing the limits on this?

Body:
The map function can take a multivariate function and apply it to multiple arrays. So you can apply your function to properly shifted versions of your array:

julia> A = [3, 6, 9, 36];

julia> map((x, y) -> x % y == 0, A[2:end], A[1:end-1])
3-element Array{Bool,1}:
  true
 false
  true

The ShiftedArrays.jl package provides lead and lag functions to make shifting arrays more convenient:

julia> using ShiftedArrays

julia> lag(A)
4-element ShiftedArray{Int64,Missing,1,Array{Int64,1}}:
  missing
 3
 6
 9

julia> map((x, x_lag) -> x % x_lag == 0, A, lag(A))
4-element Array{Union{Missing, Bool},1}:
      missing
  true
 false
  true

Note that lag introduces a missing value at the beginning of the shifted array. If you want to ensure that your function returns true for the first element of the array, you could modify it like this:

julia> map((x, y) -> ismissing(y) ? true : x % y == 0, A, lag(A))
4-element Array{Bool,1}:
  true
  true
 false
  true


问:
RegEx for failing subdomains
Basically, I would like to check a valid URL that does not have subdomain on it. I can't seem to figure out the correct regex for it.

Example of URLs that SHOULD match:

example.com

www.example.com

example.co.uk

example.com/page

example.com?key=value

Example of URLs that SHOULD NOT match:

test.example.com

sub.test.example.com

答:
Here, we would start with an expression which is bounded on the right with .com or .co.uk and others, if desired, then we would swipe to left to collect all non-dot chars, add an optional www and https, then we would add a start char ^ which would fail all subdomains:

```<code>^(https?:\/\/)?(www\.)?([^.]+)(\.com|\.co\.uk)(.+|)$
</code>```

Other TLDs can be added to this capturing group:

```<code>(\.com|\.co\.uk|\.net|\.org|\.business|\.edu|\.careers|\.coffee|\.college)
</code>```

And the expression can be modified to:

```<code>^(https?:\/\/)?(www\.)?([^.]+)(\.com|\.co\.uk|\.net|\.org|\.business|\.edu|\.careers|\.coffee|\.college)(.+|)$
</code>```

Flexibility

I can't think of something to make the TLDs too flexible, since this is a validation expression. For instance, if we would simplify it to:

```<code>^(https?:\/\/)?(www\.)?([^.]+)(\.[a-z]+)(\.uk?)?[a-z?=\/]+$
</code>```

it might work for the URLs listed in the question, but it would also pass:

```<code>example.example
</code>```

which is invalid. We can only use this expression:

```<code>^(https?:\/\/)?(www\.)?([^.]+)(\.[a-z]+)(\.uk?)?[a-z?=\/]+$
</code>```

if we would know that what we pass, it is already a URL.

NOT FUNCTIONAL DEMO

Demo

This snippet just shows that how the capturing groups work:

const regex = /^(https?:\/\/)?(www\.)?([^.]+)(\.com|\.co\.uk)(.+|)$/gm;
const str = `example.com
www.example.com
example.co.uk
example.com/page
example.com?key=value

test.example.com
sub.test.example.com`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx Circuit

jex.im visualizes regular expressions:

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

DEMO

Title: RegEx for failing subdomains

Body:
Here, we would start with an expression which is bounded on the right with .com or .co.uk and others, if desired, then we would swipe to left to collect all non-dot chars, add an optional www and https, then we would add a start char ^ which would fail all subdomains:

^(https?:\/\/)?(www\.)?([^.]+)(\.com|\.co\.uk)(.+|)$

Other TLDs can be added to this capturing group:

(\.com|\.co\.uk|\.net|\.org|\.business|\.edu|\.careers|\.coffee|\.college)

And the expression can be modified to:

^(https?:\/\/)?(www\.)?([^.]+)(\.com|\.co\.uk|\.net|\.org|\.business|\.edu|\.careers|\.coffee|\.college)(.+|)$

Flexibility

I can't think of something to make the TLDs too flexible, since this is a validation expression. For instance, if we would simplify it to:

^(https?:\/\/)?(www\.)?([^.]+)(\.[a-z]+)(\.uk?)?[a-z?=\/]+$

it might work for the URLs listed in the question, but it would also pass:

example.example

which is invalid. We can only use this expression:

^(https?:\/\/)?(www\.)?([^.]+)(\.[a-z]+)(\.uk?)?[a-z?=\/]+$

if we would know that what we pass, it is already a URL.

NOT FUNCTIONAL DEMO

Demo

This snippet just shows that how the capturing groups work:

const regex = /^(https?:\/\/)?(www\.)?([^.]+)(\.com|\.co\.uk)(.+|)$/gm;
const str = `example.com
www.example.com
example.co.uk
example.com/page
example.com?key=value

test.example.com
sub.test.example.com`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit

jex.im visualizes regular expressions:

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

DEMO


问:
How to provide the link to vector icon into resourcedictionary?
I'm trying to use vector images in my wpf application. I have an icon "ic_document.xaml" in "Resources" folder, here it is:

```<code><Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Name="Svg63" Width="50"
    Height="50">
  <Canvas Name="Sf1">
    <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="Path2" Fill="#000000"
          Data="M 7 2 V 48 H 43 V 14.59 l -0.28 -0.31 -12 -12 L 30.406 2 Z M 9 4 H 29 V 16 H 41 V 46 H 9 Z M 31 5.4375 39.5625 14 H 31 Z" />
   </Canvas>
</Canvas>
</code>```

I know that if I want to use it in my application then I should create a "ResourceDictionary" and then just copy-paste this code to it. But can I do it more simply and just provide the link to ic_document.xaml ? Something like this

```<code><ResourceDictionary xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Canvas x:Key="IcTest">
     //Link to ic_document.xaml
  </Canvas>
</ResourceDictionary>
</code>```

How can I do it?

答:
Hi first I wanna answer whether u can Link ic_document.xaml The answer is no we cant do something like that but We can create a Style in your XAML file and use it

Resource File

```<code><Style x:Key="MyIcon" TargetType="Path">
            <Setter Property="Data" Value="F1 M 22,12L 26,12L 26,22L 36,22L 36,26L 26,26L 26,36L 22,36L 22,26L 12,26L 12,22L 22,22L 22,12 Z"></Setter>
            <Setter Property="Fill" Value="#000000"></Setter>
        </Style>
</code>```

View

```<code> <Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="50"
    Height="50">
            <Canvas >
                <Path Style="{StaticResource MyIcon}">
                </Path>
            </Canvas>
</code>```

Note if u have multiple themes and need to use DynamicResource then you need to use PathGeometry to set it

Resources File

```<code><PathGeometry x:Key="MyIcon" >
            <PathFigure StartPoint="0,0" >
                <LineSegment Point="0,50"/>
                <LineSegment Point="100,50"/>
                <LineSegment Point="100,20"/>
                <LineSegment Point="80,0"/>
                <LineSegment Point="0,0"/>
            </PathFigure>
        </PathGeometry>
</code>```

View

```<code><Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Name="Svg63" Width="50"
    Height="50">
            <Canvas Name="Sf1">
                <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="Path2" Fill="#000000"
          Data="{DynamicResource MyIcon}" />
            </Canvas>
</code>```

Body:
I'm trying to use vector images in my wpf application. I have an icon "ic_document.xaml" in "Resources" folder, here it is:

<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Name="Svg63" Width="50"
    Height="50">
  <Canvas Name="Sf1">
    <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="Path2" Fill="#000000"
          Data="M 7 2 V 48 H 43 V 14.59 l -0.28 -0.31 -12 -12 L 30.406 2 Z M 9 4 H 29 V 16 H 41 V 46 H 9 Z M 31 5.4375 39.5625 14 H 31 Z" />
   </Canvas>
</Canvas>

I know that if I want to use it in my application then I should create a "ResourceDictionary" and then just copy-paste this code to it. But can I do it more simply and just provide the link to ic_document.xaml ? Something like this

<ResourceDictionary xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Canvas x:Key="IcTest">
     //Link to ic_document.xaml
  </Canvas>
</ResourceDictionary>

How can I do it?

Body:
Hi first I wanna answer whether u can Link ic_document.xaml The answer is no we cant do something like that but We can create a Style in your XAML file and use it

Resource File

<Style x:Key="MyIcon" TargetType="Path">
            <Setter Property="Data" Value="F1 M 22,12L 26,12L 26,22L 36,22L 36,26L 26,26L 26,36L 22,36L 22,26L 12,26L 12,22L 22,22L 22,12 Z"></Setter>
            <Setter Property="Fill" Value="#000000"></Setter>
        </Style>

View

 <Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="50"
    Height="50">
            <Canvas >
                <Path Style="{StaticResource MyIcon}">
                </Path>
            </Canvas>

Note if u have multiple themes and need to use DynamicResource then you need to use PathGeometry to set it

Resources File

<PathGeometry x:Key="MyIcon" >
            <PathFigure StartPoint="0,0" >
                <LineSegment Point="0,50"/>
                <LineSegment Point="100,50"/>
                <LineSegment Point="100,20"/>
                <LineSegment Point="80,0"/>
                <LineSegment Point="0,0"/>
            </PathFigure>
        </PathGeometry>

View

<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Name="Svg63" Width="50"
    Height="50">
            <Canvas Name="Sf1">
                <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="Path2" Fill="#000000"
          Data="{DynamicResource MyIcon}" />
            </Canvas>


答: Try using the jQuery UI autocomplete. Saves you from many low-level coding.</p>

Title: How to bring ajax search onkeyup with jquery


问:
How to regenerate Build Gradle: Module app file
I was working in my Android project, my computer shut off while working with my project when power off. I recently tried to build my project but I couldn't because my Build Gradle : Module app file was corrupt and someone it had another's XML layout code, so I lost all the content of the module app file. How can I regenerate it?

NOTE

I tried to view the local history, unfortunately, I don't have any right structured file as before available on it.

If I would need to make it from scratch, how do I know the structure? (What does it need to have, an specific order and values).

答:
Right-click on the build.gradle file in the Project tool window and select Local History > Show History. You can revert to any saved changes if they exist.

Alternatively, you can delete the corrupted file and start from scratch:

Switch to Project view in the Project tool window

Right-click on the root folder of your module and select New > File

Name it 'build.gradle'

Modify this file as needed (add plugins, defaultConfig, dependencies, etc).

You can use an uncorrupted build.gradle file as reference by creating a new (temporary) Android Studio project and adding a new module to it. Now you have a fresh build.gradle file. From there, it's a matter of adding dependencies and making any other modifications so your code compiles.

As of this writing, the general structure of the build.gradle file for an android library is:

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 28
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    // module dependencies
}
</code>```

Body:
Right-click on the build.gradle file in the Project tool window and select Local History > Show History. You can revert to any saved changes if they exist.

Alternatively, you can delete the corrupted file and start from scratch:

Switch to Project view in the Project tool window

Right-click on the root folder of your module and select New > File

Name it 'build.gradle'

Modify this file as needed (add plugins, defaultConfig, dependencies, etc).

You can use an uncorrupted build.gradle file as reference by creating a new (temporary) Android Studio project and adding a new module to it. Now you have a fresh build.gradle file. From there, it's a matter of adding dependencies and making any other modifications so your code compiles.

As of this writing, the general structure of the build.gradle file for an android library is:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 28
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    // module dependencies
}


问:
I kept on getting Error Parsing Reference on Docker Build
```<code>Sending build context to Docker daemon 7.351 MB
Step 1/12 : FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build
Error parsing reference: "mcr.microsoft.com/dotnet/core/sdk:2.2 AS build" is not a valid repository/tag: invalid reference format
</code>```

This is what i am getting on my console.
It was completely working fine on linux but when i tried the same code on windows, i am getting this error.

答:
When you use AS build, that means you are using multistage build which starts from Docker 17.05, see this.

So, your need to upgrade your docker version, otherwise you will see something like next:

```<code>root@ip-10-23-22-89:/home/ubuntu# docker version
Client:
 Version:      1.13.0
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   49bf474
 Built:        Tue Jan 17 09:50:17 2017
 OS/Arch:      linux/amd64

Server:
 Version:      1.13.0
 API version:  1.25 (minimum version 1.12)
 Go version:   go1.7.3
 Git commit:   49bf474
 Built:        Tue Jan 17 09:50:17 2017
 OS/Arch:      linux/amd64
 Experimental: false
root@ip-10-23-22-89:/home/ubuntu# docker build -t abc:1 .
Sending build context to Docker daemon  21.5 kB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build
Error parsing reference: "mcr.microsoft.com/dotnet/core/sdk:2.2 AS build" is not a valid repository/tag: invalid reference format
</code>```

Body:
Sending build context to Docker daemon 7.351 MB
Step 1/12 : FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build
Error parsing reference: "mcr.microsoft.com/dotnet/core/sdk:2.2 AS build" is not a valid repository/tag: invalid reference format

This is what i am getting on my console.
It was completely working fine on linux but when i tried the same code on windows, i am getting this error.

Body:
When you use AS build, that means you are using multistage build which starts from Docker 17.05, see this.

So, your need to upgrade your docker version, otherwise you will see something like next:

root@ip-10-23-22-89:/home/ubuntu# docker version
Client:
 Version:      1.13.0
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   49bf474
 Built:        Tue Jan 17 09:50:17 2017
 OS/Arch:      linux/amd64

Server:
 Version:      1.13.0
 API version:  1.25 (minimum version 1.12)
 Go version:   go1.7.3
 Git commit:   49bf474
 Built:        Tue Jan 17 09:50:17 2017
 OS/Arch:      linux/amd64
 Experimental: false
root@ip-10-23-22-89:/home/ubuntu# docker build -t abc:1 .
Sending build context to Docker daemon  21.5 kB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build
Error parsing reference: "mcr.microsoft.com/dotnet/core/sdk:2.2 AS build" is not a valid repository/tag: invalid reference format


问:
Django rest framework "Var must be a User Instance" vs "Object of type 'type' is not JSON serializable"
I'm trying to serialize a model having a foreign key "User".
The concerned view snippet is:

```<code>  data = JSONParser().parse(request)
    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        userid = data['supervisor']

        user = User.objects.get(id=userid).__dict__ ## tried case I
        user = User.objects.get(id=userid) ## tried case II
        serializer.save(supervisor=user)
        return JsonResponse(serializer.data, status=201)
</code>```

The serializer is as :

```<code>class SiteSerializer(serializers.ModelSerializer):
supervisor = serializers.RelatedField(source='User', read_only=True)
class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')
</code>```

The model is :

```<code>class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)
</code>```

When I pass supervisor object it says that object of type "Type" is not serializable and when I pass supervisor as dictionary it says that the dict variable supervisor must be a User instance.
How do I sort this out and proceed??

答:
DRF handles most of the data parsing itself and the parsed data can be found in request.data attribute.

```<code># serializers.py
class SiteSerializer(serializers.ModelSerializer):
    <b>supervisor = serializers.RelatedField(read_only=True) # remove "source argument "</b>

    class Meta:
        model = Site
        fields = ('sitename', 'start_date', 'supervisor')

#views.py
<b>from rest_framework.response import Response # use DRF's response class</b>

class Foo(APIView):
    ...

    def post(self, request, *args, **kwargs):
        <b>serializer = SiteSerializer(data=request.data) # use "request.data"</b>
        if serializer.is_valid():
            <b>serializer.save(supervisor=request.user) # pass user instance directly to the serializer/model saving flow using "request.user"</b>
            <b>return Response(serializer.data)</b>
        <b>else:
            return Response(serializer.errors) # show validation errors if any</b></code>```

Body:
I'm trying to serialize a model having a foreign key "User".
The concerned view snippet is:

  data = JSONParser().parse(request)
    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        userid = data['supervisor']

        user = User.objects.get(id=userid).__dict__ ## tried case I
        user = User.objects.get(id=userid) ## tried case II
        serializer.save(supervisor=user)
        return JsonResponse(serializer.data, status=201)

The serializer is as :

class SiteSerializer(serializers.ModelSerializer):
supervisor = serializers.RelatedField(source='User', read_only=True)
class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')

The model is :

class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)

When I pass supervisor object it says that object of type "Type" is not serializable and when I pass supervisor as dictionary it says that the dict variable supervisor must be a User instance.
How do I sort this out and proceed??

Body:
DRF handles most of the data parsing itself and the parsed data can be found in request.data attribute.

# serializers.py
class SiteSerializer(serializers.ModelSerializer):
    supervisor = serializers.RelatedField(read_only=True) # remove "source argument "

    class Meta:
        model = Site
        fields = ('sitename', 'start_date', 'supervisor')

#views.py
from rest_framework.response import Response # use DRF's response class

class Foo(APIView):
    ...

    def post(self, request, *args, **kwargs):
        serializer = SiteSerializer(data=request.data) # use "request.data"
        if serializer.is_valid():
            serializer.save(supervisor=request.user) # pass user instance directly to the serializer/model saving flow using "request.user"
            return Response(serializer.data)
        else:
            return Response(serializer.errors) # show validation errors if any


问:
How do I kill background tasks in Oreo programmatically?
I'm building a mobile app, and I'd like to implement a functionality where I can clean ram memory by killing background tasks in Android Oreo (something similar like CCleaner would do).

I've tried an algorithm I found on a GitHub. But it seemed to only work with Android 5.0

```<code> protected void populateTextViewWithRunningProcesses() {
        // Empty the TextView
        mTextView.setText("");

        // Initialize a new instance of ActivityManager
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);

        // Get a list of RunningAppProcessInfo
        List<AndroidAppProcess> processes = AndroidProcesses.getRunningAppProcesses();

        // Display the number of running processes
        Toast.makeText(mContext, "Running processes : " +
                runningProcesses.size(), Toast.LENGTH_SHORT).show();

        // Loop through the running processes
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            // Get the process name
            mTextView.setText(mTextView.getText() + processInfo.processName + "\n");
        }
    }
</code>```

It only shows my app's own tasks but not other running tasks

答: Android 5.0+ killed getRunningTasks(int) and getRunningAppProcesses(). Both of those methods are now deprecated and only return your application process. You can get a list of running apps using UsageStatsManager. Check this example: https://github.com/googlesamples/android-AppUsageStatistics</p>

Body:
I'm building a mobile app, and I'd like to implement a functionality where I can clean ram memory by killing background tasks in Android Oreo (something similar like CCleaner would do).

I've tried an algorithm I found on a GitHub. But it seemed to only work with Android 5.0

 protected void populateTextViewWithRunningProcesses() {
        // Empty the TextView
        mTextView.setText("");

        // Initialize a new instance of ActivityManager
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);

        // Get a list of RunningAppProcessInfo
        List<AndroidAppProcess> processes = AndroidProcesses.getRunningAppProcesses();

        // Display the number of running processes
        Toast.makeText(mContext, "Running processes : " +
                runningProcesses.size(), Toast.LENGTH_SHORT).show();

        // Loop through the running processes
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            // Get the process name
            mTextView.setText(mTextView.getText() + processInfo.processName + "\n");
        }
    }

It only shows my app's own tasks but not other running tasks


问:
Removing nested api call from for loop
i made an api call to return a set of data(ex: users - list type, with the returned data i created a for loop and and within my for loop i make another api call to get the user's profile detail based on the user's id. I know this isn't the best practice and i was wondering how i could go about refactoring it.

```<code>api.get(...).then(response => {
   this.users = response;
   for(let i=0; i<this.users.length; i++){
     api.get(...this.users[i].id).then(response => {
       if(response.name == this.users[i].name)
         this.newList.push(response);
     })
   }
})
</code>```

and in my html i loop over this.newList to display the info that i need.

How can i remove the nested api call from within the for loop and still get the same results?

答:
Just push array of request into array after that we can use Promise.all() to make a request at a time, then we could create newList based on results array.</p>

```<code> api.get(...).then(response => {
    this.users = response;
    const promises = this.users.map(user => api.get(...user.id))
    const result = Promise.all(promises).then(result => {
        this.newList = results.filter((user, i) => user.name === this.users[i].name)
    })
})
</code>```

Title: Removing nested api call from for loop

Body:
i made an api call to return a set of data(ex: users - list type, with the returned data i created a for loop and and within my for loop i make another api call to get the user's profile detail based on the user's id. I know this isn't the best practice and i was wondering how i could go about refactoring it.

api.get(...).then(response => {
   this.users = response;
   for(let i=0; i<this.users.length; i++){
     api.get(...this.users[i].id).then(response => {
       if(response.name == this.users[i].name)
         this.newList.push(response);
     })
   }
})

and in my html i loop over this.newList to display the info that i need.

How can i remove the nested api call from within the for loop and still get the same results?

Body:
Just push array of request into array after that we can use Promise.all() to make a request at a time, then we could create newList based on results array.

 api.get(...).then(response => {
    this.users = response;
    const promises = this.users.map(user => api.get(...user.id))
    const result = Promise.all(promises).then(result => {
        this.newList = results.filter((user, i) => user.name === this.users[i].name)
    })
})


问:
How to divide each element in a row by corresponding row value?
(I want to divide each element in a row by corresponding row value. Denominator should the value of "Ac" when row element is present.</p>

```<code>Ac    V1  V2  V3   V4  V5  V6  V7
6.6  NA  NA  NA   NA   0  5.6  5.2
8.4  NA  0   82.5 31   0  0    1.1

Output:

V1 V2    V3        V4       V5                            V6               V7
NA 0/8.4 82.5/8.4 31/8.4  (0*6.6+0*6.6)/(6.6+8.4) (5.6*6.6+0*8.4)/(6.6+8.4) (5.2*6.6+1.1*8.4)/(6.6+8.4)
</code>```

答:
Here is one option with tidyverse.  We divide all the columns except the 'Ac' column with the 'Ac', then summarise_all to return  the sum if any non-NA element is present or else return NA

```<code>library(tidyverse)
df %>%
  transmute_at(-1, list(~ ./Ac)) %>%
  summarise_all(list(~ if(all(is.na(.))) NA else sum(.,na.rm = TRUE)))
#  V1 V2       V3       V4 V5        V6        V7
#1 NA  0 9.821429 3.690476  0 0.8484848 0.9188312
</code>```

It can also be done in a single step

```<code>df %>%
  summarise_at(-1, list(~ if(all(is.na(.))) NA else (sum(./Ac, na.rm = TRUE)) ))
#  V1 V2       V3       V4 V5        V6        V7
#1 NA  0 9.821429 3.690476  0 0.8484848 0.9188312
</code>```

Update

Based on the comments,

```<code>df %>%
    summarise_at(-1, list(~ if(all(is.na(.))) NA
       else if(sum(is.na(.)) == 1) (sum(./Ac, na.rm = TRUE))
      else (sum(Ac* ., na.rm = TRUE)/sum(Ac, na.rm = TRUE)) ))
#  V1 V2       V3       V4 V5    V6    V7
#1 NA  0 9.821429 3.690476  0 2.464 2.904
</code>```

Same method can be translated to data.table as well

```<code>library(data.table)
setDT(df)[, lapply(.SD, function(x) if(all(is.na(x))) NA
      else sum(x/Ac, na.rm = TRUE)), .SDcols = 2:ncol(df)]
#   V1 V2       V3       V4 V5        V6        V7
#1: NA  0 9.821429 3.690476  0 0.8484848 0.9188312
</code>```

Updated data.table solution

```<code>setDT(df)[, lapply(.SD, function(x) if(all(is.na(x))) NA
       else if(sum(is.na(x)) == 1) (sum(x/Ac, na.rm = TRUE))
      else (sum(Ac* x, na.rm = TRUE)/sum(Ac, na.rm = TRUE)) ), .SDcols = 2:ncol(df)]
#   V1 V2       V3       V4 V5    V6    V7
#1: NA  0 9.821429 3.690476  0 2.464 2.904
</code>```

data

```<code>df <- structure(list(Ac = c(6.6, 8.4), V1 = c(NA_real_, NA_real_),
    V2 = c(NA, 0), V3 = c(NA, 82.5), V4 = c(NA, 31), V5 = c(0,
    0), V6 = c(5.6, 0), V7 = c(5.2, 1.1)), class = "data.frame",
    row.names = c(NA,
-2L))
</code>```

Body:
(I want to divide each element in a row by corresponding row value. Denominator should the value of "Ac" when row element is present.

Ac    V1  V2  V3   V4  V5  V6  V7
6.6  NA  NA  NA   NA   0  5.6  5.2
8.4  NA  0   82.5 31   0  0    1.1

Output:

V1 V2    V3        V4       V5                            V6               V7
NA 0/8.4 82.5/8.4 31/8.4  (0*6.6+0*6.6)/(6.6+8.4) (5.6*6.6+0*8.4)/(6.6+8.4) (5.2*6.6+1.1*8.4)/(6.6+8.4)

Body:
Here is one option with tidyverse.  We divide all the columns except the 'Ac' column with the 'Ac', then summarise_all to return  the sum if any non-NA element is present or else return NA

library(tidyverse)
df %>%
  transmute_at(-1, list(~ ./Ac)) %>%
  summarise_all(list(~ if(all(is.na(.))) NA else sum(.,na.rm = TRUE)))
#  V1 V2       V3       V4 V5        V6        V7
#1 NA  0 9.821429 3.690476  0 0.8484848 0.9188312

It can also be done in a single step

df %>%
  summarise_at(-1, list(~ if(all(is.na(.))) NA else (sum(./Ac, na.rm = TRUE)) ))
#  V1 V2       V3       V4 V5        V6        V7
#1 NA  0 9.821429 3.690476  0 0.8484848 0.9188312

Update

Based on the comments,

df %>%
    summarise_at(-1, list(~ if(all(is.na(.))) NA
       else if(sum(is.na(.)) == 1) (sum(./Ac, na.rm = TRUE))
      else (sum(Ac* ., na.rm = TRUE)/sum(Ac, na.rm = TRUE)) ))
#  V1 V2       V3       V4 V5    V6    V7
#1 NA  0 9.821429 3.690476  0 2.464 2.904

Same method can be translated to data.table as well

library(data.table)
setDT(df)[, lapply(.SD, function(x) if(all(is.na(x))) NA
      else sum(x/Ac, na.rm = TRUE)), .SDcols = 2:ncol(df)]
#   V1 V2       V3       V4 V5        V6        V7
#1: NA  0 9.821429 3.690476  0 0.8484848 0.9188312

Updated data.table solution

setDT(df)[, lapply(.SD, function(x) if(all(is.na(x))) NA
       else if(sum(is.na(x)) == 1) (sum(x/Ac, na.rm = TRUE))
      else (sum(Ac* x, na.rm = TRUE)/sum(Ac, na.rm = TRUE)) ), .SDcols = 2:ncol(df)]
#   V1 V2       V3       V4 V5    V6    V7
#1: NA  0 9.821429 3.690476  0 2.464 2.904

data

df <- structure(list(Ac = c(6.6, 8.4), V1 = c(NA_real_, NA_real_),
    V2 = c(NA, 0), V3 = c(NA, 82.5), V4 = c(NA, 31), V5 = c(0,
    0), V6 = c(5.6, 0), V7 = c(5.2, 1.1)), class = "data.frame",
    row.names = c(NA,
-2L))


问:
web scraping with Beautifulsoup - output unintentionally merging words (e.g., ThisHappens)
I am trying to web scrape some research study abstracts and some words are just being merged together. Unfortunately, it's not consistent enough where I can just do something like outputexample.replace("WordMerge","").

For example, in the URL provided in my code, the first line in the output is:

```<code>AbstractsPublic AbstractDownload this abstract: English (pdf) | Español (pdf) | Audio Recording (mp3)
</code>```

I would like to prevent this from happening and maintain as much of the original text and format as possible.

```<code> import requests
 import time
 from bs4 import BeautifulSoup
 import re

 urlsummary ='https://www.pcori.org/research-results/2013/testing-new-
 ways-schedule-appointments-community-health-centers-help-patients'
 html = requests.get(urlsummary).content
 soup = BeautifulSoup(html, 'lxml')

 abstract = soup.find(class_='pane pane--node').get_text()
 print(abstract)
</code>```

答:
Just use

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

From the docs:

You can specify a string to be used to join the bits of text together:

Body:
I am trying to web scrape some research study abstracts and some words are just being merged together. Unfortunately, it's not consistent enough where I can just do something like outputexample.replace("WordMerge","").

For example, in the URL provided in my code, the first line in the output is:

AbstractsPublic AbstractDownload this abstract: English (pdf) | Español (pdf) | Audio Recording (mp3)

I would like to prevent this from happening and maintain as much of the original text and format as possible.

 import requests
 import time
 from bs4 import BeautifulSoup
 import re

 urlsummary ='https://www.pcori.org/research-results/2013/testing-new-
 ways-schedule-appointments-community-health-centers-help-patients'
 html = requests.get(urlsummary).content
 soup = BeautifulSoup(html, 'lxml')

 abstract = soup.find(class_='pane pane--node').get_text()
 print(abstract)

Body:
Just use

.get_text(" ")

From the docs:

You can specify a string to be used to join the bits of text together:


问:
replace a string with special " ' "
I want to find and replace string with special symbol " ' " using gsub of awk.

I tried escape the symbol with \ and even \\ but my code returns > .

```<code>awk '{ gsub("%27","'",$1); print $1 }' file.txt
</code>```

file.txt:

```<code>%27SWAY%27
</code>```

I want above to be replaced to 'SWAY'

答:
You can use BASH string expansion if your BASH is a recent one:

```<code>$ echo "%27SWAY%27" | awk $'{gsub("%27","\'",$1); print $1 }'
'SWAY'
</code>```

The "$" in front of '{..}' interprets the "\'" for awk.

Title: replace a string with special " ' "

Body:
I want to find and replace string with special symbol " ' " using gsub of awk.

I tried escape the symbol with \ and even \\ but my code returns > .

awk '{ gsub("%27","'",$1); print $1 }' file.txt

file.txt:

%27SWAY%27

I want above to be replaced to 'SWAY'

Body:
You can use BASH string expansion if your BASH is a recent one:

$ echo "%27SWAY%27" | awk $'{gsub("%27","\'",$1); print $1 }'
'SWAY'

The "$" in front of '{..}' interprets the "\'" for awk.


问:
Group Role-based Authorization In Enterprise Applications
I have used Azure App registrations to register my app. In the Manifest, I added appRoles. I then use Azure Enterprise applications to add Users and Groups to the appRoles I created. Do I need to update "groupMembershipClaims": "SecurityGroup" in the Manifest because I add Groups in Enterprise application?  Can I use role-based claims for groups in Enterprise Applications? </p>

答:
You might be mixing up two completely different concepts here. I'll give some details regarding each one below and then you can decide whether you really need group claims for your application or not.

My guess is that you're interested in roles claim, so you don't need to update your app manifest to include "groupMembershipClaims": "SecurityGroup", but you are the best judge for your application's requirement.

Application Roles

You can define application roles by editing app manifest and adding appRoles. Now you can assign these roles to individual users or even to Azure AD groups.

Assigning Roles to Individual Users

You can assign roles to individual users by going to Enterprise Applications and then using portal UI. It looks like you've already done this for your app. When a user signs in to your application, the incoming access token contains role claims for the user. e.g. "roles": ["MyAppCustomRole1"]

Assigning Roles to Azure AD Groups

You can assign an application role to Azure AD Group (if you have Azure AD Premium). This can be convenient especially when dealing with a large number of users. This way you don't need to assign appRole to individual users but can bulk assign by the virtue of their group membership.

If this is what you're looking to do then you don't need to update your app manifest to include "groupMembershipClaims": "SecurityGroup"

Sample Code - Authorization in a web app using Azure AD application roles & role claims

Microsoft Docs - Application roles

Group Claims

You can enable group claims to come in as part of the access token for your application by editing your application's manifest (this can be done directly in Azure Portal) and setting "groupMembershipClaims" property to "All" or "SecurityGroup" as needed.

Once application manifest is updated as mentioned, you can get Group Id's as part of claims. Here's a quick sample for a decoded JWT token. Notice that this is a completely different claim as compared to the roles claim explained earlier.

Sample Code - Authorization in a web app using Azure AD groups & group claims

Groups v/s Roles

Do understand that Azure AD Groups and their membership is completely separate from any single application.

Lifetime of an Azure AD Group may also be different, i.e. a group may continue to exist long after an application is removed or no longer needed.

Application Roles on the other hand are very closely related to one specific application.

For some applications the authorization strategy is to check for user's group membership instead of Application specific role. I have also seen cases where applications make authorization decisions based on a combination of app specific role and the groups that a user belongs to.

On a side note, to ensure that the token size doesn't exceed HTTP header size limits, Azure AD limits the number of objectIds that it includes in the groups claim. If a user is member of more groups than the overage limit (150 for SAML tokens, 200 for JWT tokens), then Azure AD does not emit the groups claim in the token. Instead, it includes an overage claim in the token that indicates to the application to query the Graph API to retrieve the user's group membership.

Other related SO Posts:

ASP.NET mvc and azure active directory security group based authorization

Azure Active Directory Integration with Custom RBAC

How to check if a user is in an AD group via Azure AD?


问:
AttributeError: 'UUID' object has no attribute 'replace' when using backend-agnostic GUID type
I want to have a primary key id with type uuid in a Postgresql database using SQLAlchemy 1.1.5, connecting to the database with the pg8000 adapter. I used the Backend-agnostic GUID Type recipe from the SQLAlchemy documentation.

When I want to insert into the database, I get the following error

```<code>  File ".../guid.py", line ???, in process_result_value
    return uuid.UUID(value)
  File "/usr/lib/python2.7/uuid.py", line 131, in __init__
    hex = hex.replace('urn:', '').replace('uuid:', '')
AttributeError: 'UUID' object has no attribute 'replace'
</code>```

my model looks like this

```<code>from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from guid import GUID
import uuid

base = declarative_base()

class Item(base):
    __tablename__ = 'item'

    id = Column(GUID(), default=uuid.uuid4, nullable=False, unique=True, primary_key=True)
    name = Column(String)
    description = Column(String)

    def __repr__(self):
        return "<Item(name='%s', description='%s')>" % (self.name, self.description)
</code>```

My resource or controller looks like this

```<code>data = req.params
item = Item(name=data['name'], description=data['description'])

self.session.add(item)
self.session.commit()
</code>```

答:
I had this issue affecting my ORM without using forms.  I was running psycopg2.  The fix for me was to:

```<code>sudo pip install psycopg2-binary
</code>```

After restarting apache, I haven't see the error again as of psycopg2-binary version 2.7.5+

Body:
I want to have a primary key id with type uuid in a Postgresql database using SQLAlchemy 1.1.5, connecting to the database with the pg8000 adapter. I used the Backend-agnostic GUID Type recipe from the SQLAlchemy documentation.

When I want to insert into the database, I get the following error

  File ".../guid.py", line ???, in process_result_value
    return uuid.UUID(value)
  File "/usr/lib/python2.7/uuid.py", line 131, in __init__
    hex = hex.replace('urn:', '').replace('uuid:', '')
AttributeError: 'UUID' object has no attribute 'replace'

my model looks like this

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from guid import GUID
import uuid

base = declarative_base()

class Item(base):
    __tablename__ = 'item'

    id = Column(GUID(), default=uuid.uuid4, nullable=False, unique=True, primary_key=True)
    name = Column(String)
    description = Column(String)

    def __repr__(self):
        return "<Item(name='%s', description='%s')>" % (self.name, self.description)

My resource or controller looks like this

data = req.params
item = Item(name=data['name'], description=data['description'])

self.session.add(item)
self.session.commit()

Body:
I had this issue affecting my ORM without using forms.  I was running psycopg2.  The fix for me was to:

sudo pip install psycopg2-binary

After restarting apache, I haven't see the error again as of psycopg2-binary version 2.7.5+


问:
Getting a null object exception when using an interface
I have created a shopping cart via recyclerview. Each viewholder also has a + and - button to add or remove quantity. This functionality is done in the adapter and I have to notify the parent fragment of the updated total amount. This last bit is done via an interface. The problem is, I am getting the following error:

```<code>Process: com.ecomm.market, PID: 6630
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.ecomm.market.SelectionAdapter$OnUpdateCartListener.onUpdateCart(int)' on a null object reference
        at com.ecomm.market.SelectionAdapter$ViewHolder$1.onClick(SelectionAdapter.java:103)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

The selected item and corresponding quantity are stored in a hashmap that I convert to an array to populate the recycler view cart. This is what the relevant part of my main fragment MenuFragment looks like:

```<code>
                // Using the adapter interface to add items to cart and adding up total amount
                menuItemAdapter.setOnAddToCartListener(new MenuItemAdapter.OnAddToCartListener() {
                    @Override
                    public void onAddToCart(final HashMap selectionItemsHashMap) {

                        setupSelectionRecycler(menuView);
                        totalAmount = mapToArray(selectionItemsHashMap);

                            selectionAdapter = new SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

                        selectionRecycler.setAdapter(selectionAdapter);
                        cartItemsHashmap = selectionItemsHashMap;

                        selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                            @Override
                            public void onUpdateCart(int updatedTotalAmount) {

                                String stringTotalAmount = Integer.toString(updatedTotalAmount);
                                Log.d(TAG, "received total:" +stringTotalAmount);
                                tvTotalAmount.setText("$"+ stringTotalAmount);
                                totalAmount = updatedTotalAmount;
                            }
                        });
                    }
                });
            }
</code>```

And here is an excerpt from my adapter SelectionAdapter:

```<code>public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.ViewHolder> {

    private static final String TAG = SelectionAdapter.class.getSimpleName();

    private ArrayList<SelectionItem> selectionItemArrayList = new ArrayList<>();
    public HashMap<String, Integer> selectionItemsHashMap = new HashMap<String, Integer>();
    public int totalAmount;

    private OnUpdateCartListener updateCartListener;

    public interface OnUpdateCartListener {
        void onUpdateCart(int totalAmount);
    }

    public void setUpdateCartListener(OnUpdateCartListener updateCartListener) {
        this.updateCartListener = updateCartListener;
    }

    public SelectionAdapter(ArrayList<SelectionItem> selectionItemArrayList, HashMap<String, Integer> selectionItemsHashMap, int currentTotalAmount) {
        this.selectionItemArrayList = selectionItemArrayList;
        this.selectionItemsHashMap = selectionItemsHashMap;
        this.totalAmount = currentTotalAmount;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.selection_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
        String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
        viewHolder.tvDishQuantity.setText(quantity);
    }

    @Override
    public int getItemCount() {
        return selectionItemArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvSelectItem, tvDishQuantity;
        ImageView addQuantity, subtractQuantity, deleteItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvSelectItem = itemView.findViewById(R.id.dish_selection);
            tvDishQuantity = itemView.findViewById(R.id.dish_quantity);

            addQuantity = itemView.findViewById(R.id.button_add);
            subtractQuantity = itemView.findViewById(R.id.button_subtract);
            deleteItem = itemView.findViewById(R.id.delete_item);

            addQuantity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Find the name of the menu item
                    int position = getAdapterPosition();
                    String itemName = selectionItemArrayList.get(position).getSelectionName();

                    // Increase quantity
                    int currentQuantity = selectionItemsHashMap.get(itemName);

                    currentQuantity += 1;
                    // Update the hashmap with the new quantity
                    selectionItemsHashMap.put(itemName,currentQuantity);

                    //Update total amount
                    for (Object name: selectionItemsHashMap.keySet()) {
                        String key = (String) name;
                        if (key.equals(selectionItemArrayList.get(position).getSelectionName())) {
                            int eachPrice = Integer.parseInt(selectionItemArrayList.get(position).getSelectionPrice());
                            totalAmount += eachPrice;
                        }
                    }
                    // Display the new quantity
                    String stringCurrentQuantity = Integer.toString(currentQuantity);
                    tvDishQuantity.setText(stringCurrentQuantity);
                    //updateCartListener.onUpdateCart(totalAmount);
                }
            });
}
</code>```

EDIT
A couple of points:
- When the cart is initially filled, I use this same code and it works fine.
- The problem occurs once the user returns to the cart and I have to repopulate it from a bundle. Everything works fine, except when the user goes straight to the cart and attempts to alter the quantity from there.

答: You need to instantiate your updateCartListener begfore you use it. Do updateCartListener = new WhatverClassThatImplementsYourInterafce() before you use it or make your method to override Default if you are using Java 8 using the new FunctionalInterface in java.util.Function.  </p>

Body:
I have created a shopping cart via recyclerview. Each viewholder also has a + and - button to add or remove quantity. This functionality is done in the adapter and I have to notify the parent fragment of the updated total amount. This last bit is done via an interface. The problem is, I am getting the following error:

Process: com.ecomm.market, PID: 6630
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.ecomm.market.SelectionAdapter$OnUpdateCartListener.onUpdateCart(int)' on a null object reference
        at com.ecomm.market.SelectionAdapter$ViewHolder$1.onClick(SelectionAdapter.java:103)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

The selected item and corresponding quantity are stored in a hashmap that I convert to an array to populate the recycler view cart. This is what the relevant part of my main fragment MenuFragment looks like:

                // Using the adapter interface to add items to cart and adding up total amount
                menuItemAdapter.setOnAddToCartListener(new MenuItemAdapter.OnAddToCartListener() {
                    @Override
                    public void onAddToCart(final HashMap selectionItemsHashMap) {

                        setupSelectionRecycler(menuView);
                        totalAmount = mapToArray(selectionItemsHashMap);

                            selectionAdapter = new SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

                        selectionRecycler.setAdapter(selectionAdapter);
                        cartItemsHashmap = selectionItemsHashMap;

                        selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                            @Override
                            public void onUpdateCart(int updatedTotalAmount) {

                                String stringTotalAmount = Integer.toString(updatedTotalAmount);
                                Log.d(TAG, "received total:" +stringTotalAmount);
                                tvTotalAmount.setText("$"+ stringTotalAmount);
                                totalAmount = updatedTotalAmount;
                            }
                        });
                    }
                });
            }

And here is an excerpt from my adapter SelectionAdapter:

public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.ViewHolder> {

    private static final String TAG = SelectionAdapter.class.getSimpleName();

    private ArrayList<SelectionItem> selectionItemArrayList = new ArrayList<>();
    public HashMap<String, Integer> selectionItemsHashMap = new HashMap<String, Integer>();
    public int totalAmount;

    private OnUpdateCartListener updateCartListener;

    public interface OnUpdateCartListener {
        void onUpdateCart(int totalAmount);
    }

    public void setUpdateCartListener(OnUpdateCartListener updateCartListener) {
        this.updateCartListener = updateCartListener;
    }

    public SelectionAdapter(ArrayList<SelectionItem> selectionItemArrayList, HashMap<String, Integer> selectionItemsHashMap, int currentTotalAmount) {
        this.selectionItemArrayList = selectionItemArrayList;
        this.selectionItemsHashMap = selectionItemsHashMap;
        this.totalAmount = currentTotalAmount;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.selection_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
        String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
        viewHolder.tvDishQuantity.setText(quantity);
    }

    @Override
    public int getItemCount() {
        return selectionItemArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvSelectItem, tvDishQuantity;
        ImageView addQuantity, subtractQuantity, deleteItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvSelectItem = itemView.findViewById(R.id.dish_selection);
            tvDishQuantity = itemView.findViewById(R.id.dish_quantity);

            addQuantity = itemView.findViewById(R.id.button_add);
            subtractQuantity = itemView.findViewById(R.id.button_subtract);
            deleteItem = itemView.findViewById(R.id.delete_item);

            addQuantity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Find the name of the menu item
                    int position = getAdapterPosition();
                    String itemName = selectionItemArrayList.get(position).getSelectionName();

                    // Increase quantity
                    int currentQuantity = selectionItemsHashMap.get(itemName);

                    currentQuantity += 1;
                    // Update the hashmap with the new quantity
                    selectionItemsHashMap.put(itemName,currentQuantity);

                    //Update total amount
                    for (Object name: selectionItemsHashMap.keySet()) {
                        String key = (String) name;
                        if (key.equals(selectionItemArrayList.get(position).getSelectionName())) {
                            int eachPrice = Integer.parseInt(selectionItemArrayList.get(position).getSelectionPrice());
                            totalAmount += eachPrice;
                        }
                    }
                    // Display the new quantity
                    String stringCurrentQuantity = Integer.toString(currentQuantity);
                    tvDishQuantity.setText(stringCurrentQuantity);
                    //updateCartListener.onUpdateCart(totalAmount);
                }
            });
}

EDIT
A couple of points:
- When the cart is initially filled, I use this same code and it works fine.
- The problem occurs once the user returns to the cart and I have to repopulate it from a bundle. Everything works fine, except when the user goes straight to the cart and attempts to alter the quantity from there.


问:
How to efficiently find a specific substring in PHP?
OK, I know how to do this but I'm interested in better/more elegant solutions (if any) for this problem.

Imagine I have the following string :

Mozilla/4.0 (compatible; MSIE 7.0;
  Windows NT 5.1; Trident/4.0; GTB6.6;
  Mozilla/4.0 (compatible; MSIE 6.0;
  Windows NT 5.1; SV1) ; .NET CLR
  1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)

I'm interested to find the highest MSIE version in that string (in that case 7.0).

Currently I use explode and preg_match a couple of times in combination with str_replace then I loop between matches and then compare the version string. It works but it's far from elegant. Any ideas on how to improve this?

Keep in mind that:

The string can have any number of MSIE occurrences (or even none)

MSIE is case insensitive

MSIE is followed by a white space (space, tab...) then by the version. The version can contain number letters and dots. The version string is ended by either a white space, a ; or the end of the line.

Thanks!

答:
Something like this:</p>

```<code>$str = "Mozilla/4.0 (compatible; msie 7.0; Windows NT 5.1; Trident/4.0; GTB6.6; Mozilla/4.0 (compatible; MSIE 7.1; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";

preg_match_all('/MSIE\s([\d.]+);/i', $str, $matches);

if(!empty($matches[1])){
    echo "Max version found:" . max($matches[1]);
}else{
    echo "None found";
}
</code>```

Body:
Something like this:

$str = "Mozilla/4.0 (compatible; msie 7.0; Windows NT 5.1; Trident/4.0; GTB6.6; Mozilla/4.0 (compatible; MSIE 7.1; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";

preg_match_all('/MSIE\s([\d.]+);/i', $str, $matches);

if(!empty($matches[1])){
    echo "Max version found:" . max($matches[1]);
}else{
    echo "None found";
}


问:
The argparse code snippet only print part log
I have a code for testing argparse module function:

```<code>import argparse

parser = argparse.ArgumentParser()
parser.description='give me two number, I will return the product'
parser.add_argument("-a","--ParA", help="I am A",type=int)
parser.add_argument("-b","--ParB", help="I am B",type=int)
args = parser.parse_args()
if args.ParA:
    print("A is: ",args.ParA)
if args.ParB:
    print("B is:",args.ParB)
if args.ParA and args.ParB:
    print("the product is: ",args.ParA*args.ParB)

print('over.')
</code>```

but when I run it in my PyCharm, there only print the over.

答:
this is because you run the python file did not pass any params.

you shouldn't run it directly.

you can run it in a terminal like this:

```<code>$ python3 test11.py -a 1 -b 123
</code>```

Body:
I have a code for testing argparse module function:

import argparse

parser = argparse.ArgumentParser()
parser.description='give me two number, I will return the product'
parser.add_argument("-a","--ParA", help="I am A",type=int)
parser.add_argument("-b","--ParB", help="I am B",type=int)
args = parser.parse_args()
if args.ParA:
    print("A is: ",args.ParA)
if args.ParB:
    print("B is:",args.ParB)
if args.ParA and args.ParB:
    print("the product is: ",args.ParA*args.ParB)

print('over.')

but when I run it in my PyCharm, there only print the over.

Body:
this is because you run the python file did not pass any params.

you shouldn't run it directly.

you can run it in a terminal like this:

$ python3 test11.py -a 1 -b 123


问:
How to dynamically auto populate a input field uisng Nodejs and MySQL?
I have a field in my website where I want users to enter book names that they can checkout from the database. I want it so that when they start typing the names I want suggestions or drop down under the input box matching the name of the book they are typing.

Is it possible to achieve something like this? I have a books table in my MySQL database and I am using Nodejs as my backend. I have searched a lot online but did not find anything related to this online. Therefore, I decided to ask the question here.

答:
You have to send AJAX request with type GET and send the typed character to the Backend.
and in backend you have to do query for ex :select * from book where name like %input%
Then you have to return the result as an array to the front-end.
Finally, in your front-end code you have to render the result array under the input.
Also, you can use any ready jquery plugin to do this task in front-end code.


问:
How to install memcached from binaries and include in c file
I am trying to install memcached on ubuntu 16.04. I need to install it manually as I want to modify the files. I also don't want to install it locally as my changes might not be what other people want from their memcached.

I have tried following the instructions from the github https://github.com/memcached/memcached/wiki/Install (changing the prefix and libevent path to be in my home directory).

Libevent installation:

./configure --prefix=/path/to/home/local_include

make

make install

This seemed to work as the memcached config did not complain.

memcached installation:

wget https://memcached.org/latest

tar -zxf memcached-1.5.13.tar.gz

./configure --prefix=/path/to/home/local_include --with-libevent=/path/to/home/local_include

make

make test

make install

Doing this I saw no errors. This is the result when I finished make install:

```<code> make  install-recursive
 make[1]: Entering directory `/path/to/home/memcached-1.5.13'
 Making install in doc
 make[2]: Entering directory `/path/to/home/memcached-1.5.13/doc'
 make  install-am
 make[3]: Entering directory `/path/to/home/memcached-1.5.13/doc'
 make[4]: Entering directory `/path/to/home/memcached-1.5.13/doc'
 make[4]: Nothing to be done for `install-exec-am'.
  /usr/bin/mkdir -p '/path/to/home/local_includes/share/man/man1'
  /usr/bin/install -c -m 644 memcached.1 '/path/to/home/local_includes/share/man/man1'
 make[4]: Leaving directory `/path/to/home/memcached-1.5.13/doc'
 make[3]: Leaving directory `/path/to/home/memcached-1.5.13/doc'
 make[2]: Leaving directory `/path/to/home/memcached-1.5.13/doc'
 make[2]: Entering directory `/path/to/home/memcached-1.5.13'
 make[3]: Entering directory `/path/to/home/memcached-1.5.13'
  /usr/bin/mkdir -p '/path/to/home/local_includes/bin'
   /usr/bin/install -c memcached '/path/to/home/local_includes/bin'
  /usr/bin/mkdir -p '/path/to/home/local_includes/include/memcached'
  /usr/bin/install -c -m 644 protocol_binary.h '/path/to/home/local_includes/include/memcached'
 make[3]: Leaving directory `/path/to/home/memcached-1.5.13'
 make[2]: Leaving directory `/path/to/home/memcached-1.5.13'
 make[1]: Leaving directory `/path/to/home/memcached-1.5.13'
</code>```

when I run ps ax | grep memcached however no trace of the program being installed is apparent.

I also tried reinstalling and change the make install instruction to:

make install --prefix=PREFIX

and

make install --prefix=/path/to/home/local_lib

though neither of them were registered as acceptable arguments (though the INSTALL instructions seemed to indicate they would be).

If anyone has any ideas I would appreciate them. Thanks.

答:
You built the binary but have not started it.

Try starting it via:
sudo service memcached restart

If that doesn't work, then run this:
sudo /etc/init.d/memcached restart

Body:
I am trying to install memcached on ubuntu 16.04. I need to install it manually as I want to modify the files. I also don't want to install it locally as my changes might not be what other people want from their memcached.

I have tried following the instructions from the github https://github.com/memcached/memcached/wiki/Install (changing the prefix and libevent path to be in my home directory).

Libevent installation:

./configure --prefix=/path/to/home/local_include

make

make install

This seemed to work as the memcached config did not complain.

memcached installation:

wget https://memcached.org/latest

tar -zxf memcached-1.5.13.tar.gz

./configure --prefix=/path/to/home/local_include --with-libevent=/path/to/home/local_include

make

make test

make install

Doing this I saw no errors. This is the result when I finished make install:

 make  install-recursive
 make[1]: Entering directory `/path/to/home/memcached-1.5.13'
 Making install in doc
 make[2]: Entering directory `/path/to/home/memcached-1.5.13/doc'
 make  install-am
 make[3]: Entering directory `/path/to/home/memcached-1.5.13/doc'
 make[4]: Entering directory `/path/to/home/memcached-1.5.13/doc'
 make[4]: Nothing to be done for `install-exec-am'.
  /usr/bin/mkdir -p '/path/to/home/local_includes/share/man/man1'
  /usr/bin/install -c -m 644 memcached.1 '/path/to/home/local_includes/share/man/man1'
 make[4]: Leaving directory `/path/to/home/memcached-1.5.13/doc'
 make[3]: Leaving directory `/path/to/home/memcached-1.5.13/doc'
 make[2]: Leaving directory `/path/to/home/memcached-1.5.13/doc'
 make[2]: Entering directory `/path/to/home/memcached-1.5.13'
 make[3]: Entering directory `/path/to/home/memcached-1.5.13'
  /usr/bin/mkdir -p '/path/to/home/local_includes/bin'
   /usr/bin/install -c memcached '/path/to/home/local_includes/bin'
  /usr/bin/mkdir -p '/path/to/home/local_includes/include/memcached'
  /usr/bin/install -c -m 644 protocol_binary.h '/path/to/home/local_includes/include/memcached'
 make[3]: Leaving directory `/path/to/home/memcached-1.5.13'
 make[2]: Leaving directory `/path/to/home/memcached-1.5.13'
 make[1]: Leaving directory `/path/to/home/memcached-1.5.13'

when I run ps ax | grep memcached however no trace of the program being installed is apparent.

I also tried reinstalling and change the make install instruction to:

make install --prefix=PREFIX

and

make install --prefix=/path/to/home/local_lib

though neither of them were registered as acceptable arguments (though the INSTALL instructions seemed to indicate they would be).

If anyone has any ideas I would appreciate them. Thanks.


答:
Is there local history available ?

Try right clicking the faulty gradle file / XML file / Java file  and checking Local History -> Show History

If you can fetch the local history, right click the history entry and click revert

Title: How to regenerate Build Gradle: Module app file

Body:
I was working in my Android project, my computer shut off while working with my project when power off. I recently tried to build my project but I couldn't because my Build Gradle : Module app file was corrupt and someone it had another's XML layout code, so I lost all the content of the module app file. How can I regenerate it?

NOTE

I tried to view the local history, unfortunately, I don't have any right structured file as before available on it.

If I would need to make it from scratch, how do I know the structure? (What does it need to have, an specific order and values).