问:
Why are bars missing in my stacked bar chart -- Python w/matplotlib
all.

I am trying to create a stacked bar chart built using time series data. My issue -- if I plot my data as time series (using lines) then everything works fine and I get a (messy) time series graph that includes correct dates. However, if I instead try to plot this as a stacked bar chart, my dates disappear and none of my bars appear.

I have tried messing with the indexing, height, and width of the bars. No luck.

Here is my code:

```<code>import pylab
import pandas as pd
import matplotlib.pyplot as plt

df1= pd.read_excel('pathway/filename.xls')
df1.set_index('TIME', inplace=True)

ax = df1.plot(kind="Bar", stacked=True)
ax.set_xlabel("Date")
ax.set_ylabel("Change in Yield")
df1.sum(axis=1).plot( ax=ax, color="k", title='Historical Decomposition -- 1 year -- One-Quarter Revision')
plt.axhline(y=0, color='r', linestyle='-')
plt.show()
</code>```

If i change
ax = df1.plot(kind="Bar", stacked=True)

to ax = df1.plot(kind="line", stacked=False)

I get:

if instead I use ax = df1.plot(kind="Bar", stacked=True)

I get:

Any thoughts here?

答:
Without knowing what the data looks like, I'd try something like this:

```<code>#Import data here and generate DataFrame

print(df.head(5))

               A     B     C     D
DATE
2020-01-01 -0.01  0.06  0.40  0.45
2020-01-02 -0.02  0.05  0.39  0.42
2020-01-03 -0.03  0.04  0.38  0.39
2020-01-04 -0.04  0.03  0.37  0.36
2020-01-05 -0.05  0.02  0.36  0.33

f, ax = plt.subplots()
ax.bar(df.index, df['A'])
ax.bar(df.index, df['B'])
ax.bar(df.index, df['C'], bottom=df['B'])
ax.plot(df.index, df['D'], color='black', linewidth=2)
ax.set_xlabel('Date')
ax.set_ylabel('Change in Yield')
ax.axhline(y=0, color='r')
ax.set_xticks([])
ax.legend()
plt.show()

</code>```

Edit:: Ok, I've found a way looking at this post here:
Plot Pandas DataFrame as Bar and Line on the same one chart

Try resetting the index so that it is a separate column. In my example, it is called 'DATE'. Then try:

```<code>ax = df[['DATE','D']].plot(x='DATE',color='black')
df[['DATE','A','B','C']].plot(x='DATE', kind='bar',stacked=True,ax=ax)
ax.axhline(y=0, color='r')
ax.set_xticks([])
ax.set_xlabel('Date')
ax.set_ylabel('Change in Yield')
ax.legend()
plt.show()
</code>```

Body:
all.

I am trying to create a stacked bar chart built using time series data. My issue -- if I plot my data as time series (using lines) then everything works fine and I get a (messy) time series graph that includes correct dates. However, if I instead try to plot this as a stacked bar chart, my dates disappear and none of my bars appear.

I have tried messing with the indexing, height, and width of the bars. No luck.

Here is my code:

import pylab
import pandas as pd
import matplotlib.pyplot as plt

df1= pd.read_excel('pathway/filename.xls')
df1.set_index('TIME', inplace=True)

ax = df1.plot(kind="Bar", stacked=True)
ax.set_xlabel("Date")
ax.set_ylabel("Change in Yield")
df1.sum(axis=1).plot( ax=ax, color="k", title='Historical Decomposition -- 1 year -- One-Quarter Revision')
plt.axhline(y=0, color='r', linestyle='-')
plt.show()

If i change
ax = df1.plot(kind="Bar", stacked=True)

to ax = df1.plot(kind="line", stacked=False)

I get:

if instead I use ax = df1.plot(kind="Bar", stacked=True)

I get:

Any thoughts here?

Body:
Without knowing what the data looks like, I'd try something like this:

#Import data here and generate DataFrame

print(df.head(5))

               A     B     C     D
DATE
2020-01-01 -0.01  0.06  0.40  0.45
2020-01-02 -0.02  0.05  0.39  0.42
2020-01-03 -0.03  0.04  0.38  0.39
2020-01-04 -0.04  0.03  0.37  0.36
2020-01-05 -0.05  0.02  0.36  0.33

f, ax = plt.subplots()
ax.bar(df.index, df['A'])
ax.bar(df.index, df['B'])
ax.bar(df.index, df['C'], bottom=df['B'])
ax.plot(df.index, df['D'], color='black', linewidth=2)
ax.set_xlabel('Date')
ax.set_ylabel('Change in Yield')
ax.axhline(y=0, color='r')
ax.set_xticks([])
ax.legend()
plt.show()

Edit:: Ok, I've found a way looking at this post here:
Plot Pandas DataFrame as Bar and Line on the same one chart

Try resetting the index so that it is a separate column. In my example, it is called 'DATE'. Then try:

ax = df[['DATE','D']].plot(x='DATE',color='black')
df[['DATE','A','B','C']].plot(x='DATE', kind='bar',stacked=True,ax=ax)
ax.axhline(y=0, color='r')
ax.set_xticks([])
ax.set_xlabel('Date')
ax.set_ylabel('Change in Yield')
ax.legend()
plt.show()


来源: stackexchange

问:
I want to deploy back-end and front-end seperate apps on the same server with nginx
I've created a restful api with nodejs and I'm planning to use sapper/svelte for front-end. In the end, these will be seperate apps and I want to run them on the same server with same domain. Is this approach reasonable? If it is, what should my nginx configuration file look like? If not, what should be my approach? </p>

<p>This my conf for api: </p>

```<code>server {
    server_name domain.name;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
   .
   .
   .
}
</code>```

答:
Following best pratice your API will be under BASE/api/

That will allow you to host backend + Frontend on the same server

```<code>server {
    server_name domain.name;

    location /api/ {    # Backend
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

        ...
    }

    location / {    # Frontend
        root        /app-path/;
        index       index.html;
        try_files   $uri $uri/ /index.html;

        ...
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've created a restful api with nodejs and I'm planning to use sapper/svelte for front-end. In the end, these will be seperate apps and I want to run them on the same server with same domain. Is this approach reasonable? If it is, what should my nginx configuration file look like? If not, what should be my approach?

This my conf for api:

server {
    server_name domain.name;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
   .
   .
   .
}

Body:
Following best pratice your API will be under BASE/api/

That will allow you to host backend + Frontend on the same server

server {
    server_name domain.name;

    location /api/ {    # Backend
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

        ...
    }

    location / {    # Frontend
        root        /app-path/;
        index       index.html;
        try_files   $uri $uri/ /index.html;

        ...
    }
}


问:
How to click on dropdown list items through Selenium in VBA macro?
I am trying to create a macro to download a file from a web page. I have coded the login and navigating to main download page however, unable to get codes to click on a drop-down menu on a web page. I need to click on 3 dots then click on Download xlsx to start downloading the file. I can not proceed to rest of the codes until file is downloaded. Here is the link to HTML properties of this dropdownlist

```<code>obj.FindElementsByClass("ant-dropdown-menu-item").Click
</code>```

答:
I had figured out the solution. I had to click on the blank space to get that drop down buttons appear. Then clicked as usually. I got the element path form Chropath chrome add on  and used xpath.</p>

```<code>Obj.FindElementByClass("insight__header").Click         '-----------This clicks on blank space to show 3 dots.
Obj.FindElementByXPath("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/header[1]/span[2]/div[1]/button[1]/i[1]/*").Click   '---------This cicks on 3 dots and displays the menu.
Obj.FindElementByXPath("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/ul[1]/li[4]/span[1]").Click    '---------This clicks on Download xlxs button to start downloading the file.
</code>```

Body:
I am trying to create a macro to download a file from a web page. I have coded the login and navigating to main download page however, unable to get codes to click on a drop-down menu on a web page. I need to click on 3 dots then click on Download xlsx to start downloading the file. I can not proceed to rest of the codes until file is downloaded. Here is the link to HTML properties of this dropdownlist

obj.FindElementsByClass("ant-dropdown-menu-item").Click

Body:
I had figured out the solution. I had to click on the blank space to get that drop down buttons appear. Then clicked as usually. I got the element path form Chropath chrome add on  and used xpath.

Obj.FindElementByClass("insight__header").Click         '-----------This clicks on blank space to show 3 dots.
Obj.FindElementByXPath("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/header[1]/span[2]/div[1]/button[1]/i[1]/*").Click   '---------This cicks on 3 dots and displays the menu.
Obj.FindElementByXPath("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/ul[1]/li[4]/span[1]").Click    '---------This clicks on Download xlxs button to start downloading the file.


问:
PHP - Mutidimensional array diff
i would like to ask for your help since I'm having difficulty resolving this matter. I had created a function to facilitate on array diff but it does not suffice to my needs. Thanks and more power!

```<code><?php
   $arraySession = array(
      'sampleA' => array('1', '2', '3'),
      'sampleB' => array('1', '2', '3'),
   );

$arrayPost = array(
    'sampleA' => array('1'),
    'sampleB' => array('1','2'),
);
</code>```

result should be:

```<code>array(
   'sampleA' => array('2', '3')
   'sampleB' => array('3'),
)
</code>```

my existing function:

```<code>    public function array_diff_multidimensional($session, $post) {
      $result = array();
      foreach($session as $sKey => $sValue){
          foreach($post as $pKey => $pValue) {
              if((string) $sKey == (string) $pKey) {
                  $result[$sKey] = array_diff($sValue, $pValue);
              } else {
                  $result[$sKey] = $sValue;
              }
          }
      }
      return $result;
    }
</code>```

Any help would be much appreciated! Happy coding!

答:
Not my function and not tested by me, but this was one of the first comments at php.net/array_diff (credit goes to thefrox at gmail dot com)</p>

```<code><?php
function multidimensional_array_diff($a1, $a2) {
    $r = array();

    foreach ($a2 as $key => $second) {
        foreach ($a1 as $key => $first) {
          if (isset($a2[$key])) {
              foreach ($first as $first_value) {
                  foreach ($second as $second_value) {
                      if ($first_value == $second_value) {
                          $true = true;
                          break;
                      }
                  }
                  if (!isset($true)) {
                      $r[$key][] = $first_value;
                  }
                  unset($true);
              }
          } else {
              $r[$key] = $first;
          }
        }
    }
    return $r;
}
?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP - Mutidimensional array diff

Body:
i would like to ask for your help since I'm having difficulty resolving this matter. I had created a function to facilitate on array diff but it does not suffice to my needs. Thanks and more power!

<?php
   $arraySession = array(
      'sampleA' => array('1', '2', '3'),
      'sampleB' => array('1', '2', '3'),
   );

$arrayPost = array(
    'sampleA' => array('1'),
    'sampleB' => array('1','2'),
);

result should be:

array(
   'sampleA' => array('2', '3')
   'sampleB' => array('3'),
)

my existing function:

    public function array_diff_multidimensional($session, $post) {
      $result = array();
      foreach($session as $sKey => $sValue){
          foreach($post as $pKey => $pValue) {
              if((string) $sKey == (string) $pKey) {
                  $result[$sKey] = array_diff($sValue, $pValue);
              } else {
                  $result[$sKey] = $sValue;
              }
          }
      }
      return $result;
    }

Any help would be much appreciated! Happy coding!

Body:
Not my function and not tested by me, but this was one of the first comments at php.net/array_diff (credit goes to thefrox at gmail dot com)

<?php
function multidimensional_array_diff($a1, $a2) {
    $r = array();

    foreach ($a2 as $key => $second) {
        foreach ($a1 as $key => $first) {
          if (isset($a2[$key])) {
              foreach ($first as $first_value) {
                  foreach ($second as $second_value) {
                      if ($first_value == $second_value) {
                          $true = true;
                          break;
                      }
                  }
                  if (!isset($true)) {
                      $r[$key][] = $first_value;
                  }
                  unset($true);
              }
          } else {
              $r[$key] = $first;
          }
        }
    }
    return $r;
}
?>


问:
Bash - replace in file strings from first array with strings from second array
I have two arrays. The first one is filled with values greped from the file that I want to replace with the new ones downloaded.

Please note that I don't know exactly how the first array will look like, meaning some values will have _, other - and some won't have any of that and immediately after the name will be placed : (colon).

Example arrays:

array1:

[account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123]

array2:

[account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124]

Those arrays are the only example, there are more than 50 values to replace.

I am doing a comparison of every item in the second array with every item in the first array as shown below:

```<code>file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                 fi
        done
done
</code>```

Here I substring only the first part for every item in the second array so I can compare it with the item in the first array.

e.g. account_custom_2:124 -> account or notification-dispatcher_custom_2:124 -> notification-dispatcher.

This works nice but I encounter problem when notification is in notification-core_1:123 and notification-dispatcher_core_1:123 and notification-dispatcher-smschannel_core_1:123.

Can you please give advice on how to fix this or if you can suggest another approach to this?

答:
If number of items in your arrays are equal then you can process them in one loop</p>

```<code>for i in "${!array1[@]}"; {
    value=${array1[$i]}
    new_value=${array2[$i]}
    sed -i "s/$value/$new_value/" file
}
</code>```

Body:
I have two arrays. The first one is filled with values greped from the file that I want to replace with the new ones downloaded.

Please note that I don't know exactly how the first array will look like, meaning some values will have _, other - and some won't have any of that and immediately after the name will be placed : (colon).

Example arrays:

array1:

[account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123]

array2:

[account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124]

Those arrays are the only example, there are more than 50 values to replace.

I am doing a comparison of every item in the second array with every item in the first array as shown below:

file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                 fi
        done
done

Here I substring only the first part for every item in the second array so I can compare it with the item in the first array.

e.g. account_custom_2:124 -> account or notification-dispatcher_custom_2:124 -> notification-dispatcher.

This works nice but I encounter problem when notification is in notification-core_1:123 and notification-dispatcher_core_1:123 and notification-dispatcher-smschannel_core_1:123.

Can you please give advice on how to fix this or if you can suggest another approach to this?

Body:
If number of items in your arrays are equal then you can process them in one loop

for i in "${!array1[@]}"; {
    value=${array1[$i]}
    new_value=${array2[$i]}
    sed -i "s/$value/$new_value/" file
}


问:
Nested ListView in PyQt5 and QML
I need to create nested ListView. For example,

```<code>->Item1
 -->Subitem1
 -->Subitem2
->Item2
 -->Subitem1
</code>```

I have a dictionary data inside Python side. I need to display this data from QML ListView.
So, I should take the model from python and I should design collapsable ListView inside QML. I searched about this but I couldn't find example about it. I tried to create my own model but it didn't work.

Can someone help me?

答:
Take a look at sections in ListView

https://doc-snapshots.qt.io/qt5-5.11/qml-qtquick-listview.html#section-prop

Title: Nested ListView in PyQt5 and QML

Body:
I need to create nested ListView. For example,

->Item1
 -->Subitem1
 -->Subitem2
->Item2
 -->Subitem1

I have a dictionary data inside Python side. I need to display this data from QML ListView.
So, I should take the model from python and I should design collapsable ListView inside QML. I searched about this but I couldn't find example about it. I tried to create my own model but it didn't work.

Can someone help me?


问:
How to set value for provider gathered from API backend in Angular
how can I set value here from API ?

答:
You would ideally achieve this via an async factory in your providers. Unfortunately that has been an open issue for a while.

A workaround could be to create a wrapper service that loads the api key first time through and then replays the loaded service from a subject.

```<code>@Injectable({ providedIn: 'root'})
export class ServiceWrapper {

  private service$: Subject<Service>;

  getService(): Observable<Service> {
    if (this.service$) {
      return this.service$.pipe(
        take(1)
      );
    }

    this.service$ = new ReplaySubject<Service>(1);

    this.http.get(apiKeyUrl).subscribe(apiKey => {
      this.service$.next(new Service(apiKey));
    });

    return this.service$.pipe(
      take(1)
    );
  }
}
</code>```

You would then inject this wrapper service into the components (or whatever consumes it):

```<code>export class MyComponent {
  constructor(private service: ServiceWrapper) {}

  ngOnInit(): void {
    this.service.getService().pipe(
      switchMap(service => service.method())
    ).subscribe(result => {
      // do something
    });
  }
}
</code>```

You will end up with a lot of switchMap calls, so isn't ideal, but is one workaround.

If you had any other dependencies you needed to inject into the service, you would also inject those into your wrapper service.

Working demo: https://stackblitz.com/edit/angular-wlbyqp

Body: how can I set value here from API ?

Body:
You would ideally achieve this via an async factory in your providers. Unfortunately that has been an open issue for a while.

A workaround could be to create a wrapper service that loads the api key first time through and then replays the loaded service from a subject.

@Injectable({ providedIn: 'root'})
export class ServiceWrapper {

  private service$: Subject<Service>;

  getService(): Observable<Service> {
    if (this.service$) {
      return this.service$.pipe(
        take(1)
      );
    }

    this.service$ = new ReplaySubject<Service>(1);

    this.http.get(apiKeyUrl).subscribe(apiKey => {
      this.service$.next(new Service(apiKey));
    });

    return this.service$.pipe(
      take(1)
    );
  }
}

You would then inject this wrapper service into the components (or whatever consumes it):

export class MyComponent {
  constructor(private service: ServiceWrapper) {}

  ngOnInit(): void {
    this.service.getService().pipe(
      switchMap(service => service.method())
    ).subscribe(result => {
      // do something
    });
  }
}

You will end up with a lot of switchMap calls, so isn't ideal, but is one workaround.

If you had any other dependencies you needed to inject into the service, you would also inject those into your wrapper service.

Working demo: https://stackblitz.com/edit/angular-wlbyqp


问:
Kotlin equivalent of %@ in swift
i am new to kotlin.
In swift i can do :

```<code>let endpoint = "categories/" + "%@/issues/"
let number = "4"
let finalstring = String(format: endpoint, number)
</code>```

The final output of the string will be : categories/4/issues/ as a string .

I have looked at string format in kotlin but it's only work afterwards meaning that i can't define a template for my string and fill it later.

```<code>var value1 = "categories/"
var value2 = 4
var value3 = "/issues/"
println(java.lang.String.format("%s%d%s", value1, value2, value3))
</code>```

This give me the same result but it's mean that i have to manualy write the end of the string.

What i want to do i to have a template for my string in a Road file.
Then complet my string at the run time. The probleme is that the part of my string that i want to complete is in the middle of the string.
Of course i can use substring and remplace but i am looking for a clean way to do it as in swift.

Thanks for helping.

答:
You can create your format string up front with all the constant parts, and with relevant placeholders (like %d for numbers) (more info in the javadoc).

Later, use the regular Java String.format() later with the parameters:

```<code>// define this constant up front
val format = "categories/%d/issues/"

// and then later:
val categoryId = 4
println(String.format(format, categoryId))
</code>```

Title: Kotlin equivalent of %@ in swift

Body:
i am new to kotlin.
In swift i can do :

let endpoint = "categories/" + "%@/issues/"
let number = "4"
let finalstring = String(format: endpoint, number)

The final output of the string will be : categories/4/issues/ as a string .

I have looked at string format in kotlin but it's only work afterwards meaning that i can't define a template for my string and fill it later.

var value1 = "categories/"
var value2 = 4
var value3 = "/issues/"
println(java.lang.String.format("%s%d%s", value1, value2, value3))

This give me the same result but it's mean that i have to manualy write the end of the string.

What i want to do i to have a template for my string in a Road file.
Then complet my string at the run time. The probleme is that the part of my string that i want to complete is in the middle of the string.
Of course i can use substring and remplace but i am looking for a clean way to do it as in swift.

Thanks for helping.

Body:
You can create your format string up front with all the constant parts, and with relevant placeholders (like %d for numbers) (more info in the javadoc).

Later, use the regular Java String.format() later with the parameters:

// define this constant up front
val format = "categories/%d/issues/"

// and then later:
val categoryId = 4
println(String.format(format, categoryId))


问:
Sorting named numeric vectors in Rcpp
In a function, I want to calculate numeric values, give names to them and return a sorted NumericVector in Rcpp. I can sort the vectors (using this), but the order of the names of the values remains the same.

```<code>library(Rcpp)
x <- c(a = 1, b = 5, c = 3)
cppFunction('
NumericVector foo(NumericVector x) {
  std::sort(x.begin(), x.end());
  return(x);
}')
foo(x)
## a b c
## 1 3 5
</code>```

I want the function to return this:

```<code>## a c b
## 1 3 5
</code>```

Is it possible? How can I achieve this?

答:
Using the tip Dirk gave in his comment, I figured out that names of x is just another vector. So, I searched for sorting a vector using another vector. Using this SO answer I come up with following two solutions:

```<code>library(Rcpp)
x = c(a = 1, b = 5, c = 3, d = -3.2)

cppFunction('
NumericVector foo1(NumericVector x) {
 IntegerVector idx = seq_along(x) - 1;
 std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
 return x[idx];
}')

foo1(x)

##    d    a    c    b
## -3.2  1.0  3.0  5.0

cppFunction('
NumericVector foo2(NumericVector x) {
 IntegerVector idx = seq_along(x) - 1;
 //// Ordered indices based on x:
 std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
 //// Get the names of x:
 CharacterVector names_of_x = x.names();
 //// y vector is sorted x
 NumericVector y = x[idx];
 //// Assign sorted names to y vector as names
 y.attr("names") = names_of_x[idx];
 return y;
}')

foo2(x)

##    d    a    c    b
## -3.2  1.0  3.0  5.0
</code>```

Title: Sorting named numeric vectors in Rcpp

Body:
In a function, I want to calculate numeric values, give names to them and return a sorted NumericVector in Rcpp. I can sort the vectors (using this), but the order of the names of the values remains the same.

library(Rcpp)
x <- c(a = 1, b = 5, c = 3)
cppFunction('
NumericVector foo(NumericVector x) {
  std::sort(x.begin(), x.end());
  return(x);
}')
foo(x)
## a b c
## 1 3 5

I want the function to return this:

## a c b
## 1 3 5

Is it possible? How can I achieve this?

Body:
Using the tip Dirk gave in his comment, I figured out that names of x is just another vector. So, I searched for sorting a vector using another vector. Using this SO answer I come up with following two solutions:

library(Rcpp)
x = c(a = 1, b = 5, c = 3, d = -3.2)

cppFunction('
NumericVector foo1(NumericVector x) {
 IntegerVector idx = seq_along(x) - 1;
 std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
 return x[idx];
}')

foo1(x)

##    d    a    c    b
## -3.2  1.0  3.0  5.0

cppFunction('
NumericVector foo2(NumericVector x) {
 IntegerVector idx = seq_along(x) - 1;
 //// Ordered indices based on x:
 std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
 //// Get the names of x:
 CharacterVector names_of_x = x.names();
 //// y vector is sorted x
 NumericVector y = x[idx];
 //// Assign sorted names to y vector as names
 y.attr("names") = names_of_x[idx];
 return y;
}')

foo2(x)

##    d    a    c    b
## -3.2  1.0  3.0  5.0


问:
Save Each slide as a separate file
I am trying to save my each slide as a separate file by naming with there slide number with below given script, but it is saving only the selected slide.</p>

```<code>Sub TestMe()
    SaveSlide 5, "C:\G-Tools\export\test.pptx"
End Sub

Sub SaveSlide(lSlideNum As Long, sFileName As String)

    Dim oTempPres As Presentation
    Dim x As Long

    ActivePresentation.SaveCopyAs sFileName
    ' open the saved copy windowlessly
    Set oTempPres = Presentations.Open(sFileName, , , False)

    For x = 1 To lSlideNum - 1
        oTempPres.Slides(1).Delete
    Next

    ' What was slide number lSlideNum is now slide 1
    For x = oTempPres.Slides.Count To 2 Step -1
        oTempPres.Slides(x).Delete
    Next

    oTempPres.Save
    oTempPres.Close

End Sub
</code>```

答:
Instead of deleting all other slides (which was the solution given in this answer), you can create a new presentation for each slide and copy it to the new presentation. In order to keep the same color scheme and design, you must copy that over as well.</p>

```<code>Option Explicit

Sub TestMe()
    SaveAllSlides "C:\Temp\myslides.pptx", True
End Sub

Sub SaveAllSlides(ByVal newFilename As String, _
                  Optional ByVal keepOpen As Boolean = False)
    Dim dotPosition As Long
    dotPosition = InStrRev(newFilename, ".")
    If dotPosition = 0 Then
        MsgBox "The filename is missing the pptx extension"
        Exit Sub
    End If

    Dim filepathNoExt As String
    filepathNoExt = Left$(newFilename, dotPosition - 1)

    Dim newPresentation As Presentation
    Dim thisPresentation As Presentation
    Set thisPresentation = ActivePresentation

    Dim i As Long
    For i = 1 To ActivePresentation.Slides.Count
        Set newPresentation = Presentations.Add
        thisPresentation.Slides(i).Copy
        With newPresentation
            .Slides.Paste Index:=1
            .Slides(1).Design = thisPresentation.Slides(i).Design
            .Slides(1).ColorScheme = thisPresentation.Slides(i).ColorScheme
            .SaveAs FileName:=filepathNoExt & Format(i, "00") & ".pptx"
            If Not keepOpen Then
                .Close
            End If
        End With
    Next i
End Sub
</code>```

Title: Save Each slide as a separate file

Body:
I am trying to save my each slide as a separate file by naming with there slide number with below given script, but it is saving only the selected slide.

Sub TestMe()
    SaveSlide 5, "C:\G-Tools\export\test.pptx"
End Sub

Sub SaveSlide(lSlideNum As Long, sFileName As String)

    Dim oTempPres As Presentation
    Dim x As Long

    ActivePresentation.SaveCopyAs sFileName
    ' open the saved copy windowlessly
    Set oTempPres = Presentations.Open(sFileName, , , False)

    For x = 1 To lSlideNum - 1
        oTempPres.Slides(1).Delete
    Next

    ' What was slide number lSlideNum is now slide 1
    For x = oTempPres.Slides.Count To 2 Step -1
        oTempPres.Slides(x).Delete
    Next

    oTempPres.Save
    oTempPres.Close

End Sub

Body:
Instead of deleting all other slides (which was the solution given in this answer), you can create a new presentation for each slide and copy it to the new presentation. In order to keep the same color scheme and design, you must copy that over as well.

Option Explicit

Sub TestMe()
    SaveAllSlides "C:\Temp\myslides.pptx", True
End Sub

Sub SaveAllSlides(ByVal newFilename As String, _
                  Optional ByVal keepOpen As Boolean = False)
    Dim dotPosition As Long
    dotPosition = InStrRev(newFilename, ".")
    If dotPosition = 0 Then
        MsgBox "The filename is missing the pptx extension"
        Exit Sub
    End If

    Dim filepathNoExt As String
    filepathNoExt = Left$(newFilename, dotPosition - 1)

    Dim newPresentation As Presentation
    Dim thisPresentation As Presentation
    Set thisPresentation = ActivePresentation

    Dim i As Long
    For i = 1 To ActivePresentation.Slides.Count
        Set newPresentation = Presentations.Add
        thisPresentation.Slides(i).Copy
        With newPresentation
            .Slides.Paste Index:=1
            .Slides(1).Design = thisPresentation.Slides(i).Design
            .Slides(1).ColorScheme = thisPresentation.Slides(i).ColorScheme
            .SaveAs FileName:=filepathNoExt & Format(i, "00") & ".pptx"
            If Not keepOpen Then
                .Close
            End If
        End With
    Next i
End Sub


问:
Get all values from another column in a table when null
I am trying to create a bridge table in SQL and want to join back to the lookup table.

what I want to achieve here is if I join on the Hierarchy code and Base code I am getting the desired result, But I want to get all values in the lookup table for each hierarchy code where the base code is null in the bridge table.

Table format:

答:
Your join needs to have two predicates combined with an OR operator.

For example:

```<code>select b.*, l.*
from bridge b
join lookup l on l.hierarchy_code = b.hierarchy_code and l.base_code = b.base_code
              or b.base_code is null and l.hierarchy_code = b.hierarchy_code
</code>```

Body:
Your join needs to have two predicates combined with an OR operator.

For example:

select b.*, l.*
from bridge b
join lookup l on l.hierarchy_code = b.hierarchy_code and l.base_code = b.base_code
              or b.base_code is null and l.hierarchy_code = b.hierarchy_code


问:
reference LONG variable to cell in a sheet
How to link a Long variable to a value entered in an excel sheet? I want to create large number of rows and although I am able to change the variable directly in the code (e.g. x=100000) but as soon as I link the variable x to a cell (e.g. x = Cells(1,1) no value seems to be recognized and printed to the range.</p>

答:
Thanks for taking the time to answer my question. I found the following approach to work best for me.

Sub test()

Dim x As LongLong
x = Worksheets("Sheet1").Cells(4, 2) 'e.g. value is 100.000
range(Cells(1, 1), Cells(x, 1)).Value = "*" 'fill x rows with a * as a test

End Sub```


问:
JUnit Test with Mockito - How to Mock javax.ws.rs.client.ClientRequestContext?
I have a class that implements javax.ws.rs.client.ClientRequestFilter:

```<code>public class CustomFilter implements ClientRequestFilter {

@Override
public void filter(ClientRequestContext context) throws IOException {
    URI newUri = ... //replace a new uri
    context.setUri(URI.create(newUri));

    if (context.getMethod == "POST") {
        context.setMethod("GET");
        context.getHeaders().putSingle("ID","some string");
    }
}
</code>```

What I want is somehow to mock the ClientRequestContext. I want to compare that after calling the filter() function:

The new uri is set correctly.

The new http method is set correctly.

A new header "ID" is set with "some string" for the context.

As I tried to figure out, I can only mock the getter methods, and I do not know how to mock ClientRequestContext properly and use my CustomerFilter class to call the real function filter() to change values of the ClientRequestContext object since it is an interface. Could you help me to achieve the 3 requirements?

答:
The class ClientRequestFilter is an interface, so you can mock it either using the static Mockito.mock method or annotating the field as @Mock in the test. So, if you want to check if the setUri method is called, you should do the following in your test method:

```<code>CustomFilter customFilter = new CustomFilter();
customFilter.filter(context);
Mockito.verify(context, Mockito.once()).setUri(ArgumentMatchers.any(URI.class));
</code>```

For older Mockito versions:

```<code>CustomFilter customFilter = new CustomFilter();
customFilter.filter(context);
Mockito.verify(context, Mockito.once()).setUri(Matchers.any());
</code>```

You don't have to verify that the underlying implementation is working. Since you are using an interface you will trust that the implementation that you will have at runtime is correct, because it is not necessary to test you dependencies. You simply have to be sure that the code you wrote is working and is forwarding requests to other classes.

In similar way you can test the other requirement:

```<code>Mockito.when(context.getMethod()).thenReturn("POST");
MultivaluedMap headers = Mockito.mock(MultivaluedMap.class);
Mockito.when(context.getHeaders()).thenReturn(headers);
CustomFilter customFilter = new CustomFilter();
customFilter.filter(context);
Mockito.verify(context, Mockito.once()).setUri(Matchers.any());
Mockito.verify(context, Mockito.once()).setMethod(Matchers.any());
Mockito.verify(context, Mockito.once()).getHeaders();
</code>```

Body:
I have a class that implements javax.ws.rs.client.ClientRequestFilter:

public class CustomFilter implements ClientRequestFilter {

@Override
public void filter(ClientRequestContext context) throws IOException {
    URI newUri = ... //replace a new uri
    context.setUri(URI.create(newUri));

    if (context.getMethod == "POST") {
        context.setMethod("GET");
        context.getHeaders().putSingle("ID","some string");
    }
}

What I want is somehow to mock the ClientRequestContext. I want to compare that after calling the filter() function:

The new uri is set correctly.

The new http method is set correctly.

A new header "ID" is set with "some string" for the context.

As I tried to figure out, I can only mock the getter methods, and I do not know how to mock ClientRequestContext properly and use my CustomerFilter class to call the real function filter() to change values of the ClientRequestContext object since it is an interface. Could you help me to achieve the 3 requirements?

Body:
The class ClientRequestFilter is an interface, so you can mock it either using the static Mockito.mock method or annotating the field as @Mock in the test. So, if you want to check if the setUri method is called, you should do the following in your test method:

CustomFilter customFilter = new CustomFilter();
customFilter.filter(context);
Mockito.verify(context, Mockito.once()).setUri(ArgumentMatchers.any(URI.class));

For older Mockito versions:

CustomFilter customFilter = new CustomFilter();
customFilter.filter(context);
Mockito.verify(context, Mockito.once()).setUri(Matchers.any());

You don't have to verify that the underlying implementation is working. Since you are using an interface you will trust that the implementation that you will have at runtime is correct, because it is not necessary to test you dependencies. You simply have to be sure that the code you wrote is working and is forwarding requests to other classes.

In similar way you can test the other requirement:

Mockito.when(context.getMethod()).thenReturn("POST");
MultivaluedMap headers = Mockito.mock(MultivaluedMap.class);
Mockito.when(context.getHeaders()).thenReturn(headers);
CustomFilter customFilter = new CustomFilter();
customFilter.filter(context);
Mockito.verify(context, Mockito.once()).setUri(Matchers.any());
Mockito.verify(context, Mockito.once()).setMethod(Matchers.any());
Mockito.verify(context, Mockito.once()).getHeaders();


问:
Access third party React app state from outside React
A website uses a third-party plugin that comes with a React application.

I need to get a JS function that reads some values from that React app state. However, I cannot find the React instance in the global window scope... Where does React store the app instance?

My attempt: When I install the browser extension "React Developer Tools" in Chrome, then there is a global object window.$r that allows me to access the React state. I can do var title = window.$r.state.title.

However, the $r object is only present when the React Developer Tools are installed. I need to write some JS that works for all users, even when they do not have that browser extension.

Also, I cannot modify the React app to make the state available via a ref or export. I can only write JS outside the app.

I have also tried to examine the root DOM node that renders the main application Component but I have not found a way to read application details from that...

答:
I found a solution by searching through a ton of JS data, but I could extract a function that returns the state object of the React application.

I noticed that the state is nested like 6 - 10 levels below the actual react root DOM node, so I wrote a function that loops through the React app and identifies the state by an attribute name.

This code is tested with React 16.7

```<code>function getAppState(rootNode, globalAttributeName) {
    var $root = jQuery(rootNode);
    var reactState = false;
    var searchStack = [];
    var searched = [];

    // Fetch the "__reactInternalInstance$..." attribute from the DOM node.
    for ( const key in $root[0] ) {
        // The full name changes on every page load, e.g. "__reactInternalInstance$ek3wnas4g6"
        if (0 === key.indexOf('__reactInternalInstance$') ) {
            searchStack.push($root[0][key]);
            break;
        }
    }

    // Find the state by examining the object structure.
    while (stack.length) {
        var obj = stack.pop();

        if (obj && typeof obj == 'object' && -1 === searched.indexOf(obj)) {
            if ( undefined !== obj[ globalAttributeName ] ) {
                reactState = obj;
                break;
            }

            for (i in obj) {
                stack.push(obj[i]);
            }
            searched.push(obj);
        }
    }

    return reactState;
}

// In my example, I know that the app uses "state.activeModule",
// so I search for the key "activeModule" to identify the state:
getAppState('#root-id', 'activeModule');

// Here is the full path to the state, in my example:
// __reactInternalInstance$ek3wnas4g6g.alternate.return.alternate.return.alternate.memoizedProps._owner.alternate.memoizedState
</code>```

This answer did greatly help me to find this solution: https://stackoverflow.com/a/12103127/313501

Body:
I found a solution by searching through a ton of JS data, but I could extract a function that returns the state object of the React application.

I noticed that the state is nested like 6 - 10 levels below the actual react root DOM node, so I wrote a function that loops through the React app and identifies the state by an attribute name.

This code is tested with React 16.7

function getAppState(rootNode, globalAttributeName) {
    var $root = jQuery(rootNode);
    var reactState = false;
    var searchStack = [];
    var searched = [];

    // Fetch the "__reactInternalInstance$..." attribute from the DOM node.
    for ( const key in $root[0] ) {
        // The full name changes on every page load, e.g. "__reactInternalInstance$ek3wnas4g6"
        if (0 === key.indexOf('__reactInternalInstance$') ) {
            searchStack.push($root[0][key]);
            break;
        }
    }

    // Find the state by examining the object structure.
    while (stack.length) {
        var obj = stack.pop();

        if (obj && typeof obj == 'object' && -1 === searched.indexOf(obj)) {
            if ( undefined !== obj[ globalAttributeName ] ) {
                reactState = obj;
                break;
            }

            for (i in obj) {
                stack.push(obj[i]);
            }
            searched.push(obj);
        }
    }

    return reactState;
}

// In my example, I know that the app uses "state.activeModule",
// so I search for the key "activeModule" to identify the state:
getAppState('#root-id', 'activeModule');

// Here is the full path to the state, in my example:
// __reactInternalInstance$ek3wnas4g6g.alternate.return.alternate.return.alternate.memoizedProps._owner.alternate.memoizedState

This answer did greatly help me to find this solution: https://stackoverflow.com/a/12103127/313501


问:
I keep getting this error for my program: VM178 SortLib.js:71 Uncaught TypeError: Cannot read property 'length' of undefined
I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript. My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.

```<code>//Merge Sort Algorithm Implementation

//Function for dividing array into two sub problems
divide = (array) => {
    if (array.length < 2) {
        return array
    }
        const mid = Math.floor(array.length / 2)
        const smallOne = array.slice(0, mid)
        const smallTwo = array.slice(mid)
        return sort(divide(smallOne), divide(smallTwo))
    }

//Function for sorting array
sort = (smallOne, smallTwo) => {
    const sorted = []
    while (smallOne.length && smallTwo.length) {
        if (smallOne[0] <= smallTwo[0]) {
            sorted.push(smallOne.shift())
        } else {
            sorted.push(smallTwo.shift())
            }
        }
    const output = [...sorted, ...smallOne, ...smallTwo]
    console.log(output)
    return output
    }

//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}

</code>```

Here's a picture of my error in the console

答:
You are getting the error because that smallTwo is undefined inside the sort function.

The Full error message is:

```<code>while (smallOne.length && smallTwo.length) {
                                       ^

TypeError: Cannot read property 'length' of undefined
</code>```

Body:
I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript. My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.

//Merge Sort Algorithm Implementation

//Function for dividing array into two sub problems
divide = (array) => {
    if (array.length < 2) {
        return array
    }
        const mid = Math.floor(array.length / 2)
        const smallOne = array.slice(0, mid)
        const smallTwo = array.slice(mid)
        return sort(divide(smallOne), divide(smallTwo))
    }

//Function for sorting array
sort = (smallOne, smallTwo) => {
    const sorted = []
    while (smallOne.length && smallTwo.length) {
        if (smallOne[0] <= smallTwo[0]) {
            sorted.push(smallOne.shift())
        } else {
            sorted.push(smallTwo.shift())
            }
        }
    const output = [...sorted, ...smallOne, ...smallTwo]
    console.log(output)
    return output
    }

//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}

Here's a picture of my error in the console

Body:
You are getting the error because that smallTwo is undefined inside the sort function.

The Full error message is:

while (smallOne.length && smallTwo.length) {
                                       ^

TypeError: Cannot read property 'length' of undefined


问:
Replacing all tokens based on properties file with ANT
I'm pretty sure this is a simple question to answer and ive seen it asked before just no solid answers.

I have several properties files that are used for different environments, i.e xxxx-dev, xxxx-test, xxxx-live

The properties files contain something like:

```<code>server.name=dummy_server_name
server.ip=127.0.0.1
</code>```

The template files im using look something like:

```<code><...>
   <server name="@server.name@" ip="@server.ip@"/>
</...>
</code>```

The above is a really primitive example, but im wondering if there is a way to just tell ANT to replace all tokens based on the properties file, rather than having to hardcode a token line for each... i.e

```<code><replacetokens>
   <token key="server.name" value="${server.name}"/>
   <token key="server.ip" value="${server.ip}"/>
</replacetokens>
</code>```

Any help would be great!

答:
Using fileset form ant-contrib you can read the tokens form properties file and replace multiple tokens over multiple files.

<project name="MyProject" default="replaceToklens" basedir=".">
    <property name="profilesProperties" value="${basedir}/environment.properties" />
    <property name="build.dir" location="build"/>

    <property file="${profilesProperties}" />
    <target name="replaceToklens">
        <taskdef resource="net/sf/antcontrib/antlib.xml">
            <classpath>
                <pathelement location="${basedir}/ant-contrib-1.0b3.jar" />
            </classpath>
        </taskdef>
            <mkdir dir="${build.dir}"/>
            <filter filtersfile="${profilesProperties}" />
            <copy todir="${build.dir}" filtering="true" overwrite="true">
                <fileset dir="${basedir}">
                    <include name="*.xml" />
                    <exclude name="build.xml" />
                </fileset>
            </copy>
    </target>
</project>
```

<p>folder structure:</p>

```ANT
 \_ build.xml
 \_ environment.properties
 \_ server.xml
 \_ build
        \_ server.xml   [replaced with token value]
```

<p>In order to replace single toke use the following:</p>

<pre class="lang-xml prettyprint-override"><code><replace file="build/server.xml" token="@keyName@" value="${keyValue}" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm pretty sure this is a simple question to answer and ive seen it asked before just no solid answers.

I have several properties files that are used for different environments, i.e xxxx-dev, xxxx-test, xxxx-live

The properties files contain something like:

server.name=dummy_server_name
server.ip=127.0.0.1

The template files im using look something like:

<...>
   <server name="@server.name@" ip="@server.ip@"/>
</...>

The above is a really primitive example, but im wondering if there is a way to just tell ANT to replace all tokens based on the properties file, rather than having to hardcode a token line for each... i.e

<replacetokens>
   <token key="server.name" value="${server.name}"/>
   <token key="server.ip" value="${server.ip}"/>
</replacetokens>

Any help would be great!

Body:
Using fileset form ant-contrib you can read the tokens form properties file and replace multiple tokens over multiple files.

<project name="MyProject" default="replaceToklens" basedir=".">
    <property name="profilesProperties" value="${basedir}/environment.properties" />
    <property name="build.dir" location="build"/>

    <!-- File to Load/ Accessable -->
    <property file="${profilesProperties}" />
    <target name="replaceToklens">
        <taskdef resource="net/sf/antcontrib/antlib.xml">
            <classpath>
                <pathelement location="${basedir}/ant-contrib-1.0b3.jar" />
            </classpath>
        </taskdef>
            <mkdir dir="${build.dir}"/>
            <filter filtersfile="${profilesProperties}" />
            <copy todir="${build.dir}" filtering="true" overwrite="true">
                <fileset dir="${basedir}"> <!-- target/MyProject -->
                    <include name="*.xml" />
                    <exclude name="build.xml" />
                </fileset>
            </copy>
    </target>
</project>

folder structure:

ANT
 \_ build.xml
 \_ environment.properties
 \_ server.xml
 \_ build
        \_ server.xml   [replaced with token value]

In order to replace single toke use the following:

<replace file="build/server.xml" token="@keyName@" value="${keyValue}" />


问:
WTForms RadioField preventing form validation
I have a WTForms form containing a few different types of fields, all of which work except the RadioField.

Python:
    from flask_wtf import FlaskForm
    from wtforms import validators, RadioField, DecimalField

```<code>class MyForm(FlaskForm):
    field_one = DecimalField('Field 1', validators=[Optional()]
    field_two = RadioField('Radio', choices=[(True, 'True'), (False, 'False')])
    submit = SubmitField('Submit')

@app.route('/page', methods=['GET', 'POST'])
def page():
    form = MyForm()
    print('Page requested')

    if form.validate_on_submit():
        print('form validated')

    return render_template('/page.html', form=form)
</code>```

HTML:

```<code><form method="POST">
  <div class="row">
    {{ form.hidden_tag() }}
    {{ form.field_one.label }}
    <div>
      {{ form.field_one }}
    </div>
  </div>
  <div class="row">
    {{ form.hidden_tag() }}
    {{ form.field_two.label }}
    <div>
      {% for subfield in form.field_two %}
        <p>{{ subfield }} - {{ subfield.label }}
      {% endfor %}
    </div>
  </div>
</form>
</code>```

When I take out anything related to field_two (the RadioField), print('form validated') will execute every time I press submit.

But as soon as the RadioField is included the form is never validated. I thought it might be because the field doesn't have an associated validator, but it still doesn't work when I add validators=[Optional()] to the field_two definition.

Anyone know why the form isn't validated with the RadioField?

(I've tried the four options I can think of. Clicking submit with and without selecting a radio option, and adding and removing the Optional validator to the form definition.)

答:
I had the same problem and found the working solution is to make a parent class that validates the RadioField class (see https://github.com/wtforms/wtforms/issues/477 for code).
The failure of RadioFields to validate is a known issue.</p>

Body:
I have a WTForms form containing a few different types of fields, all of which work except the RadioField.

Python:
    from flask_wtf import FlaskForm
    from wtforms import validators, RadioField, DecimalField

class MyForm(FlaskForm):
    field_one = DecimalField('Field 1', validators=[Optional()]
    field_two = RadioField('Radio', choices=[(True, 'True'), (False, 'False')])
    submit = SubmitField('Submit')

@app.route('/page', methods=['GET', 'POST'])
def page():
    form = MyForm()
    print('Page requested')

    if form.validate_on_submit():
        print('form validated')

    return render_template('/page.html', form=form)

HTML:

<form method="POST">

    {{ form.hidden_tag() }}
    {{ form.field_one.label }}

      {{ form.field_one }}

    {{ form.hidden_tag() }}
    {{ form.field_two.label }}

      {% for subfield in form.field_two %}

{{ subfield }} - {{ subfield.label }}
      {% endfor %}

</form>

When I take out anything related to field_two (the RadioField), print('form validated') will execute every time I press submit.

But as soon as the RadioField is included the form is never validated. I thought it might be because the field doesn't have an associated validator, but it still doesn't work when I add validators=[Optional()] to the field_two definition.

Anyone know why the form isn't validated with the RadioField?

(I've tried the four options I can think of. Clicking submit with and without selecting a radio option, and adding and removing the Optional validator to the form definition.)


问:
google protobuf timestamp undeclared identifier with C++ on Windows
I have a Windows native C++ project that uses google protobufs (version 3 syntax) and gRPC. I have a .proto file that includes the Timestamp type like this:

import "timestamp.proto";

I can successfully generate (using protoc.exe) the .cc and .h files for the messages and services in my .proto file without any errors or warnings. I can also generate the output for gRPC from the .proto file without errors or warnings.

When I use those generated files in a Visual Studio project, I see these errors in the .cc file generated from my .proto file. They're all related to the Timestamp type:

```<code>Error C2491 'scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto': definition of dllimport data not allowed
Error C2491 'TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets': definition of dllimport static data member not allowed
Error C2653 'PROTOBUF_INTERNAL_EXPORT_timestamp_2eproto': is not a class or namespace name
Error C2059 syntax error: '<'
Error C2065 'scc_info_Timestamp_timestamp_2eproto': undeclared identifier
Error C2065 'scc_info_Timestamp_timestamp_2eproto': undeclared identifier
Error C2039 'descriptor_table_timestamp_2eproto': is not a member of ''global namespace''
Error C2065 'descriptor_table_timestamp_2eproto': undeclared identifier
</code>```

I've added the Timestamp.pb.h/.cc files to the Visual Studio project header files, as well as the other .h/.cc files generated from my .proto file.

I have no idea how to go about troubleshooting this. I've verified that removing the Timestamp type allows the project to build successfully. I've tried an older version of protobufs. And of course googled for hours...

My environment:

```<code>Windows 10
Visual Studio 2017
vcpkg (Microsoft C++ package manager) used to build Protocol buffers 3.11.3 and gRPC 1.27.1
</code>```

Any suggestions?

答:
I've found the resolution for this problem. It was mostly caused by my include folder path. I the VS include path set to "\include\google\protobuf" which has all of the .h files generated from .proto files. What I needed was to have the include folder just set to "\include". This allowed me to change my .proto file so it references the Timestamp type like this:

import "google/protobuf/timestamp.proto";

instead of the way I was referencing it:

import "timestamp.proto";

In addition - I found that I did not need to include "timestamp.pb.cc" in my project. I haven't fully investigated why this is yet - but a couple tests appear to show that it's really not needed.

Body:
I have a Windows native C++ project that uses google protobufs (version 3 syntax) and gRPC. I have a .proto file that includes the Timestamp type like this:

import "timestamp.proto";

I can successfully generate (using protoc.exe) the .cc and .h files for the messages and services in my .proto file without any errors or warnings. I can also generate the output for gRPC from the .proto file without errors or warnings.

When I use those generated files in a Visual Studio project, I see these errors in the .cc file generated from my .proto file. They're all related to the Timestamp type:

Error C2491 'scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto': definition of dllimport data not allowed
Error C2491 'TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets': definition of dllimport static data member not allowed
Error C2653 'PROTOBUF_INTERNAL_EXPORT_timestamp_2eproto': is not a class or namespace name
Error C2059 syntax error: '<'
Error C2065 'scc_info_Timestamp_timestamp_2eproto': undeclared identifier
Error C2065 'scc_info_Timestamp_timestamp_2eproto': undeclared identifier
Error C2039 'descriptor_table_timestamp_2eproto': is not a member of ''global namespace''
Error C2065 'descriptor_table_timestamp_2eproto': undeclared identifier

I've added the Timestamp.pb.h/.cc files to the Visual Studio project header files, as well as the other .h/.cc files generated from my .proto file.

I have no idea how to go about troubleshooting this. I've verified that removing the Timestamp type allows the project to build successfully. I've tried an older version of protobufs. And of course googled for hours...

My environment:

Windows 10
Visual Studio 2017
vcpkg (Microsoft C++ package manager) used to build Protocol buffers 3.11.3 and gRPC 1.27.1

Any suggestions?


问:
Spring Integration : send json as request body and headers in http outbound gateway
I want to invoke an external REST endpoint POST request with a JSON payload which would be getting called from another service through the http inbound gateway.

I am using the below configuration for my application :

```<code><int:channel id="xappSearchRequest" />
<int:channel id="xappSearchResponse" />

<int:channel id="xappFilterChannelOutput"/>
<int:channel id="discardFilterChannel"/>
<int:channel id="mutableMessageChannel"/>

<int:filter  input-channel="mutableMessageChannel" output-channel="xappFilterChannelOutput" discard-channel="discardFilterChannel" ref="structureValidationFilter"/>

 <int:transformer input-channel="xappSearchRequest" output-channel="mutableMessageChannel"
    ref="mutableMessageTransformer" />

<int-http:inbound-gateway id="inboundxappSearchRequestGateway"
    supported-methods="POST"
    request-channel="xappSearchRequest"
    reply-channel="xappSearchResponse"
    mapped-response-headers="Return-Status, Return-Status-Msg, HTTP_RESPONSE_HEADERS"
    path="${xapp.request.path}"
    reply-timeout="50000"
    request-payload-type="standalone.CFIRequestBody">
</int-http:inbound-gateway>

<int:service-activator id="xappServiceActivator"
                input-channel="xappFilterChannelOutput"
                output-channel="xappSearchResponse"
                ref="xappSearchService"
                method="handlexappRequest"
                requires-reply="true"
                send-timeout="60000"/>

<int:service-activator id="dicardPayloadServiceActivator"
                input-channel="discardFilterChannel"
                output-channel="xappSearchResponse"
                ref="invalidPayloadService"
                method="getInvalidMessage"
                requires-reply="true"
                send-timeout="60000"/>

<int-http:outbound-gateway id="get.outbound.gateway"
    request-channel="get_send_channel" url="${cms.stub.request.url}"
    http-method="POST" reply-channel="get_receive_channel"
    expected-response-type="standalone.StubResponseBody">
</int-http:outbound-gateway>
</code>```

Not able to figure out how to send a JSON payload and custom headers to call the POST endpoint.

答:
Custom headers can be mapped to HTTP headers using an appropriate property - mapped-request-headers.

There is a full documentation on the matter: https://docs.spring.io/spring-integration/docs/5.2.3.RELEASE/reference/html/http.html#http-header-mapping

For JSON request the <int-http:outbound-gateway> is supplied with the RestTemplate which has a MappingJackson2HttpMessageConverter configured if you have a jackson-databind on classpath. Only what you need from your application is to send a POJO which can be serialized into a JSON and what is important - a MessageHeaders.CONTENT_TYPE header with an application/json value.

Body:
I want to invoke an external REST endpoint POST request with a JSON payload which would be getting called from another service through the http inbound gateway.

I am using the below configuration for my application :

<int:channel id="xappSearchRequest" />
<int:channel id="xappSearchResponse" />

<int:channel id="xappFilterChannelOutput"/>
<int:channel id="discardFilterChannel"/>
<int:channel id="mutableMessageChannel"/>

<int:filter  input-channel="mutableMessageChannel" output-channel="xappFilterChannelOutput" discard-channel="discardFilterChannel" ref="structureValidationFilter"/>

 <int:transformer input-channel="xappSearchRequest" output-channel="mutableMessageChannel"
    ref="mutableMessageTransformer" />

<int-http:inbound-gateway id="inboundxappSearchRequestGateway"
    supported-methods="POST"
    request-channel="xappSearchRequest"
    reply-channel="xappSearchResponse"
    mapped-response-headers="Return-Status, Return-Status-Msg, HTTP_RESPONSE_HEADERS"
    path="${xapp.request.path}"
    reply-timeout="50000"
    request-payload-type="standalone.CFIRequestBody">
</int-http:inbound-gateway>

<int:service-activator id="xappServiceActivator"
                input-channel="xappFilterChannelOutput"
                output-channel="xappSearchResponse"
                ref="xappSearchService"
                method="handlexappRequest"
                requires-reply="true"
                send-timeout="60000"/>

<int:service-activator id="dicardPayloadServiceActivator"
                input-channel="discardFilterChannel"
                output-channel="xappSearchResponse"
                ref="invalidPayloadService"
                method="getInvalidMessage"
                requires-reply="true"
                send-timeout="60000"/>

<int-http:outbound-gateway id="get.outbound.gateway"
    request-channel="get_send_channel" url="${cms.stub.request.url}"
    http-method="POST" reply-channel="get_receive_channel"
    expected-response-type="standalone.StubResponseBody">
</int-http:outbound-gateway>

Not able to figure out how to send a JSON payload and custom headers to call the POST endpoint.


问:
Elastic Search Date Range Query
I am new to elastic search and I am struggling with date range query. I have to query the records which fall between some particular dates.The JSON records pushed into elastic search database are as follows:

```<code>                "messageid": "Some message id",
                "subject": "subject",
                "emaildate": "2020-01-01 21:09:24",
                "starttime": "2020-01-02 12:30:00",
                "endtime": "2020-01-02 13:00:00",
                "meetinglocation": "some location",
                "duration": "00:30:00",
                "employeename": "Name",
                "emailid": "abc@xyz.com",
                "employeecode": "141479",
                "username": "username",
                "organizer": "Some name",
                "organizer_email": "cde@xyz.com",
</code>```

I have to query the records which has start time between "2020-01-02 12:30:00" to "2020-01-10 12:30:00". I have written a query like this :

```<code>{
   "query":
      {
        "bool":
           {

              "filter": [
                {
                    "range" : {
                        "starttime": {
                             "gte": "2020-01-02 12:30:00",
                             "lte": "2020-01-10 12:30:00"
                         }
                    }
                }
              ]
           }
      }
}
</code>```

This query is not giving results as expected. I assume that the person who has pushed the data into elastic search database at my office has not set the mapping and Elastic Search is dynamically deciding the data type of "starttime" as "text". Hence I am getting inconsistent results.
I can set the mapping like this :

```<code>PUT /meetings
{
  "mappings": {
    "dynamic": false,
    "properties": {
        .
        .
        .
        .
      "starttime": {
        "type": "date",
        "format":"yyyy-MM-dd HH:mm:ss"
      }
        .
        .
        .
    }
  }
}
</code>```

And the query will work but I am not allowed to do so (office policies). What alternatives do I have so that I can achieve my task.

Update :

I assumed the data type to be "Text" but by default Elastic Search applies both "Text" and "Keyword" so that we can implement both Full Text and Keyword based searches. If it is also set as "Keyword" . Will this benefit me in any case. I do not have access to lots of stuff in the office that's why I am unable to debug the query.I only have the search API for which I have to build the query.

GET /meetings/_mapping output :

```<code>  '
  '
  '
 "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
  }

    '
    '
    '
</code>```

答:
Date range queries will not work on text field, for that, you have to use the date field

Since you are working on date fields , best practice is to use the date field.

I would suggest you to reindex your index to another index so that you can change the type of your text field to date field

Step1-: Create index2 using index1 mapping and make sure to change the type of your date field which is text to date type

Step 2-: Run the elasticsearch reindex and reindex all your data from index1 to index2. Since you have changed your field type to date field type. Elasticsearch will now recognize this field as date

```<code>POST _reindex
 {
"source":{ "index": "index1" },
 "dest": { "index": "index2" }
 }
</code>```

Now you can run your Normal date queries on index2

Title: Elastic Search Date Range Query

Body:
I am new to elastic search and I am struggling with date range query. I have to query the records which fall between some particular dates.The JSON records pushed into elastic search database are as follows:

                "messageid": "Some message id",
                "subject": "subject",
                "emaildate": "2020-01-01 21:09:24",
                "starttime": "2020-01-02 12:30:00",
                "endtime": "2020-01-02 13:00:00",
                "meetinglocation": "some location",
                "duration": "00:30:00",
                "employeename": "Name",
                "emailid": "abc@xyz.com",
                "employeecode": "141479",
                "username": "username",
                "organizer": "Some name",
                "organizer_email": "cde@xyz.com",

I have to query the records which has start time between "2020-01-02 12:30:00" to "2020-01-10 12:30:00". I have written a query like this :

{
   "query":
      {
        "bool":
           {

              "filter": [
                {
                    "range" : {
                        "starttime": {
                             "gte": "2020-01-02 12:30:00",
                             "lte": "2020-01-10 12:30:00"
                         }
                    }
                }
              ]
           }
      }
}

This query is not giving results as expected. I assume that the person who has pushed the data into elastic search database at my office has not set the mapping and Elastic Search is dynamically deciding the data type of "starttime" as "text". Hence I am getting inconsistent results.
I can set the mapping like this :

PUT /meetings
{
  "mappings": {
    "dynamic": false,
    "properties": {
        .
        .
        .
        .
      "starttime": {
        "type": "date",
        "format":"yyyy-MM-dd HH:mm:ss"
      }
        .
        .
        .
    }
  }
}

And the query will work but I am not allowed to do so (office policies). What alternatives do I have so that I can achieve my task.

Update :

I assumed the data type to be "Text" but by default Elastic Search applies both "Text" and "Keyword" so that we can implement both Full Text and Keyword based searches. If it is also set as "Keyword" . Will this benefit me in any case. I do not have access to lots of stuff in the office that's why I am unable to debug the query.I only have the search API for which I have to build the query.

GET /meetings/_mapping output :

  '
  '
  '
 "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
  }

    '
    '
    '

Body:
Date range queries will not work on text field, for that, you have to use the date field

Since you are working on date fields , best practice is to use the date field.

I would suggest you to reindex your index to another index so that you can change the type of your text field to date field

Step1-: Create index2 using index1 mapping and make sure to change the type of your date field which is text to date type

Step 2-: Run the elasticsearch reindex and reindex all your data from index1 to index2. Since you have changed your field type to date field type. Elasticsearch will now recognize this field as date

POST _reindex
 {
"source":{ "index": "index1" },
 "dest": { "index": "index2" }
 }

Now you can run your Normal date queries on index2


问:
Openapi3 and CSV response (for Dredd)
I test my Api with DREDD against it's specification (written in Openapi3 considering, painfull limitations of Support by Dredd considered). No I have one endpoint, which produces CSV-data if the Accept-header is set so.

    '/my-endpoint':
        summary: ...
        description: ...
        get:
 #          parameters:
 #              -
 #                  in: header
 #                  name: Accept
 #                  description: "Response format: application/json or text/csv"
 #                  example: "text/csv"
            responses:
                '200':
                    description: ...
                    content:
                        text/csv:
                            schema:
                                type: string
                            example:
                                summary: 'csv table'
                                value: 'cell1, cell2'

```

<p>When I run the test with Dredd the test fails with</p>

```
expected:
headers:

body:
[
  {
    "key": "summary",
    "value": "csv table"
  },
  {
    "key": "value",
    "value": "cell1, cell2"
  }
]
statusCode: 200

```

<p>Clearly there is something misunderstood and Dredd expects still JSON. Also the API is not told to produce the CSV Version. If I commit in the Accept header in the code abvoe I get the very same result - the expecetd result above and as actual result the JSON version of the my-endpoint-data and also ad warning: </p>

```warn: API description parser warning in .../tmp/transformed.specs.yml: 'Parameter Object' 'name' in location 'header' should not be 'Accept', 'Content-Type' or 'Authorization'
```

I read here and here: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers, use the corresponding OpenAPI keywords - but what are they? According to this and this page it seems to be enough to specify a response of the given type but that is clearly not enough to tell Dredd to produce such a header.

答:
You got an error because the value of the example key is meant to be a literal example value. So in your case it's treated as an object with the summary and value properties.

Change your definition to:

                    content:
                        text/csv:
                            schema:
                                type: string
                            example: 'cell1, cell2'
```

<p>Or if you want to provide a summary/description for an example, use <code>examples</code> instead:</p>

<pre class="lang-yaml prettyprint-override"><code>                    content:
                        text/csv:
                            schema:
                                type: string
                            examples:
                                csv table:
                                    summary: A CSV table with 2 cells
                                    value: 'cell1, cell2'
</code>```

Title: Openapi3 and CSV response (for Dredd)

Body:
I test my Api with DREDD against it's specification (written in Openapi3 considering, painfull limitations of Support by Dredd considered). No I have one endpoint, which produces CSV-data if the Accept-header is set so.

    '/my-endpoint':
        summary: ...
        description: ...
        get:
 #          parameters:
 #              -
 #                  in: header
 #                  name: Accept
 #                  description: "Response format: application/json or text/csv"
 #                  example: "text/csv"
            responses:
                '200':
                    description: ...
                    content:
                        text/csv:
                            schema:
                                type: string
                            example:
                                summary: 'csv table'
                                value: 'cell1, cell2'

When I run the test with Dredd the test fails with

expected:
headers:

body:
[
  {
    "key": "summary",
    "value": "csv table"
  },
  {
    "key": "value",
    "value": "cell1, cell2"
  }
]
statusCode: 200

Clearly there is something misunderstood and Dredd expects still JSON. Also the API is not told to produce the CSV Version. If I commit in the Accept header in the code abvoe I get the very same result - the expecetd result above and as actual result the JSON version of the my-endpoint-data and also ad warning:

warn: API description parser warning in .../tmp/transformed.specs.yml: 'Parameter Object' 'name' in location 'header' should not be 'Accept', 'Content-Type' or 'Authorization'

I read here and here: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers, use the corresponding OpenAPI keywords - but what are they? According to this and this page it seems to be enough to specify a response of the given type but that is clearly not enough to tell Dredd to produce such a header.

Body:
You got an error because the value of the example key is meant to be a literal example value. So in your case it's treated as an object with the summary and value properties.

Change your definition to:

                    content:
                        text/csv:
                            schema:
                                type: string
                            example: 'cell1, cell2'

Or if you want to provide a summary/description for an example, use examples instead:

                    content:
                        text/csv:
                            schema:
                                type: string
                            examples:
                                csv table:
                                    summary: A CSV table with 2 cells
                                    value: 'cell1, cell2'


问:
Restructure Date in R
I have dataset like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4
</code>```

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

```<code>a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a
</code>```

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

```<code>df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")
</code>```

It's giving the desired result but it's filling alternate NA values in DATE column like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4
</code>```

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

答:
How about:</p>

```<code>df$DATE = format(lubridate::parse_date_time(df$DATE, c('dmy','dby')), '%d-%b-%Y')
</code>```

Title: Restructure Date in R

Body:
I have dataset like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")

It's giving the desired result but it's filling alternate NA values in DATE column like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

Body:
How about:

df$DATE = format(lubridate::parse_date_time(df$DATE, c('dmy','dby')), '%d-%b-%Y')


问:
Accessing SQLite database in android emulator
i am working on an android app which stores data in sqlite db  i want to be able to access the data that is currently stored in the emulator. How do i go about connecting  to it and perform sql operations.</p>

答:
In the eclipse, go in to FileExplorer, here you will find three root folders: here go in to
1.data
2.go in to data folder again
3. here you will find all the package names of the applications.
4. once you find your projects particular package, click on it.
5.you will see a folder called 'databases'
6.in that folder you will get the sqlite db file.
7.in order to pull it out of the emulator, just click on it and on the
  top right corner you will find 3 icons: one to delete, one to pull a file from device and the other to push file in the device.
8. after selecting the db file, click on the icon that says 'pull a file from the device'.
 Thats it mate ...cheers.</p>


问:
Circuit breaker with kafka consumer
Is there a way to implement a circuit breaker pattern with Spring Kafka based consumer . I am wondering while implementing my Spring kafka consumer is it possible to stop consuming records if there is a failure to process the data based on some external system and which throws  a network error. However if the network issue is resolved the consumer should again process normally.

答:
You can refer this solution if you want to stop consuming messages when downstream service or DB is down.

Example

Consumer is calling service A

Service A is calling External HTTP service B

You want to setup circuit breaker when external Service B  is down

In this case you can setup circuit breaker on Service A. Whenever External Service B is down then this circuit will open. Then upon state transition of this circuit breaker, call your listener/bindings(if you are using spring-cloud-stream) to stop/pause consumer. So your messages will stay on queue/topic until the circuit breaker is closed again & you dont have to deadletter messages or put them onto error queue/topic.

You can refer below link for detailed solution which uses Resilience4j for circuit breaker implementation & spring-cloud-stream for consumer.

https://dublincoders.com/circuit-breaker-kafka/

Title: Circuit breaker with kafka consumer


问:
How to write reproduction health data in google fit?
I'm trying to read reproductive health data (menstrual flow) from google fit api for android but I can't test it as there is currently no data to read, so I decided to write the data in the app but It isn't going well. Here is my code:
I'm getting error on setDataType(HealthDataTypes.TYPE_MENSTRUATION): must set data source type</p>

```<code>        DataSource menstruationSource = new DataSource.Builder()
        .setDataType(HealthDataTypes.TYPE_MENSTRUATION)
        .build();
        DataSet dataSet = DataSet.create(menstruationSource);
        DataPoint bloodPressure = DataPoint.builder(menstruationSource)
        .setTimestamp(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
        .setField(HealthFields.FIELD_MENSTRUAL_FLOW, HealthFields.MENSTRUAL_FLOW_MEDIUM)
        .build();
        dataSet.add(bloodPressure);
        Object dataReadResult = Fitness.HistoryApi.insertData(googleFitManager.getGoogleApiClient(), dataSet);
</code>```

答:
It's saying that you need to set the type of the data source (not just the data type):

```<code>new DataSource.Builder()
      .setDataType(HealthDataTypes.TYPE_MENSTRUATION)
      .setType(DataSource.TYPE_RAW)  // <-- THIS
</code>```

(I'm not claiming this is sufficient to create it; merely, that's what the error message is saying you should do).

But, menstruation is a restricted data type. In order to be able to access these data types, your app needs to be specially verified.

As the note says:

Google has temporarily stopped taking new requests to write to restricted data types. We are updating our policy and process for reviewing requests and will update this documentation again when we resume.

Body:
I'm trying to read reproductive health data (menstrual flow) from google fit api for android but I can't test it as there is currently no data to read, so I decided to write the data in the app but It isn't going well. Here is my code:
I'm getting error on setDataType(HealthDataTypes.TYPE_MENSTRUATION): must set data source type

        DataSource menstruationSource = new DataSource.Builder()
        .setDataType(HealthDataTypes.TYPE_MENSTRUATION)
        .build();
        DataSet dataSet = DataSet.create(menstruationSource);
        DataPoint bloodPressure = DataPoint.builder(menstruationSource)
        .setTimestamp(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
        .setField(HealthFields.FIELD_MENSTRUAL_FLOW, HealthFields.MENSTRUAL_FLOW_MEDIUM)
        .build();
        dataSet.add(bloodPressure);
        Object dataReadResult = Fitness.HistoryApi.insertData(googleFitManager.getGoogleApiClient(), dataSet);

Body:
It's saying that you need to set the type of the data source (not just the data type):

new DataSource.Builder()
      .setDataType(HealthDataTypes.TYPE_MENSTRUATION)
      .setType(DataSource.TYPE_RAW)  // <-- THIS

(I'm not claiming this is sufficient to create it; merely, that's what the error message is saying you should do).

But, menstruation is a restricted data type. In order to be able to access these data types, your app needs to be specially verified.

As the note says:

Google has temporarily stopped taking new requests to write to restricted data types. We are updating our policy and process for reviewing requests and will update this documentation again when we resume.


问:
Kotlin equivalent of %@ in swift
i am new to kotlin.
In swift i can do :

```<code>let endpoint = "categories/" + "%@/issues/"
let number = "4"
let finalstring = String(format: endpoint, number)
</code>```

The final output of the string will be : categories/4/issues/ as a string .

I have looked at string format in kotlin but it's only work afterwards meaning that i can't define a template for my string and fill it later.

```<code>var value1 = "categories/"
var value2 = 4
var value3 = "/issues/"
println(java.lang.String.format("%s%d%s", value1, value2, value3))
</code>```

This give me the same result but it's mean that i have to manualy write the end of the string.

What i want to do i to have a template for my string in a Road file.
Then complet my string at the run time. The probleme is that the part of my string that i want to complete is in the middle of the string.
Of course i can use substring and remplace but i am looking for a clean way to do it as in swift.

Thanks for helping.

答:
You already have the answer right there in your example, you just have to put it together.

String.format takes %s as placeholder for a String or %d for a number (and many more placeholder options).

So your template string would be: "categories/%d/issues/". To format it you use:

```<code>val format = "categories/%d/issues/"
val number = 4
val string = String.format(format, number)
</code>```

About interpolation vs formatting, they can be used in different situations.

If you have the template string available in source code then you would use interpolation:

```<code>val string = "categories/${category.id}/issues/"
</code>```

But when you have no control over the string, because it comes from an external source (such as a file), then you would have to use the formatting.

Title: Kotlin equivalent of %@ in swift

Body:
i am new to kotlin.
In swift i can do :

let endpoint = "categories/" + "%@/issues/"
let number = "4"
let finalstring = String(format: endpoint, number)

The final output of the string will be : categories/4/issues/ as a string .

I have looked at string format in kotlin but it's only work afterwards meaning that i can't define a template for my string and fill it later.

var value1 = "categories/"
var value2 = 4
var value3 = "/issues/"
println(java.lang.String.format("%s%d%s", value1, value2, value3))

This give me the same result but it's mean that i have to manualy write the end of the string.

What i want to do i to have a template for my string in a Road file.
Then complet my string at the run time. The probleme is that the part of my string that i want to complete is in the middle of the string.
Of course i can use substring and remplace but i am looking for a clean way to do it as in swift.

Thanks for helping.

Body:
You already have the answer right there in your example, you just have to put it together.

String.format takes %s as placeholder for a String or %d for a number (and many more placeholder options).

So your template string would be: "categories/%d/issues/". To format it you use:

val format = "categories/%d/issues/"
val number = 4
val string = String.format(format, number)

About interpolation vs formatting, they can be used in different situations.

If you have the template string available in source code then you would use interpolation:

val string = "categories/${category.id}/issues/"

But when you have no control over the string, because it comes from an external source (such as a file), then you would have to use the formatting.


问:
Writing new tag to XMP group with configured exiftool doesn't work
I need to add new tags to many images, the tags are:

```<code>AboveGroundAltitude
BandName
CentralWaveLength
ColorTransform
PerspectiveDistortion
PerspectiveFocalLength
PrincipalPoint
WavelengthFWHM
</code>```

I created this configuration file:

```<code>
%Image::ExifTool::UserDefined = (

  'Image::ExifTool::XMP::xmp' => {
    NewXMPxmpTag => { Groups => { 1 => 'AboveGroundAltitude' } },
    NewXMPxmpTag => { Groups => { 1 => 'BandName' } },
    NewXMPxmpTag => { Groups => { 1 => 'CentralWaveLength' } },
    NewXMPxmpTag => { Groups => { 1 => 'ColorTransform' } },
    NewXMPxmpTag => { Groups => { 1 => 'PerspectiveDistortion' } },
    NewXMPxmpTag => { Groups => { 1 => 'PerspectiveFocalLength' } },
    NewXMPxmpTag => { Groups => { 1 => 'PrincipalPoint' } },
    NewXMPxmpTag => { Groups => { 1 => 'WavelengthFWHM' } },
    },
);
</code>```

Variations: I've tried group 0 the first time, then read somewhere that XMP tags belong to group 1 and edited accodingly.

And I'm running the command like this:

```<code>exiftool -config config.txt -ext jpg \
-AboveGroundAltitude='55.8224668413325'\
-BandName='Red, Garbage, NIR'\
-CentralWaveLength='625, 0, 850'\
-ColorTransform='1.000, 0.000, -0.996, 0.000, 0.000, 0.000, -0.286, 0.000, 4.350'\
-PerspectiveDistortion='-0.093, 0.122, 0.000, 0.000, 0.000'\
-PerspectiveFocalLength='5.4'
-PrincipalPoint='3.100, 2.325'\
-WavelengthFWHM='100, 0, 40' test.jpg
</code>```

Variations tried:

```<code>- -xmp:AboveGroundAltitude='55.8224668413325'
- -XMP-AboveGroundAltitude='55.8224668413325'
- -XMP-xmp:AboveGroundAltitude='55.8224668413325'
- all the three above with `+=` between the tag and the value
</code>```

Also note the backslashes were added here for clarity, my original command is a one liner with no newlines nor backslashes.

The error I'm getting is (I'm using a mix of options tried here to illustrate different error messages, but when I tried them the style for options were normalized at each try):

Also, used -v4 for more verbose logging

```<code>exiftool -config config.txt -v4 -ext jpg -XMP-AboveGroundAltitude='55.8224668413325' -xmp:BandName='Red, Garbage, NIR' -XMP-xmp:CentralWaveLength='625, 0, 850' -xmp:ColorTransform='1.000, 0.000, -0.996, 0.000, 0.000, 0.000, -0.286, 0.000, 4.350' -PerspectiveDistortion='-0.093, 0.122, 0.000, 0.000, 0.000' -xmp:PerspectiveFocalLength='5.4' -xmp:PrincipalPoint='3.100, 2.325' -xmp:WavelengthFWHM='100, 0, 40' test.jpg

Tag 'XMP-AboveGroundAltitude' is not defined or has a bad language code
Warning: Tag 'XMP-AboveGroundAltitude' is not defined or has a bad language code
Tag 'xmp:BandName' is not defined
Warning: Tag 'xmp:BandName' is not defined
Tag 'XMP-xmp:CentralWaveLength' is not defined
Warning: Tag 'XMP-xmp:CentralWaveLength' is not defined

Sorry, xmp:ColorTransform doesn't exist or isn't writable
Warning: Sorry, xmp:ColorTransform doesn't exist or isn't writable

Tag 'PerspectiveDistortion' is not defined
Warning: Tag 'PerspectiveDistortion' is not defined
Tag 'xmp:PerspectiveFocalLength' is not defined
Warning: Tag 'xmp:PerspectiveFocalLength' is not defined
Tag 'xmp:PrincipalPoint' is not defined
Warning: Tag 'xmp:PrincipalPoint' is not defined
Tag 'xmp:WavelengthFWHM' is not defined
Warning: Tag 'xmp:WavelengthFWHM' is not defined
Nothing to do.

</code>```

Notice how the message for ColorTransform is different

Note: Already seen enter link description here and other related posts here and in the exiftool forum.

答:
I found a configuration file made by the camera maker, which I'll paste below:

```<code>#------------------------------------------------------------------------------
# File:         xmp_camera_tags.config
#
# Description:  Adds capability to modify all XMP camera tags
#
#------------------------------------------------------------------------------

%Image::ExifTool::UserDefined = (
    'Image::ExifTool::XMP::Main' => {
        Camera=> {
            SubDirectory => {
                TagTable => 'Image::ExifTool::UserDefined::Camera',
            },
        },
    },
);
%Image::ExifTool::UserDefined::Camera = (
    GROUPS => { 0 => 'XMP', 1 => 'XMP-Camera', 2 => 'Other' },
    NAMESPACE => { 'Camera' => 'http://pix4d.com/Camera/1.0/' },
    WRITABLE => 'string',
    GPSXYAccuracy=> {},
    GPSZAccuracy => {},
    Pitch => {},
    Roll=>{},
    Yaw => {},
    BandName => { List => 'Seq' },
    CentralWavelength => { List => 'Seq' },
    WavelengthFWHM => { List => 'Seq' },
    BandSensitivity => { List => 'Seq' },
    ColorTransform => { List => 'Seq' },
 );

%Image::ExifTool::UserDefined::camera = (
    GROUPS => { 0 => 'XMP', 1 => 'XMP-Camera', 2 => 'Other' },
    NAMESPACE => { 'Camera' => 'http://pix4d.com/Camera/1.0/' },
 );
#------------------------------------------------------------------------------
</code>```

and used that as a template to add the missing tags I needed.

The relevant model info for the Sentera camera is:

```<code>LensModel                       : 5.4mm-0001_0015
Model                           : 21021-03_12MP-ERS-0001
</code>```

Original problem was my employee took a first batch (near 8000) of aerial photos with an old firmware. Later he updated the firmware and did the rest of the work. So when trying to process the images, the ones taken first would produce errors and the processing software refused to work.

Thanks anyway @StartGeek for your comments :)

Clearly my attempt was far, far away from what was needed, but the urgency didn't allow me time to investigate further the proper way to configure Exiftool.

Body:
I need to add new tags to many images, the tags are:

AboveGroundAltitude
BandName
CentralWaveLength
ColorTransform
PerspectiveDistortion
PerspectiveFocalLength
PrincipalPoint
WavelengthFWHM

I created this configuration file:

%Image::ExifTool::UserDefined = (

  'Image::ExifTool::XMP::xmp' => {
    NewXMPxmpTag => { Groups => { 1 => 'AboveGroundAltitude' } },
    NewXMPxmpTag => { Groups => { 1 => 'BandName' } },
    NewXMPxmpTag => { Groups => { 1 => 'CentralWaveLength' } },
    NewXMPxmpTag => { Groups => { 1 => 'ColorTransform' } },
    NewXMPxmpTag => { Groups => { 1 => 'PerspectiveDistortion' } },
    NewXMPxmpTag => { Groups => { 1 => 'PerspectiveFocalLength' } },
    NewXMPxmpTag => { Groups => { 1 => 'PrincipalPoint' } },
    NewXMPxmpTag => { Groups => { 1 => 'WavelengthFWHM' } },
    },
);

Variations: I've tried group 0 the first time, then read somewhere that XMP tags belong to group 1 and edited accodingly.

And I'm running the command like this:

exiftool -config config.txt -ext jpg \
-AboveGroundAltitude='55.8224668413325'\
-BandName='Red, Garbage, NIR'\
-CentralWaveLength='625, 0, 850'\
-ColorTransform='1.000, 0.000, -0.996, 0.000, 0.000, 0.000, -0.286, 0.000, 4.350'\
-PerspectiveDistortion='-0.093, 0.122, 0.000, 0.000, 0.000'\
-PerspectiveFocalLength='5.4'
-PrincipalPoint='3.100, 2.325'\
-WavelengthFWHM='100, 0, 40' test.jpg

Variations tried:

- -xmp:AboveGroundAltitude='55.8224668413325'
- -XMP-AboveGroundAltitude='55.8224668413325'
- -XMP-xmp:AboveGroundAltitude='55.8224668413325'
- all the three above with `+=` between the tag and the value

Also note the backslashes were added here for clarity, my original command is a one liner with no newlines nor backslashes.

The error I'm getting is (I'm using a mix of options tried here to illustrate different error messages, but when I tried them the style for options were normalized at each try):

Also, used -v4 for more verbose logging

exiftool -config config.txt -v4 -ext jpg -XMP-AboveGroundAltitude='55.8224668413325' -xmp:BandName='Red, Garbage, NIR' -XMP-xmp:CentralWaveLength='625, 0, 850' -xmp:ColorTransform='1.000, 0.000, -0.996, 0.000, 0.000, 0.000, -0.286, 0.000, 4.350' -PerspectiveDistortion='-0.093, 0.122, 0.000, 0.000, 0.000' -xmp:PerspectiveFocalLength='5.4' -xmp:PrincipalPoint='3.100, 2.325' -xmp:WavelengthFWHM='100, 0, 40' test.jpg

Tag 'XMP-AboveGroundAltitude' is not defined or has a bad language code
Warning: Tag 'XMP-AboveGroundAltitude' is not defined or has a bad language code
Tag 'xmp:BandName' is not defined
Warning: Tag 'xmp:BandName' is not defined
Tag 'XMP-xmp:CentralWaveLength' is not defined
Warning: Tag 'XMP-xmp:CentralWaveLength' is not defined

Sorry, xmp:ColorTransform doesn't exist or isn't writable
Warning: Sorry, xmp:ColorTransform doesn't exist or isn't writable

Tag 'PerspectiveDistortion' is not defined
Warning: Tag 'PerspectiveDistortion' is not defined
Tag 'xmp:PerspectiveFocalLength' is not defined
Warning: Tag 'xmp:PerspectiveFocalLength' is not defined
Tag 'xmp:PrincipalPoint' is not defined
Warning: Tag 'xmp:PrincipalPoint' is not defined
Tag 'xmp:WavelengthFWHM' is not defined
Warning: Tag 'xmp:WavelengthFWHM' is not defined
Nothing to do.

Notice how the message for ColorTransform is different

Note: Already seen enter link description here and other related posts here and in the exiftool forum.

Body:
I found a configuration file made by the camera maker, which I'll paste below:

#------------------------------------------------------------------------------
# File:         xmp_camera_tags.config
#
# Description:  Adds capability to modify all XMP camera tags
#
#------------------------------------------------------------------------------

%Image::ExifTool::UserDefined = (
    'Image::ExifTool::XMP::Main' => {
        Camera=> {
            SubDirectory => {
                TagTable => 'Image::ExifTool::UserDefined::Camera',
            },
        },
    },
);
%Image::ExifTool::UserDefined::Camera = (
    GROUPS => { 0 => 'XMP', 1 => 'XMP-Camera', 2 => 'Other' },
    NAMESPACE => { 'Camera' => 'http://pix4d.com/Camera/1.0/' },
    WRITABLE => 'string',
    GPSXYAccuracy=> {},
    GPSZAccuracy => {},
    Pitch => {},
    Roll=>{},
    Yaw => {},
    BandName => { List => 'Seq' },
    CentralWavelength => { List => 'Seq' },
    WavelengthFWHM => { List => 'Seq' },
    BandSensitivity => { List => 'Seq' },
    ColorTransform => { List => 'Seq' },
 );

%Image::ExifTool::UserDefined::camera = (
    GROUPS => { 0 => 'XMP', 1 => 'XMP-Camera', 2 => 'Other' },
    NAMESPACE => { 'Camera' => 'http://pix4d.com/Camera/1.0/' },
 );
#------------------------------------------------------------------------------

and used that as a template to add the missing tags I needed.

The relevant model info for the Sentera camera is:

LensModel                       : 5.4mm-0001_0015
Model                           : 21021-03_12MP-ERS-0001

Original problem was my employee took a first batch (near 8000) of aerial photos with an old firmware. Later he updated the firmware and did the rest of the work. So when trying to process the images, the ones taken first would produce errors and the processing software refused to work.

Thanks anyway @StartGeek for your comments :)

Clearly my attempt was far, far away from what was needed, but the urgency didn't allow me time to investigate further the proper way to configure Exiftool.