问:
Difference between Special Variable and Global Variable
In GNU CLISP 2.49.92, the following code:

```<code>(defvar i 1)
(defun g ()
  (format T "g0:~d~%" i)
  (setf i 2)
  (format T "g1:~d~%" i))
(defun f ()
  (setf i 3)
  (format T "f0:~d~%" i)
  (g)
  (format T "f1:~d~%" i))
(f)
</code>```

gives the following output:

```<code>f0:3
g0:3
g1:2
f1:2
NIL
</code>```

Similarly, the following code in C:

```<code>#include <stdio.h>

static int i = 1;

int g (void) {
  printf("g0:%d\n", i);
  i = 2;
  printf("g1:%d\n", i);
}

int f (void) {
  i = 3;
  printf("f0:%d\n", i);
  g();
  printf("f1:%d\n", i);
}

int main() {
    f();
    return 0;
}
</code>```

gives the following output:

```<code>f0:3
g0:3
g1:2
f1:2
</code>```

According the the documentation that I found, defvar creates a special variable that is dynamically scoped. On the other hand, C is a statically scoped language. And yet, the two pieces of code give the same output. What then is the difference between a Special Variable and a Global Variable?

答:
The difference is that a special variable is dynamically scoped: any binding of that name is visible to any code that runs during the dynamic extent of that binding, whether or not that binding is lexically visible to the code.

In what follows I am skating over some things: see notes at the end for some hints as to what I've skated over.

It's important to understand the difference between a binding and an assignment, which is often confused in various languages (notably Python, but not really C):

used as a noun, a binding is an association between a name and a value;

used as a verb, binding a variable creates a new association between a name and a value;

an assignment of a variable modifies an existing binding, it modifies an association between a name and a value.

So, in C:

```<code>void g (void) {
  int i;                        /* a binding */
  int j = 2;                    /* a binding with an initial value */
  i = 1;                        /* an assignment */
  {
    int i;                      /* a binding */
    i = 3;                      /* an assignment to the inner binding of i */
    j = 4;                      /* an assignment to the outer binding of j */
  }
}
</code>```

C calls bindings 'declarations'.

In Lisp (by which I will mean 'Common Lisp' here & below), bindings are created by a small number of primitive binding forms: functions bind their arguments, let establishes bindings and there are some other forms perhaps.  Existing bindings are mutated by, ultimately, setq and some other operators perhaps: setf is a macro which expands to setq in simple cases.

C does not have dynamic bindings: if my g function called some function h then if h tried to refer to i it would either be an error or it would be referring to some global i.

But Lisp does have such bindings, although they are not used by default.

So if you take the default case, bindings work the same way as C (in fact, they don't, but the difference does not matter here):

(defun g ()
  (let ((i)                             ;a binding (initial value will be NIL)
        (j 2))                          ;a binding with a initial value
    (setf i 1)                          ;an assignment
    (let ((i))                          ;a binding
      (setf i 3)                        ;an assignment to the inner binding of i
      (setf j 4))))                     ;an assignment to the outer binding of j
```
<p>In this case you can tell, just by looking (which is what 'lexical' means) which bindings are visible, and which assignments mutate which bindings.</p>
<p>Something like this code would be an error (technically: is undefined behaviour, but I will call it 'an error'):</p>
<pre class="lang-lisp prettyprint-override"><code>(defun g ()
  (let ((i))
    (h)))

(defun h ()
  (setf i 3))                           ;this is an error
</code>```

It's an error because (assuming there's no global binding of i), h can't see the binding established by g and so cannot mutate it.  This is not an error:

(defun g ()
  (let ((i 2))
    (h i)
    i))

(defun h (i)                            ;binds i
  (setf i 3))                           ;mutates that binding
```
<p>But calling <code>g</code> will return <code>2</code>, not <code>3</code> because <code>h</code> is mutating the binding it creates, not the binding <code>g</code> created.</p>
<p>Dynamic bindings work very differently.  The normal way to create them is to use <code>defvar</code> (or <code>defparameter</code>) which declares that a given name is 'globally special' which means that <em>all bindings of that name are dynamic</em> (which is also called 'special').  So consider this code:</p>
<pre class="lang-lisp prettyprint-override"><code>;;; Declare *i* globally special and give it an initial value of 1
(defvar *i* 1)

(defun g ()
  (let ((*i* 2))                        ;dynamically bind *i* to 2
    (h)))

(defun h ()
  *i*)                                  ;refer to the dynamic value of *i*
</code>```

Calling g will return 2.  And in this case:

;;; Declare *i* globally special and give it an initial value of 1
(defvar *i* 1)

(defun g ()
  (let ((*i* 2))                        ;dynamically bind *i* to 2
    (h)
    *i*))

(defun h ()
  (setf *i* 4))                         ;mutate the current dynamic binding of *i*
```
<p>Calling <code>g</code> will return <code>4</code>, because <code>h</code> has mutated the dynamic binding of <code>*i*</code> established by <code>g</code>.  What will this return?</p>
<pre class="lang-lisp prettyprint-override"><code>;;; Declare *i* globally special and give it an initial value of 1
(defvar *i* 1)

(defun g ()
  (let ((*i* 2))                        ;dynamically bind *i* to 2
    (h))
  *i*)

(defun h ()
  (setf *i* 4))                         ;mutate the current dynamic binding of *i*
</code>```

Dynamic bindings are very useful where you want some dynamic state to be established for a computation.  For instance imagine some system which deals with transactions of some kind.  You might write this:

(defvar *current-transaction*)

(defun outer-thing (...)
  (let ((*current-transaction* ...))
    (inner-thing ...)))

(defun inner-thing (...)
  ...
  refer to *current-transaction* ...)
```
<p>Note that <code>*current-transaction*</code> is essentially a bit of 'ambient state': any code in the dynamic scope of a transaction can see it but you don't have to spend some fantastic amount of work to pass it down to all the code.  And note also that you can't do this with globals: you might think that this will work:</p>
<pre class="lang-lisp prettyprint-override"><code>(defun outer-thing (...)
  (setf *current-transaction* ...)
  (inner-thing)
  (setf *current-transaction* nil))
</code>```

And it will, superficially ... until you get an error which leaves *current-transaction* assigned to some bogus thing.  Well you can deal with that in CL:

(defun outer-thing (...)
  (setf *current-transaction* ...)
  (unwind-protect
      (inner-thing)
    (setf *current-transaction* nil)))
```

The unwind-protect form will mean that *current-transaction* always gets assigned to nil on the way out, regardless of whether an error happened.  And that seems to work even better ... until you start using multiple threads, at which point you die screaming, because now *current-transaction* is shared across all the threads and you're just doomed (see below): If you want dynamic bindings, you need dynamic bindings, and you can't, in fact, fake them up with assignments.

One important thing is that, because CL does not textually distinguish between operations on dynamic bindings and those on lexical bindings, it's important that there should be a convention about names, so when you read code you can understand it.  For global dynamic variables, this convention is to surround the name with * characters: *foo* not foo.  It's important to use this convention if you do not want to fall into a pit of confusion.

I hope that is enough both to understand what bindings are, how they differ from assignments, and what dynamic bindings are and why they're interesting.

Notes.

There are other lisps than Common Lisp of course.  They have different rules (for instance, for a long time in elisp, all bindings were dynamic).

In CL and its relations, dynamic bindings are called 'special' bindings, and dynamic variables are therefore 'special variables'.

It is possible to have variables which are only local but are dynamically bound, although I have not talked about them.

Primitively, Common Lisp does not support variables which are both global and lexical: all the constructs which create global variables create global dynamic (or special) variables.  However CL is powerful enough that it's pretty easy to simulate global lexicals if you wan them.

There is some dispute about what an assignment to an undeclared  variable (one for which there is no apparent binding) should do, which I alluded to above.  Some people claim this is OK: they are heretics and should be shunned.  Of course they regard me as a heretic and think I should be shunned...

There is a subtlety about things like (defvar *foo*): this declares that *foo* is a dynamic variable, but doesn't give it an initial value: it is globally dynamic, but globally unbound.

Common Lisp does not define any kind of threading interface so, technically, how special variables work in the presence of threads is undefined.  I'm sure that in practice all implementations which have multiple threads deal with special bindings as I've described above, because anything else would be awful.  Some (perhaps all) implementations (maybe all) allow you to specify that new threads get a new set of bindings of some global variables but that doesn't alter any of this.

There will be other things I have missed.

Body:
In GNU CLISP 2.49.92, the following code:

(defvar i 1)
(defun g ()
  (format T "g0:~d~%" i)
  (setf i 2)
  (format T "g1:~d~%" i))
(defun f ()
  (setf i 3)
  (format T "f0:~d~%" i)
  (g)
  (format T "f1:~d~%" i))
(f)

gives the following output:

f0:3
g0:3
g1:2
f1:2
NIL

Similarly, the following code in C:

#include <stdio.h>

static int i = 1;

int g (void) {
  printf("g0:%d\n", i);
  i = 2;
  printf("g1:%d\n", i);
}

int f (void) {
  i = 3;
  printf("f0:%d\n", i);
  g();
  printf("f1:%d\n", i);
}

int main() {
    f();
    return 0;
}

gives the following output:

f0:3
g0:3
g1:2
f1:2

According the the documentation that I found, defvar creates a special variable that is dynamically scoped. On the other hand, C is a statically scoped language. And yet, the two pieces of code give the same output. What then is the difference between a Special Variable and a Global Variable?

Body:
The difference is that a special variable is dynamically scoped: any binding of that name is visible to any code that runs during the dynamic extent of that binding, whether or not that binding is lexically visible to the code.

In what follows I am skating over some things: see notes at the end for some hints as to what I've skated over.

It's important to understand the difference between a binding and an assignment, which is often confused in various languages (notably Python, but not really C):

used as a noun, a binding is an association between a name and a value;

used as a verb, binding a variable creates a new association between a name and a value;

an assignment of a variable modifies an existing binding, it modifies an association between a name and a value.

So, in C:

void g (void) {
  int i;                        /* a binding */
  int j = 2;                    /* a binding with an initial value */
  i = 1;                        /* an assignment */
  {
    int i;                      /* a binding */
    i = 3;                      /* an assignment to the inner binding of i */
    j = 4;                      /* an assignment to the outer binding of j */
  }
}

C calls bindings 'declarations'.

In Lisp (by which I will mean 'Common Lisp' here & below), bindings are created by a small number of primitive binding forms: functions bind their arguments, let establishes bindings and there are some other forms perhaps.  Existing bindings are mutated by, ultimately, setq and some other operators perhaps: setf is a macro which expands to setq in simple cases.

C does not have dynamic bindings: if my g function called some function h then if h tried to refer to i it would either be an error or it would be referring to some global i.

But Lisp does have such bindings, although they are not used by default.

So if you take the default case, bindings work the same way as C (in fact, they don't, but the difference does not matter here):

(defun g ()
  (let ((i)                             ;a binding (initial value will be NIL)
        (j 2))                          ;a binding with a initial value
    (setf i 1)                          ;an assignment
    (let ((i))                          ;a binding
      (setf i 3)                        ;an assignment to the inner binding of i
      (setf j 4))))                     ;an assignment to the outer binding of j

In this case you can tell, just by looking (which is what 'lexical' means) which bindings are visible, and which assignments mutate which bindings.

Something like this code would be an error (technically: is undefined behaviour, but I will call it 'an error'):

(defun g ()
  (let ((i))
    (h)))

(defun h ()
  (setf i 3))                           ;this is an error

It's an error because (assuming there's no global binding of i), h can't see the binding established by g and so cannot mutate it.  This is not an error:

(defun g ()
  (let ((i 2))
    (h i)
    i))

(defun h (i)                            ;binds i
  (setf i 3))                           ;mutates that binding

But calling g will return 2, not 3 because h is mutating the binding it creates, not the binding g created.

Dynamic bindings work very differently.  The normal way to create them is to use defvar (or defparameter) which declares that a given name is 'globally special' which means that all bindings of that name are dynamic (which is also called 'special').  So consider this code:

;;; Declare *i* globally special and give it an initial value of 1
(defvar *i* 1)

(defun g ()
  (let ((*i* 2))                        ;dynamically bind *i* to 2
    (h)))

(defun h ()
  *i*)                                  ;refer to the dynamic value of *i*

Calling g will return 2.  And in this case:

;;; Declare *i* globally special and give it an initial value of 1
(defvar *i* 1)

(defun g ()
  (let ((*i* 2))                        ;dynamically bind *i* to 2
    (h)
    *i*))

(defun h ()
  (setf *i* 4))                         ;mutate the current dynamic binding of *i*

Calling g will return 4, because h has mutated the dynamic binding of *i* established by g.  What will this return?

;;; Declare *i* globally special and give it an initial value of 1
(defvar *i* 1)

(defun g ()
  (let ((*i* 2))                        ;dynamically bind *i* to 2
    (h))
  *i*)

(defun h ()
  (setf *i* 4))                         ;mutate the current dynamic binding of *i*

Dynamic bindings are very useful where you want some dynamic state to be established for a computation.  For instance imagine some system which deals with transactions of some kind.  You might write this:

(defvar *current-transaction*)

(defun outer-thing (...)
  (let ((*current-transaction* ...))
    (inner-thing ...)))

(defun inner-thing (...)
  ...
  refer to *current-transaction* ...)

Note that *current-transaction* is essentially a bit of 'ambient state': any code in the dynamic scope of a transaction can see it but you don't have to spend some fantastic amount of work to pass it down to all the code.  And note also that you can't do this with globals: you might think that this will work:

(defun outer-thing (...)
  (setf *current-transaction* ...)
  (inner-thing)
  (setf *current-transaction* nil))

And it will, superficially ... until you get an error which leaves *current-transaction* assigned to some bogus thing.  Well you can deal with that in CL:

(defun outer-thing (...)
  (setf *current-transaction* ...)
  (unwind-protect
      (inner-thing)
    (setf *current-transaction* nil)))

The unwind-protect form will mean that *current-transaction* always gets assigned to nil on the way out, regardless of whether an error happened.  And that seems to work even better ... until you start using multiple threads, at which point you die screaming, because now *current-transaction* is shared across all the threads and you're just doomed (see below): If you want dynamic bindings, you need dynamic bindings, and you can't, in fact, fake them up with assignments.

One important thing is that, because CL does not textually distinguish between operations on dynamic bindings and those on lexical bindings, it's important that there should be a convention about names, so when you read code you can understand it.  For global dynamic variables, this convention is to surround the name with * characters: *foo* not foo.  It's important to use this convention if you do not want to fall into a pit of confusion.

I hope that is enough both to understand what bindings are, how they differ from assignments, and what dynamic bindings are and why they're interesting.

Notes.

There are other lisps than Common Lisp of course.  They have different rules (for instance, for a long time in elisp, all bindings were dynamic).

In CL and its relations, dynamic bindings are called 'special' bindings, and dynamic variables are therefore 'special variables'.

It is possible to have variables which are only local but are dynamically bound, although I have not talked about them.

Primitively, Common Lisp does not support variables which are both global and lexical: all the constructs which create global variables create global dynamic (or special) variables.  However CL is powerful enough that it's pretty easy to simulate global lexicals if you wan them.

There is some dispute about what an assignment to an undeclared  variable (one for which there is no apparent binding) should do, which I alluded to above.  Some people claim this is OK: they are heretics and should be shunned.  Of course they regard me as a heretic and think I should be shunned...

There is a subtlety about things like (defvar *foo*): this declares that *foo* is a dynamic variable, but doesn't give it an initial value: it is globally dynamic, but globally unbound.

Common Lisp does not define any kind of threading interface so, technically, how special variables work in the presence of threads is undefined.  I'm sure that in practice all implementations which have multiple threads deal with special bindings as I've described above, because anything else would be awful.  Some (perhaps all) implementations (maybe all) allow you to specify that new threads get a new set of bindings of some global variables but that doesn't alter any of this.

There will be other things I have missed.


来源: stackexchange

问:
Memory efficient cluster bootstrap
I have a very large dataset (10m observations but reduced to 14 essential variables), and am following the following thread: Cluster bootstrapped standard errors in R for plm functions

My codes after loading libraries are:

```<code>fe_pois <- fepois(totalcountdeals ~ logdist + inst_dist_std + whited_wu_std:findev_std | iso_o_code + sic2, vcov=~pair, data = cbma, nthreads = 2)

boot_feols <- boottest(fe_pois, clustid = "pair", param = "logdist", B = 199, nthreads = 2)

</code>```

However, this fails with large enough memory.  Any other solutions.  I need to bootstrap standard errors because one of my regressors is an estimate.

I have also tried filtering the data, and run the above on a sub-sample, just for a try.  New error there is;

```<code>Error in if (!is.numeric(lower) || !is.numeric(upper) || lower >= upper) stop("lower < upper  is not fulfilled") :
  missing value where TRUE/FALSE needed
</code>```

答:
Thanks for your question!

fwildclusterboot::boottest() only supports estimation of OLS models, so running a Poisson regression should in fact throw an error in boottest(). I will have to add an error condition for that :)

The error that you observe

```<code>Error in if (!is.numeric(lower) || !is.numeric(upper) || lower >= upper) stop("lower < upper  is not fulfilled") :
  missing value where TRUE/FALSE needed
</code>```

stems from the numerical root finding procedure employed to compute confidence intervals - and I believe it is a direct result of fwildclusterboot not supporting Poisson regression.

The memory problems in both boottest and fwildclusterboot arise either because

the model you are fitting is very big and fwildclusterboot only accepts one fixed effect - all other factor variables specified in fixest are translated to dummies, hence the design matrix passed to boottest() might be very large. In fact if you do not use the fe argument for fwildclusterboot::boottest(), all fixed effects specified in feols() will be translated to dummies and no fixed effect is outprojected within the bootstrap. You can check if this is the root of your error by running your regression via lm() or glm() (or via a similar command in Stata) and see if these estimations fail due to memory as well .

boottest and fwildclusterboot are fully vectorized - hence both compute a weights matrix v, which is of dimension G x B, where G is the number of clusters and B the number of bootstrap iterations. If both G and B are large, this consumes quite a bit of memory! Stata.boottest has a function argument, matsize, that aims to help in such a situation - I quote from the documentation:
"matsize(#) limits the memory demand of the G × B matrix v∗ to prevent caching of virtual
memory to disk. The limit is specified in gigabytes; e.g., matsize(8) would limit the memory
demand to 8GB. Note that this option does not limit the actual size of v∗. Instead, it forces
boottest to break the matrix into chunks no larger than the limit, and then create and destroy
each chunk in turn"

So I would suggest that you try out the matsize argument in boottest and see if your error occurs due to a large weights matrix?

Memory is a known issue for fwildclusterboot, and improving memory performance is work in progress.

Last, there is also a new Julia implementation of the fast wild cluster bootstrap algorithm in WildBootTests.jl that supports ML based models and is - in my experience - less memory demanding than fwildclusterboot.

Update 1
See also this discussion on using boottest and pplmhdfe.

Update 2
If you want to run the wild cluster bootstrap because you are afraid that the your numbers of clusters is low & your standard errors might be biased, an alternative might be to try a degrees-of-freedom correction as implemented for glm() in the clubSandwich package. Though I have to admit that I am not sure how well the implemented corrections work for Poisson regression.

ContentLicense: CC BY-SA 4.0

Title: Memory efficient cluster bootstrap

Body:
I have a very large dataset (10m observations but reduced to 14 essential variables), and am following the following thread: Cluster bootstrapped standard errors in R for plm functions

My codes after loading libraries are:

fe_pois <- fepois(totalcountdeals ~ logdist + inst_dist_std + whited_wu_std:findev_std | iso_o_code + sic2, vcov=~pair, data = cbma, nthreads = 2)

boot_feols <- boottest(fe_pois, clustid = "pair", param = "logdist", B = 199, nthreads = 2)

However, this fails with large enough memory.  Any other solutions.  I need to bootstrap standard errors because one of my regressors is an estimate.

I have also tried filtering the data, and run the above on a sub-sample, just for a try.  New error there is;

Error in if (!is.numeric(lower) || !is.numeric(upper) || lower >= upper) stop("lower < upper  is not fulfilled") :
  missing value where TRUE/FALSE needed

Body:
Thanks for your question!

fwildclusterboot::boottest() only supports estimation of OLS models, so running a Poisson regression should in fact throw an error in boottest(). I will have to add an error condition for that :)

The error that you observe

Error in if (!is.numeric(lower) || !is.numeric(upper) || lower >= upper) stop("lower < upper  is not fulfilled") :
  missing value where TRUE/FALSE needed

stems from the numerical root finding procedure employed to compute confidence intervals - and I believe it is a direct result of fwildclusterboot not supporting Poisson regression.

The memory problems in both boottest and fwildclusterboot arise either because

the model you are fitting is very big and fwildclusterboot only accepts one fixed effect - all other factor variables specified in fixest are translated to dummies, hence the design matrix passed to boottest() might be very large. In fact if you do not use the fe argument for fwildclusterboot::boottest(), all fixed effects specified in feols() will be translated to dummies and no fixed effect is outprojected within the bootstrap. You can check if this is the root of your error by running your regression via lm() or glm() (or via a similar command in Stata) and see if these estimations fail due to memory as well .

boottest and fwildclusterboot are fully vectorized - hence both compute a weights matrix v, which is of dimension G x B, where G is the number of clusters and B the number of bootstrap iterations. If both G and B are large, this consumes quite a bit of memory! Stata.boottest has a function argument, matsize, that aims to help in such a situation - I quote from the documentation:
"matsize(#) limits the memory demand of the G × B matrix v∗ to prevent caching of virtual
memory to disk. The limit is specified in gigabytes; e.g., matsize(8) would limit the memory
demand to 8GB. Note that this option does not limit the actual size of v∗. Instead, it forces
boottest to break the matrix into chunks no larger than the limit, and then create and destroy
each chunk in turn"

So I would suggest that you try out the matsize argument in boottest and see if your error occurs due to a large weights matrix?

Memory is a known issue for fwildclusterboot, and improving memory performance is work in progress.

Last, there is also a new Julia implementation of the fast wild cluster bootstrap algorithm in WildBootTests.jl that supports ML based models and is - in my experience - less memory demanding than fwildclusterboot.

Update 1
See also this discussion on using boottest and pplmhdfe.

Update 2
If you want to run the wild cluster bootstrap because you are afraid that the your numbers of clusters is low & your standard errors might be biased, an alternative might be to try a degrees-of-freedom correction as implemented for glm() in the clubSandwich package. Though I have to admit that I am not sure how well the implemented corrections work for Poisson regression.


问:
I want to have a json response from a controller in mvc (dictionary to json)
I have a dictionary of FormCollection named values and I want to add a FormNumber that is only a string to it like the response below:

```<code>Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);

string FormNumber="6";
</code>```

答:
try this</p>
```<code>var FormNumber = "6";

var ValuesList = Values.Select(c => new KeyValuePair<string,string>(c.Key,c.Value) ).ToArray();

var model = new { FormNum = FormNumber, Values =  ValuesList};

return model;

//or I would not recomend

var json= JsonConvert.SerializeObject(model, Newtonsoft.Json.Formatting.Indented);

return json

</code>```

Body:
I have a dictionary of FormCollection named values and I want to add a FormNumber that is only a string to it like the response below:

Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);

string FormNumber="6";

Body:
try this

var FormNumber = "6";

var ValuesList = Values.Select(c => new KeyValuePair<string,string>(c.Key,c.Value) ).ToArray();

var model = new { FormNum = FormNumber, Values =  ValuesList};

return model;

//or I would not recomend

var json= JsonConvert.SerializeObject(model, Newtonsoft.Json.Formatting.Indented);

return json


问:
Using nginx map directive to dynamically set proxy upstream
I'm trying to make my Nginx a bit more dry, as it's acting as a reverse proxy for nearly 20 servers.  Here's what I'm trying to do, all the hostnames and stuff are changed/examples:

```<code>map $http_host $backend {
    baz.mydomain.com       hostname1:8080;
    foo.mydomain.com       192.168.1.10:8081;
    bar.mydomain.com       hostname2:1234;
    ham.mydomain.com       hostname2:5678;
}

server {
    listen                      443 ssl http2;
    server_name                 .mydomain.com;

    ssl_certificate             /usr/share/nginx/certs/mydomain.com.pem;
    ssl_certificate_key         /usr/share/nginx/certs/mydomain.com.key;

    location / {
        proxy_redirect          http:// https://;
        proxy_pass              http://$backend;
    }
}
</code>```

The problem is that no matter what, this will always give a bad gateway error.  I've tried a few variations and moving things around, with and without the wildcard server_name, with $host instead of $http_host but so far I can't get it working.  Am I even going about this the right way?  I'd really prefer not to have almost 20 separate virtual server entries in my config.

There isn't a whole lot of help in the nginx documentation about using map like this, and not a lot online except for one really old post that briefly mentioned something similar here: https://serverfault.com/questions/342309/how-to-write-a-dry-modular-nginx-conf-reverse-proxy-with-named-locations

答:
I figured the details out.

Basically, there is no DNS resolution if we set proxy_pass targets dynamically.

This won't work:

```<code>map $http_host $backend {
    default localhost:8080;
}

proxy_pass http://$backend;
</code>```

But, this work:

```<code>map $http_host $backend {
    default 127.0.0.1:8080;
}

proxy_pass http://$backend;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make my Nginx a bit more dry, as it's acting as a reverse proxy for nearly 20 servers.  Here's what I'm trying to do, all the hostnames and stuff are changed/examples:

map $http_host $backend {
    baz.mydomain.com       hostname1:8080;
    foo.mydomain.com       192.168.1.10:8081;
    bar.mydomain.com       hostname2:1234;
    ham.mydomain.com       hostname2:5678;
}

server {
    listen                      443 ssl http2;
    server_name                 .mydomain.com;

    ssl_certificate             /usr/share/nginx/certs/mydomain.com.pem;
    ssl_certificate_key         /usr/share/nginx/certs/mydomain.com.key;

    location / {
        proxy_redirect          http:// https://;
        proxy_pass              http://$backend;
    }
}

The problem is that no matter what, this will always give a bad gateway error.  I've tried a few variations and moving things around, with and without the wildcard server_name, with $host instead of $http_host but so far I can't get it working.  Am I even going about this the right way?  I'd really prefer not to have almost 20 separate virtual server entries in my config.

There isn't a whole lot of help in the nginx documentation about using map like this, and not a lot online except for one really old post that briefly mentioned something similar here: https://serverfault.com/questions/342309/how-to-write-a-dry-modular-nginx-conf-reverse-proxy-with-named-locations

Body:
I figured the details out.

Basically, there is no DNS resolution if we set proxy_pass targets dynamically.

This won't work:

map $http_host $backend {
    default localhost:8080;
}

proxy_pass http://$backend;

But, this work:

map $http_host $backend {
    default 127.0.0.1:8080;
}

proxy_pass http://$backend;


问:
How to give a border as a background in css without using image and without adding anything to mark-up?
For example here http://jsfiddle.net/jitendravyas/5Wqn4/1/

I want to take
 over red area. How to make is possible without using image and another added more element.

using border is not necessary I just want background like this.

答:
```<code> body {background: yellow;padding: 0px; margin: 0px;}
 h1{background: red;line-height: 10em;margin: 0px;}
</code>```


问:
Azure function trigger with IoT-Hub "EntityPath"
I am currently having troubles with connecting my function trigger to an IoT-Hub, overnight it broke somehow.
Function version 4.
Node.js version 14 LTS.

First I got an error saying I have to use web.jobs version 4.3.0, I changed the host.json to include this

Then it has started giving me a runtime error which I don't know how to fix, the error:

I defined connection string in the portal which has the format

```<code>"Endpoint=sb//{iothub-ns-"somename"-"somenumber".servicebus.windows.net/}; SharedAccessKeyName={NameOfAccessKey};SharedAccessKey={TheKey};EntityPath={Name};
</code>```

Lastly I tried removing the EntityPath which removed the error but then nothing came to the function anymore

Edit:
I got it fixed by changing function version to 3 and reverting the original Host.json to be "version": "[2.*, 3.0.0)".

I have no idea how the runtime version got changed, even when I made new functions they would also get this error. It is probably just something I have done within my workspace that is causing this.

答:
while defining the connection string give the entity path as even hub compatible name</p>
```<code>Endpoint=sb://<Event hub-compatible endpoint>.servicebus.windows.net/;EntityPath=<Event Hub compatible name>;SharedAccessKeyName=<keyName>;SharedAccessKey=<key>"
</code>```

Body:
I am currently having troubles with connecting my function trigger to an IoT-Hub, overnight it broke somehow.
Function version 4.
Node.js version 14 LTS.

First I got an error saying I have to use web.jobs version 4.3.0, I changed the host.json to include this

Then it has started giving me a runtime error which I don't know how to fix, the error:

I defined connection string in the portal which has the format

"Endpoint=sb//{iothub-ns-"somename"-"somenumber".servicebus.windows.net/}; SharedAccessKeyName={NameOfAccessKey};SharedAccessKey={TheKey};EntityPath={Name};

Lastly I tried removing the EntityPath which removed the error but then nothing came to the function anymore

Edit:
I got it fixed by changing function version to 3 and reverting the original Host.json to be "version": "[2.*, 3.0.0)".

I have no idea how the runtime version got changed, even when I made new functions they would also get this error. It is probably just something I have done within my workspace that is causing this.

Body:
while defining the connection string give the entity path as even hub compatible name

Endpoint=sb://<Event hub-compatible endpoint>.servicebus.windows.net/;EntityPath=<Event Hub compatible name>;SharedAccessKeyName=<keyName>;SharedAccessKey=<key>"


问:
Invalid version number: Version number may be negative or greater than 255
I am getting below error when I try to access a page in my application.

```<code>SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.IllegalArgumentException: Invalid version number: Version number may be negative or greater than 255
    at com.ibm.icu.util.VersionInfo.getInstance(VersionInfo.java:191)
    at com.ibm.icu.impl.ICUDebug.getInstanceLenient(ICUDebug.java:65)
    at com.ibm.icu.impl.ICUDebug.<clinit>(ICUDebug.java:69)
</code>```

I assume that it is due to some version mismatch. How can I trace the issue?  The application is not mavenized and hence I am not sure how to check the issue. Atleast if I know which jarfile is giving issue then it will be good.

答:
I solved the problem by updating from 8.0.0.0 to 9.1.0.0</p>
```<code><dependency>
  <groupId>com.ibm.ctg</groupId>
  <artifactId>ctgclient</artifactId>
  <version>9.1.0.0</version>
</dependency>
</code>```

Body:
I am getting below error when I try to access a page in my application.

SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.IllegalArgumentException: Invalid version number: Version number may be negative or greater than 255
    at com.ibm.icu.util.VersionInfo.getInstance(VersionInfo.java:191)
    at com.ibm.icu.impl.ICUDebug.getInstanceLenient(ICUDebug.java:65)
    at com.ibm.icu.impl.ICUDebug.<clinit>(ICUDebug.java:69)

I assume that it is due to some version mismatch. How can I trace the issue?  The application is not mavenized and hence I am not sure how to check the issue. Atleast if I know which jarfile is giving issue then it will be good.

Body:
I solved the problem by updating from 8.0.0.0 to 9.1.0.0

<dependency>
  <groupId>com.ibm.ctg</groupId>
  <artifactId>ctgclient</artifactId>
  <version>9.1.0.0</version>
</dependency>


问:
Get specific value from JSON array after comparison using PowerShell?
I want to get specific value once key is matched from JSON array object

Input:

```<code>[
    {
        "Id": "19A7A3C4",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "apple",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "orange",
                "value": "20"
            },
            {
                "context": "CONTEXTLESS",
                "key": "grapes",
                "value": "30"
            }
        ]
    },
    {
        "Id": "111111",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "20"
            }
        ]
    }
]
</code>```

I want to get the value of tag where key matches to cat and value matches to 10, I am using below query but getting whole object

```<code>$content = Get-Content -Raw -Path "data.json" | ConvertFrom-Json
$content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"}
</code>```

Desired Output: 10

答:
Mathias's answer already shows a clean way to solve the problem.

A similar approach is using the intrinsic method .Where{}:

```<code>$tagValues = $content.tags.Where{ $_.key -eq "cat" -and $_.value -eq "10" }.value
</code>```

$content.tags employs member enumeration to collect all tags properties into an array. .Where{} filters array elements similar to Where-Object. Lastly .value uses member enumeration again to collect the filtered tag values into an array.

Intrinsic methods like .Where{} are supposed to be faster than pipeline commands because they don't involve the overhead of the pipeline machinery.

If you want to keep your original query, you have to deal with nested properties.

Use grouping operator () and dot notation to extract a given property:

```<code>$tagValues = ($content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"}).tags.value
</code>```

An alternative is Select-Object with parameter -ExpandProperty (alias -Expand), but it doesn't work as straightforward for nested properties (yet):

```<code>$tagValues = $content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"} |
    Select-Object -Expand tags | Select-Object -Expand value
</code>```

A more straightforward alternative is ForEach-Object:

```<code>$tagValues = $content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"} |
    ForEach-Object { $_.tags.value }
</code>```

Body:
I want to get specific value once key is matched from JSON array object

Input:

[
    {
        "Id": "19A7A3C4",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "apple",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "orange",
                "value": "20"
            },
            {
                "context": "CONTEXTLESS",
                "key": "grapes",
                "value": "30"
            }
        ]
    },
    {
        "Id": "111111",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "20"
            }
        ]
    }
]

I want to get the value of tag where key matches to cat and value matches to 10, I am using below query but getting whole object

$content = Get-Content -Raw -Path "data.json" | ConvertFrom-Json
$content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"}

Desired Output: 10

Body:
Mathias's answer already shows a clean way to solve the problem.

A similar approach is using the intrinsic method .Where{}:

$tagValues = $content.tags.Where{ $_.key -eq "cat" -and $_.value -eq "10" }.value

$content.tags employs member enumeration to collect all tags properties into an array. .Where{} filters array elements similar to Where-Object. Lastly .value uses member enumeration again to collect the filtered tag values into an array.

Intrinsic methods like .Where{} are supposed to be faster than pipeline commands because they don't involve the overhead of the pipeline machinery.

If you want to keep your original query, you have to deal with nested properties.

Use grouping operator () and dot notation to extract a given property:

$tagValues = ($content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"}).tags.value

An alternative is Select-Object with parameter -ExpandProperty (alias -Expand), but it doesn't work as straightforward for nested properties (yet):

$tagValues = $content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"} |
    Select-Object -Expand tags | Select-Object -Expand value

A more straightforward alternative is ForEach-Object:

$tagValues = $content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"} |
    ForEach-Object { $_.tags.value }


问:
SwiftUI : Converting Int16 to String
I'm learning Swift and I have problems displaying the result of a PickerTextField as an String instead of an Int16...
I'm Using an Int16 because I want to save it to core data...

To pick the Int16 I'm using a pickertextfield:

```<code>struct PickerTextField: UIViewRepresentable{

private let textField = UITextField()
private let pickerView = UIPickerView()
private let helper = Helper()

var data: [String]
var placeholder: String

@Binding var lastSelectedIndex: Int16?

func makeUIView(context: Context) -> UITextField {
    self.pickerView.delegate = context.coordinator
    self.pickerView.dataSource = context.coordinator

    self.textField.placeholder = self.placeholder
    self.textField.inputView = self.pickerView

    //Configure Accesory View
    let toolbar = UIToolbar()
    toolbar.sizeToFit()
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self.helper, action: #selector(self.helper.doneButtonAction))
    toolbar.setItems([flexibleSpace, doneButton], animated: true)
    doneButton.tintColor = UIColor.black
    self.textField.inputAccessoryView = toolbar

    self.helper.doneButtonTapped = {
        if self.lastSelectedIndex == nil {
            self.lastSelectedIndex = 0
        }
        self.textField.resignFirstResponder()
    }

    return self.textField
}

func updateUIView(_ uiView: UITextField, context: Context) {
    if let lastSelectedIndex = self.lastSelectedIndex {
        uiView.text = self.data[Int(lastSelectedIndex)]
    }
}

func makeCoordinator() -> Coordinator {
    return Coordinator(data: self.data) { (index) in
        self.lastSelectedIndex = Int16(index)
    }
}

class Helper {

    public var doneButtonTapped: (() -> Void)?
    @objc func doneButtonAction() {
        self.doneButtonTapped?()
    }
}

class Coordinator: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {

    private var data: [String]
    private var didSelectItem: ((Int) -> Void)?

    init(data: [String], didSelectItem: ((Int) -> Void)? = nil) {
    self.data = data
    self.didSelectItem = didSelectItem
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.data.count

    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return self.data[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.didSelectItem?(row)
    }

    }
}
</code>```

And this is the UI to pick a from the pickertextfield...

```<code>struct PickerView: View {

@State private var lastSelectedIndex: Int16?

var body: some View {
    VStack{
        // Text...
        Text("Choose a Color!")
        //Picker...
        PickerTextField(data: ["Red", "Green", "Blue"], placeholder: "Choose a Color!", lastSelectedIndex: self.$lastSelectedIndex)
    }
}
</code>```

}

Is there a way to convert this 'lastSelectedIndex'(Int16) to an String?

答:
try something like this:

```<code>struct PickerView: View {
    @State private var lastSelectedIndex: Int16? = 0

    var body: some View {
        VStack (spacing: 55) {
            // for testing
            Text("lastSelectedIndex = " + String(lastSelectedIndex ?? 0)) // <--- here
            // Text...
            Text("Choose a Color!")
            //Picker...
            PickerTextField(data: ["Red", "Green", "Blue"],
                            placeholder: "Choose a Color!",
                            lastSelectedIndex: $lastSelectedIndex)
        }
    }
}
</code>```

or

```<code>struct PickerView: View {
    @State private var lastSelectedIndex: Int16? = 0
    @State private var lastSelectedIndexString = "0"

    var body: some View {
        VStack (spacing: 55) {
            // for testing
            Text("lastSelectedIndex = " + String(lastSelectedIndex ?? 0)) // <-- here
            // Text...
            Text("Choose a Color!")
            //Picker...
            PickerTextField(data: ["Red", "Green", "Blue"],
                            placeholder: "Choose a Color!",
                            lastSelectedIndex: $lastSelectedIndex)
        }.onAppear {
            lastSelectedIndexString = String(lastSelectedIndex ?? 0) // <-- here
        }
    }
}
</code>```

Or, using a computed property, such as:

```<code>struct PickerView: View {
    @State private var lastSelectedIndex: Int16? = 0

    var lastSelectedIndexString: String {  // <-- here
        String(lastSelectedIndex ?? 0)
    }

    var body: some View {
        VStack (spacing: 55) {
            // for testing
            Text("lastSelectedIndexString = " + lastSelectedIndexString)  // <-- here
            // Text...
            Text("Choose a Color!")
            //Picker...
            PickerTextField(data: ["Red", "Green", "Blue"],
                            placeholder: "Choose a Color!",
                            lastSelectedIndex: $lastSelectedIndex)
        }
    }
}
</code>```

Title: SwiftUI : Converting Int16 to String

Body:
I'm learning Swift and I have problems displaying the result of a PickerTextField as an String instead of an Int16...
I'm Using an Int16 because I want to save it to core data...

To pick the Int16 I'm using a pickertextfield:

struct PickerTextField: UIViewRepresentable{

private let textField = UITextField()
private let pickerView = UIPickerView()
private let helper = Helper()

var data: [String]
var placeholder: String

@Binding var lastSelectedIndex: Int16?

func makeUIView(context: Context) -> UITextField {
    self.pickerView.delegate = context.coordinator
    self.pickerView.dataSource = context.coordinator

    self.textField.placeholder = self.placeholder
    self.textField.inputView = self.pickerView

    //Configure Accesory View
    let toolbar = UIToolbar()
    toolbar.sizeToFit()
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self.helper, action: #selector(self.helper.doneButtonAction))
    toolbar.setItems([flexibleSpace, doneButton], animated: true)
    doneButton.tintColor = UIColor.black
    self.textField.inputAccessoryView = toolbar

    self.helper.doneButtonTapped = {
        if self.lastSelectedIndex == nil {
            self.lastSelectedIndex = 0
        }
        self.textField.resignFirstResponder()
    }

    return self.textField
}

func updateUIView(_ uiView: UITextField, context: Context) {
    if let lastSelectedIndex = self.lastSelectedIndex {
        uiView.text = self.data[Int(lastSelectedIndex)]
    }
}

func makeCoordinator() -> Coordinator {
    return Coordinator(data: self.data) { (index) in
        self.lastSelectedIndex = Int16(index)
    }
}

class Helper {

    public var doneButtonTapped: (() -> Void)?
    @objc func doneButtonAction() {
        self.doneButtonTapped?()
    }
}

class Coordinator: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {

    private var data: [String]
    private var didSelectItem: ((Int) -> Void)?

    init(data: [String], didSelectItem: ((Int) -> Void)? = nil) {
    self.data = data
    self.didSelectItem = didSelectItem
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.data.count

    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return self.data[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.didSelectItem?(row)
    }

    }
}

And this is the UI to pick a from the pickertextfield...

struct PickerView: View {

@State private var lastSelectedIndex: Int16?

var body: some View {
    VStack{
        // Text...
        Text("Choose a Color!")
        //Picker...
        PickerTextField(data: ["Red", "Green", "Blue"], placeholder: "Choose a Color!", lastSelectedIndex: self.$lastSelectedIndex)
    }
}

}

Is there a way to convert this 'lastSelectedIndex'(Int16) to an String?

Body:
try something like this:

struct PickerView: View {
    @State private var lastSelectedIndex: Int16? = 0

    var body: some View {
        VStack (spacing: 55) {
            // for testing
            Text("lastSelectedIndex = " + String(lastSelectedIndex ?? 0)) // <--- here
            // Text...
            Text("Choose a Color!")
            //Picker...
            PickerTextField(data: ["Red", "Green", "Blue"],
                            placeholder: "Choose a Color!",
                            lastSelectedIndex: $lastSelectedIndex)
        }
    }
}

or

struct PickerView: View {
    @State private var lastSelectedIndex: Int16? = 0
    @State private var lastSelectedIndexString = "0"

    var body: some View {
        VStack (spacing: 55) {
            // for testing
            Text("lastSelectedIndex = " + String(lastSelectedIndex ?? 0)) // <-- here
            // Text...
            Text("Choose a Color!")
            //Picker...
            PickerTextField(data: ["Red", "Green", "Blue"],
                            placeholder: "Choose a Color!",
                            lastSelectedIndex: $lastSelectedIndex)
        }.onAppear {
            lastSelectedIndexString = String(lastSelectedIndex ?? 0) // <-- here
        }
    }
}

Or, using a computed property, such as:

struct PickerView: View {
    @State private var lastSelectedIndex: Int16? = 0

    var lastSelectedIndexString: String {  // <-- here
        String(lastSelectedIndex ?? 0)
    }

    var body: some View {
        VStack (spacing: 55) {
            // for testing
            Text("lastSelectedIndexString = " + lastSelectedIndexString)  // <-- here
            // Text...
            Text("Choose a Color!")
            //Picker...
            PickerTextField(data: ["Red", "Green", "Blue"],
                            placeholder: "Choose a Color!",
                            lastSelectedIndex: $lastSelectedIndex)
        }
    }
}


问:
access xml part from c++ android
i have a textview in xml file with "tv" id

if i declare

```<code>TextView tv ;
tv= findViewByID(R.id.tv);
</code>```

then i can call setText Method with this part

```<code>           extern "C"
        JNIEXPORT void JNICALL
        Java_org_lotka_brilliance_activity_MainActivity_textViewInit(JNIEnv *env, jobject
            thiz) {
            jclass MainCLass =  env->FindClass("org/lotka/brilliance/activity/MainActivity");
            jclass TextViewClass = env->FindClass("android/widget/TextView");
            jfieldID tvfieild = env->GetFieldID(MainCLass , "tv",
            "Landroid/widget/TextView;");
            jmethodID tvsettext = env->GetMethodID(TextViewClass , "setText", "
            (Ljava/lang/CharSequence;)V");
            jobject jobject1 = env->GetObjectField(thiz , tvfieild);
            env->CallVoidMethod(jobject1 ,tvsettext , env->NewStringUTF("hello from jni"));
        }
</code>```

im using the TextView which is declared in java part , now the question is that , if i want to find TextView  id in jni what should i do ??

答:
There will be a generated class com.your.package.R.id which contains a bunch of static ints with the view IDs. So it's just a matter of reading the particular field you're interested in, and then calling findViewById to get the TextView.

I'm not sure why anyone would want to manipulate their app's views in this cumbersome way, but it can be done:

```<code>jclass idClass = env->FindClass("com/your/package/R$id");
jfieldID tvField = env->GetStaticFieldID(idClass, "tv", "I");
jint tvId = env->GetStaticIntField(idClass, tvField);

// thiz is a jobject corresponding to the calling Activity instance
jmethodID findViewById = env->GetMethodID(env->GetObjectClass(thiz), "findViewById", "(I)Landroid/view/View;");
jobject tv = env->CallObjectMethod(thiz, findViewById, tvId);
jmethodID setText = env->GetMethodID(env->GetObjectClass(tv), "setText", "(Ljava/lang/CharSequence;)V");
env->CallVoidMethod(tv, setText, env->NewStringUTF("Hello from JNI!"));
</code>```

Title: access xml part from c++ android

Body:
i have a textview in xml file with "tv" id

if i declare

TextView tv ;
tv= findViewByID(R.id.tv);

then i can call setText Method with this part

           extern "C"
        JNIEXPORT void JNICALL
        Java_org_lotka_brilliance_activity_MainActivity_textViewInit(JNIEnv *env, jobject
            thiz) {
            jclass MainCLass =  env->FindClass("org/lotka/brilliance/activity/MainActivity");
            jclass TextViewClass = env->FindClass("android/widget/TextView");
            jfieldID tvfieild = env->GetFieldID(MainCLass , "tv",
            "Landroid/widget/TextView;");
            jmethodID tvsettext = env->GetMethodID(TextViewClass , "setText", "
            (Ljava/lang/CharSequence;)V");
            jobject jobject1 = env->GetObjectField(thiz , tvfieild);
            env->CallVoidMethod(jobject1 ,tvsettext , env->NewStringUTF("hello from jni"));
        }

im using the TextView which is declared in java part , now the question is that , if i want to find TextView  id in jni what should i do ??

Body:
There will be a generated class com.your.package.R.id which contains a bunch of static ints with the view IDs. So it's just a matter of reading the particular field you're interested in, and then calling findViewById to get the TextView.

I'm not sure why anyone would want to manipulate their app's views in this cumbersome way, but it can be done:

jclass idClass = env->FindClass("com/your/package/R$id");
jfieldID tvField = env->GetStaticFieldID(idClass, "tv", "I");
jint tvId = env->GetStaticIntField(idClass, tvField);

// thiz is a jobject corresponding to the calling Activity instance
jmethodID findViewById = env->GetMethodID(env->GetObjectClass(thiz), "findViewById", "(I)Landroid/view/View;");
jobject tv = env->CallObjectMethod(thiz, findViewById, tvId);
jmethodID setText = env->GetMethodID(env->GetObjectClass(tv), "setText", "(Ljava/lang/CharSequence;)V");
env->CallVoidMethod(tv, setText, env->NewStringUTF("Hello from JNI!"));


问:
Use alembic migration or docker volumes to populate docker postgres database?
I believe this question already shows that I am new to docker and alembic. I am building a flask+sqlalchemy app using docker and postgres. So far I am not using alembic, but I am about to plug it in and some questions came up. I will have to create a pg_trgm extension and also populate one of the tables with data I already have. Until now I have only created brand new databases using sqlalchemy for the tests. So here is what I am thinking/doing:

To create the extension I could simple add a volume to the postgres docker service like: ./pg_dump.sql:/docker-entrypoint-initdb.d/pg_dump.sql. The extension does not depend on any specific db, so a simple "CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;" would do it, right?

If I use the same strategy to populate the tables I need a pg_dump.sql that creates the complete db and tables. To accomplish that I first created the brand new database on sqlalchemy, then I used a script to populate the tables with data I have on a json file. I then generated the complete pg_dump.sql and now I can place this complete .sql file on the docker service volume and when I run my docker-compose the postgres container will have the dabatase ready to go.

Now I am starting with alembic and I am thinking I could just keep the pg_dump.sql to create the extensions, and have a alembic migration script to populate the empty tables (dropping the item 2 above).

Which way is the better way? 2, 3 or none of them? tks

答:
Create the extension in a /docker-entrypoint-initdb.d script (1).  Load the data using your application's migration system (3).

Mechanically, one good reason to do this is that the database init scripts only run the very first time you create a database container on a given storage.  If you add a column to a table and need to run migrations, the init-script sequence requires you to completely throw away and recreate the database.

Philosophically, I'd give you the same answer whether you were using Docker or something else.  You could imagine running a database on a dedicated server, or using a cloud-hosted database.  You'd have to ask your database administrator to install the extension for you, but they'd generally expect to give you credentials to an empty database and have you load the data yourself; or in a cloud setup you could imagine checking a "install this extension" checkbox in their console but there wouldn't be a way to load the data without connecting to the database remotely.

So, a migration system will work anywhere you have access to the database, and will allow incremental changes to the schema.  The init script setup is Docker-specific and requires deleting the database to make any change.


问:
pass 3 rows while applying a function to a column
I have a table that looks like this:

```<code>sumOfSquares      mean     n     std     val
12                323      2             xd
543               42       5             dwjo
</code>```

I want to use the following formula, pass df.sumOfSquares and df.mean from each row to calculate df.std for each row.

```<code>def calculateSD(sumOfSquares, mean, n):
    nominator = sumOfSquares - (mean*mean)
    denominator = n-1
    return nominator/denominator
</code>```

How can I apply the function in such a way that all 3 required cols get passed and the returned value is added to the df.std col?

答:
I don't know if passing in the entire row is an option, but you could use apply as follows:

```<code>import pandas as pd

def calculateSD(row):
  sumOfSquares = row['sumOfSquares']
  mean = row['mean']
  n = row['n']
  nominator = sumOfSquares - (mean*mean)
  denominator = n-1
  return nominator/denominator

df = pd.DataFrame(
  {
    "sumOfSquares": [12, 543],
    "mean": [323, 42],
    "n": [2, 5],
    "val": ["xd", "dwjo"]
  }
)

df['sd'] = df.apply(calculateSD, axis=1)

print(df)
</code>```

Getting the following result:

```<code>   sumOfSquares  mean  n   val         sd
0            12   323  2    xd -104317.00
1           543    42  5  dwjo    -305.25
</code>```

Body:
I have a table that looks like this:

sumOfSquares      mean     n     std     val
12                323      2             xd
543               42       5             dwjo

I want to use the following formula, pass df.sumOfSquares and df.mean from each row to calculate df.std for each row.

def calculateSD(sumOfSquares, mean, n):
    nominator = sumOfSquares - (mean*mean)
    denominator = n-1
    return nominator/denominator

How can I apply the function in such a way that all 3 required cols get passed and the returned value is added to the df.std col?

Body:
I don't know if passing in the entire row is an option, but you could use apply as follows:

import pandas as pd

def calculateSD(row):
  sumOfSquares = row['sumOfSquares']
  mean = row['mean']
  n = row['n']
  nominator = sumOfSquares - (mean*mean)
  denominator = n-1
  return nominator/denominator

df = pd.DataFrame(
  {
    "sumOfSquares": [12, 543],
    "mean": [323, 42],
    "n": [2, 5],
    "val": ["xd", "dwjo"]
  }
)

df['sd'] = df.apply(calculateSD, axis=1)

print(df)

Getting the following result:

   sumOfSquares  mean  n   val         sd
0            12   323  2    xd -104317.00
1           543    42  5  dwjo    -305.25


问:
Audio player returns Uncaught (In promise): (DOMException) The element has no supported sources
So in my audio player (ka-musicplayer.glitch.me) i saw a flaw that when i played audio by typing the path to an MP3 it returned that. If i predefine the MP3s, it works. Feel free to see the code here.

   var input = document.getElementById("input");
      var inputVal = "";
      if (input) {
        inputVal = input.value;
      }

      var player = new Audio(inputVal);
      player.crossOrigin = "anonymous";
  var s2 = document.createElement("button");
      s2.innerText = "Play";
      s2.addEventListener("click", function() {
        player.src = inputVal;
        player.play();
      });
      document.body.appendChild(s2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head></head>
<body>

<input id="input" />
Check JS Console in current browser for error</code>```

答:
I also had trouble when dynamically added songs ended with "Uncaught (In promise): (DOMException) The element has no supported sources" . Where initially loaded songs on page refresh, worked just OK, but newly added NOT even thought its same code. I tried to discard old songs with "song.srcObj = null;" to help garbage collector, then I tried to always generate unique song url if some troubles happening when loading same song (element.song = new Audio("https://domain.cz" + element.file + "?" + new Date().getTime());)

What really helped was :

```<code>song.load();
</code>```

More preciselly, since play is promise, so catching when this error breaks promise and then call load. (loading song just after it was created had no impact strangely, only when attempting to play), here is code I use :

```<code>                    var playPromise = songToPlay.song.play();
                    // In browsers that don’t yet support this functionality,
                    // playPromise won’t be defined.
                    if (playPromise !== undefined) {
                        playPromise.then(function() {
                            // Automatic playback started!
                        }).catch(function(error) {
                            console.log(error);
                            console.log("try to reload");
                            songToPlay.song.load();
                            songToPlay.song.play();
                        });
                    }
</code>```

Part of code is taken from "how to catch play error" - JavaScript audio.play() error

And of course user have to click on page at least once (I have click to show player area, so chrome wont disable audio playing straight ahead)

Body:
So in my audio player (ka-musicplayer.glitch.me) i saw a flaw that when i played audio by typing the path to an MP3 it returned that. If i predefine the MP3s, it works. Feel free to see the code here.

   var input = document.getElementById("input");
      var inputVal = "";
      if (input) {
        inputVal = input.value;
      }

      var player = new Audio(inputVal);
      player.crossOrigin = "anonymous";
  var s2 = document.createElement("button");
      s2.innerText = "Play";
      s2.addEventListener("click", function() {
        player.src = inputVal;
        player.play();
      });
      document.body.appendChild(s2);

<!DOCTYPE html>

<input id="input" />
Check JS Console in current browser for error

Body:
I also had trouble when dynamically added songs ended with "Uncaught (In promise): (DOMException) The element has no supported sources" . Where initially loaded songs on page refresh, worked just OK, but newly added NOT even thought its same code. I tried to discard old songs with "song.srcObj = null;" to help garbage collector, then I tried to always generate unique song url if some troubles happening when loading same song (element.song = new Audio("https://domain.cz" + element.file + "?" + new Date().getTime());)

What really helped was :

song.load();

More preciselly, since play is promise, so catching when this error breaks promise and then call load. (loading song just after it was created had no impact strangely, only when attempting to play), here is code I use :

                    var playPromise = songToPlay.song.play();
                    // In browsers that don’t yet support this functionality,
                    // playPromise won’t be defined.
                    if (playPromise !== undefined) {
                        playPromise.then(function() {
                            // Automatic playback started!
                        }).catch(function(error) {
                            console.log(error);
                            console.log("try to reload");
                            songToPlay.song.load();
                            songToPlay.song.play();
                        });
                    }

Part of code is taken from "how to catch play error" - JavaScript audio.play() error

And of course user have to click on page at least once (I have click to show player area, so chrome wont disable audio playing straight ahead)


问:
Total digits are inconsistent
I m using following code to get random hex values. But the output is inconsistent
Sometimes it returns 6 digits sometimes 5 digits</p>

```<code>function generateHexValue($length=6)
{
    $chars = "0123456789abcdef";

    $i = 0;
    $str = "";

    while ($i<$length) {
        $str .= $chars[mt_rand(0,strlen($chars))];
        $i++;
    }

    return $str;
}

$col=generateHexValue();
echo "<div style='background-color:#".$col."; width:100px; height:100px;'></div>";
echo $col."<br/>";
</code>```

答: Your call to mt_rand() should have a max of strlen($chars)-1, not strlen($chars). The max of mt_rand is inclusive. You could get an index off the end of $chars array (e.g. $chars[16], which is an undefined offset into $chars). Not sure what PHP would make of that.

Title: Total digits are inconsistent

Body:
I m using following code to get random hex values. But the output is inconsistent
Sometimes it returns 6 digits sometimes 5 digits

function generateHexValue($length=6)
{
    $chars = "0123456789abcdef";

    $i = 0;
    $str = "";

    while ($i<$length) {
        $str .= $chars[mt_rand(0,strlen($chars))];
        $i++;
    }

    return $str;
}

$col=generateHexValue();
echo "

";
echo $col."
";


问:
Java 11 sending HTTP post request without body
I am using java 11 http client and I need to send a post request without body.

```<code>HttpRequest request = getRequestBuilder()
    .uri(urlBuilder.toURL().toURI())
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
</code>```

When I try as above I receive 411 error code.
I also tried to set "Content-Length" header "0" but saw that is restricted.

Then I tried this:

```<code>    URL url = new URL(getHost());
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("trackingNo", orderPackage.getCargoTrackingCode());
    params.put("referenceNo", orderPackage.getCargoCode());

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    StringBuilder sb = new StringBuilder();
    for (int c; (c = in.read()) >= 0;)
        sb.append((char)c);
    String response = sb.toString();
</code>```

It throws java.io.FileNotFoundException

Normally I should use response like below:

```<code>CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(httpResponse.body(), CancelDeliveryResponse.class);
</code>```

So how can I make this request?

答:
I achieved it with HttpURLConnection:</p>
```<code>HttpURLConnection con = (HttpURLConnection) urlBuilder.toURL().openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Authorization", "Bearer " + getCargoApiAuthToken());
con.setFixedLengthStreamingMode(0);
con.connect();

if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
    // Error response scenario
    return;
}

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

StringBuilder stringBuilder = new StringBuilder();

String line;
while ((line = reader.readLine()) != null) {
    stringBuilder.append(line).append("\n");
}

CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(stringBuilder.toString(), CancelDeliveryResponse.class);
</code>```

Body:
I am using java 11 http client and I need to send a post request without body.

HttpRequest request = getRequestBuilder()
    .uri(urlBuilder.toURL().toURI())
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

When I try as above I receive 411 error code.
I also tried to set "Content-Length" header "0" but saw that is restricted.

Then I tried this:

    URL url = new URL(getHost());
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("trackingNo", orderPackage.getCargoTrackingCode());
    params.put("referenceNo", orderPackage.getCargoCode());

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    StringBuilder sb = new StringBuilder();
    for (int c; (c = in.read()) >= 0;)
        sb.append((char)c);
    String response = sb.toString();

It throws java.io.FileNotFoundException

Normally I should use response like below:

CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(httpResponse.body(), CancelDeliveryResponse.class);

So how can I make this request?

Body:
I achieved it with HttpURLConnection:

HttpURLConnection con = (HttpURLConnection) urlBuilder.toURL().openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Authorization", "Bearer " + getCargoApiAuthToken());
con.setFixedLengthStreamingMode(0);
con.connect();

if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
    // Error response scenario
    return;
}

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

StringBuilder stringBuilder = new StringBuilder();

String line;
while ((line = reader.readLine()) != null) {
    stringBuilder.append(line).append("\n");
}

CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(stringBuilder.toString(), CancelDeliveryResponse.class);


问:
Connecting to remote server failed using WinRM from PowerShell
I am trying to run powershell code from my computer to vm on my computer, but i keep getting this error:

Connecting to remote server failed with the following error message :
  The WinRM client cannot process the request. If the authentication
  scheme is different from Kerberos, or if the client computer is not
  joined to a domain, then HTTPS transport must be used or the
  destination machine must be added to the TrustedHosts configuration
  setting. Use winrm.cmd to configure TrustedHosts. Note that computers
  in the TrustedHosts list might not be authenticated. You can get more
  information about that by running the following command: winrm help
  config. For more information, see the about_Remote_Troubleshooting
  Help topic.

my code:

```<code>  string runasUsername = @"\aaa";
    string runasPassword = "aaa";
    SecureString ssRunasPassword = new SecureString();
    foreach (char x in runasPassword)
        ssRunasPassword.AppendChar(x);
    PSCredential credentials = new PSCredential(runasUsername, ssRunasPassword);

    var connInfo = new WSManConnectionInfo(new Uri("http://10.0.5.35/PowerShell"),
        "http://schemas.microsoft.com/powershell/Microsoft.Exchange",credentials);
    connInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

    var runspace = RunspaceFactory.CreateRunspace(connInfo);

    var domainName = "domainName.COM";
    var password = "ActiveDirectoryPassword1234";
    var ssPassword = new SecureString();
    foreach (char c in password)
        ssPassword.AppendChar(c);

    var command = new Command("New-Mailbox");

    command.Parameters.Add("FirstName", firstName);
    command.Parameters.Add("LastName", lastName);
    command.Parameters.Add("Password", ssPassword);
    command.Parameters.Add("ResetPasswordOnNextLogon", false);
    command.Parameters.Add("OrganizationalUnit", "NeumontStudents");

    runspace.Open(); <--//error here
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);

    var results = pipeline.Invoke();

    runspace.Dispose();
</code>```

What am I missing?

答:
Setting this up on a new client, I had to:

Run PowerShell as administrator

Enable WinRM by running this command and answering yes to the prompt:

```<code>winrm quickconfig
</code>```

Add the host to my trusted hosts (where 1.2.3.4 is the host's IP address):

```<code>Set-Item wsman:localhost\client\trustedhosts -value 1.2.3.4
</code>```

Body:
I am trying to run powershell code from my computer to vm on my computer, but i keep getting this error:

Connecting to remote server failed with the following error message :
  The WinRM client cannot process the request. If the authentication
  scheme is different from Kerberos, or if the client computer is not
  joined to a domain, then HTTPS transport must be used or the
  destination machine must be added to the TrustedHosts configuration
  setting. Use winrm.cmd to configure TrustedHosts. Note that computers
  in the TrustedHosts list might not be authenticated. You can get more
  information about that by running the following command: winrm help
  config. For more information, see the about_Remote_Troubleshooting
  Help topic.

my code:

  string runasUsername = @"\aaa";
    string runasPassword = "aaa";
    SecureString ssRunasPassword = new SecureString();
    foreach (char x in runasPassword)
        ssRunasPassword.AppendChar(x);
    PSCredential credentials = new PSCredential(runasUsername, ssRunasPassword);

    var connInfo = new WSManConnectionInfo(new Uri("http://10.0.5.35/PowerShell"),
        "http://schemas.microsoft.com/powershell/Microsoft.Exchange",credentials);
    connInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

    var runspace = RunspaceFactory.CreateRunspace(connInfo);

    var domainName = "domainName.COM";
    var password = "ActiveDirectoryPassword1234";
    var ssPassword = new SecureString();
    foreach (char c in password)
        ssPassword.AppendChar(c);

    var command = new Command("New-Mailbox");

    command.Parameters.Add("FirstName", firstName);
    command.Parameters.Add("LastName", lastName);
    command.Parameters.Add("Password", ssPassword);
    command.Parameters.Add("ResetPasswordOnNextLogon", false);
    command.Parameters.Add("OrganizationalUnit", "NeumontStudents");

    runspace.Open(); <--//error here
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);

    var results = pipeline.Invoke();

    runspace.Dispose();

What am I missing?

Body:
Setting this up on a new client, I had to:

Run PowerShell as administrator

Enable WinRM by running this command and answering yes to the prompt:

winrm quickconfig

Add the host to my trusted hosts (where 1.2.3.4 is the host's IP address):

Set-Item wsman:localhost\client\trustedhosts -value 1.2.3.4


问:
How to save current cmd-output
Is there a way to get whats currently displayed on the windows command prompt?

For example:

```<code>print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'
</code>```

答:
Create a file, let say mylib.py

```<code>import sys

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open('log.dat', 'w')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass
</code>```

Then open your interpreter:

```<code>>>> from mylib import Logger
>>> import sys
>>> sys.stdout = Logger()
>>> print(1)
1
>>> print(2)
2
>>> print(3)
3
>>> exit()
</code>```

See log.dat:

```<code>1
2
3
</code>```

Title: How to save current cmd-output

Body:
Is there a way to get whats currently displayed on the windows command prompt?

For example:

print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'

Body:
Create a file, let say mylib.py

import sys

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open('log.dat', 'w')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass

Then open your interpreter:

>>> from mylib import Logger
>>> import sys
>>> sys.stdout = Logger()
>>> print(1)
1
>>> print(2)
2
>>> print(3)
3
>>> exit()

See log.dat:

1
2
3


问:
Does anyone know nay fix for this error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>'
In local working fine but when i deployed on digital ocean Kubernetes server then showing error. please help....

答: Check your node version. It happening in new version of node.</p>


问:
Script is not highlighting all repeated words, how can I fix this
I have the below script running where it needs to search the entire google doc for specific words I have chosen and highlight them within the doc. It is currently doing this however for some repeated words it does not highlight these. How could I amend the script to ensure all words are highlighted.</p>
```<code>
function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}```
</code>```

答:
Using this sample script and the regex, how about the following modification?

Modified script:

function highlightSentences() {
  var sentences = ["value1", "value2",,,]; // Please set your search texts.

  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const searchValue = sentences.join("|");
  var rangeElement = body.findText(searchValue);
  while (rangeElement) {
    const startOffset = rangeElement.getStartOffset();
    const endOffset = rangeElement.getEndOffsetInclusive();
    const element = rangeElement.getElement();
    const textElement = element.editAsText();
    textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
    rangeElement = body.findText(searchValue, rangeElement);
  }
}
```

Reference:

findText(searchPattern, from)

Body:
I have the below script running where it needs to search the entire google doc for specific words I have chosen and highlight them within the doc. It is currently doing this however for some repeated words it does not highlight these. How could I amend the script to ensure all words are highlighted.

function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}```

Body:
Using this sample script and the regex, how about the following modification?

Modified script:

function highlightSentences() {
  var sentences = ["value1", "value2",,,]; // Please set your search texts.

  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const searchValue = sentences.join("|");
  var rangeElement = body.findText(searchValue);
  while (rangeElement) {
    const startOffset = rangeElement.getStartOffset();
    const endOffset = rangeElement.getEndOffsetInclusive();
    const element = rangeElement.getElement();
    const textElement = element.editAsText();
    textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
    rangeElement = body.findText(searchValue, rangeElement);
  }
}

Reference:

findText(searchPattern, from)


问:
I need to filter a range depending on the first cell of a column in Google Sheets
My situation is the following:

I have a database of musicians in a file. That file has multiple tabs depending on the instrument with various informations: name, age, contacts, and most importantly the concert dates the musicians will attend.

Database example with only two instruments
https://docs.google.com/spreadsheets/d/1wZsZiE2A_VdUmmNV9uSRmBMGQz0uw6GwAPuCsMa8PoI/edit?usp=sharing

You can see that columns D and E have dates in them, and under them a Y or N, depending on the musician's availability for that concert.

In another file (NOT the same one) I need to be able to import only the musicians that will play in certain dates.
Example sheet:
https://docs.google.com/spreadsheets/d/18rm4HQDh5Bx0sUbdFOQ_kUzf5Gu2vcpt2HMqphqKuqg/edit?usp=sharing

Here, there are multiple tabs for various concerts, and in each tab I need to import only the musicians that will play in the specified date (here it's set in B1).

Using FILTER() and IMPORTRANGE() doesn't work if I add dates (I want to be able to add new concerts to the left of the "old" concerts) to the database file it wrecks everything, because IMPORTRANGE() doesn't automatically updates changes made to the original file.
I tried LOOKUP() and similar functions, but I'm not sure how to make them work in my situation. Any help is welcome!

答:
there are many ways for example...

paste in A4:

```<code>=ARRAY_CONSTRAIN(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IMPORTRANGE(
 "1wZsZiE2A_VdUmmNV9uSRmBMGQz0uw6GwAPuCsMa8PoI"; A3&"!A1:E100"));
 "where lower(Col1) matches 'name|email|age|"&TO_TEXT($B$1)&"'"; 0));
 "where Col4 = 'y'"; 1); 9^9; 3)
</code>```

copy A4 and paste in A11:

Body:
there are many ways for example...

paste in A4:

=ARRAY_CONSTRAIN(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IMPORTRANGE(
 "1wZsZiE2A_VdUmmNV9uSRmBMGQz0uw6GwAPuCsMa8PoI"; A3&"!A1:E100"));
 "where lower(Col1) matches 'name|email|age|"&TO_TEXT($B$1)&"'"; 0));
 "where Col4 = 'y'"; 1); 9^9; 3)

copy A4 and paste in A11:


问:
Copy dynamic range from one sheet to another
I am using the below code to copy my data from  sheet1 to sheet2 and append the data in sheet2 if script runs again? The issue is that my range is not fixed in sheet 1,I want to copy whatever range contains the content should be copied to sheet2 Can anyone guide that what to change in the below code to get the result?</p>
```<code>  function copyInfo() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var copySheet = ss.getSheetByName("sheet1");
  var pasteSheet = ss.getSheetByName("sheet2");

  var source = copySheet.getrange(2,1,200,7);
 var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,200,7);

  source.copyTo(destination, {contentsOnly:true});
   var data = copySheet.getRange(2,1,200,6)
   data.clearContent()

   }
</code>```

答:
Method1:
Include:

```<code>var paste_lr = pasteSheet.getLastRow()
</code>```

Modify:

```<code>  var source = copySheet.getrange(paste_lr+1,1,200,7);
</code>```

Similarly change 200 using same function.

Method2:

```<code>var sp = PropertiesService.getScriptProperties();
var SourceLr = sp.getProperty("Source_Data_Rows") || 0;

var source = copySheet.getrange(SourceLr+1,1,200,7);

var Source_Lr = copySheet.getLastRow();
sp.setProperty("Source_Data_Rows", Source_Lr);
</code>```

Body:
I am using the below code to copy my data from  sheet1 to sheet2 and append the data in sheet2 if script runs again? The issue is that my range is not fixed in sheet 1,I want to copy whatever range contains the content should be copied to sheet2 Can anyone guide that what to change in the below code to get the result?

  function copyInfo() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var copySheet = ss.getSheetByName("sheet1");
  var pasteSheet = ss.getSheetByName("sheet2");

  var source = copySheet.getrange(2,1,200,7);
 var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,200,7);

  source.copyTo(destination, {contentsOnly:true});
   var data = copySheet.getRange(2,1,200,6)
   data.clearContent()

   }

Body:
Method1:
Include:

var paste_lr = pasteSheet.getLastRow()

Modify:

  var source = copySheet.getrange(paste_lr+1,1,200,7);

Similarly change 200 using same function.

Method2:

var sp = PropertiesService.getScriptProperties();
var SourceLr = sp.getProperty("Source_Data_Rows") || 0;

var source = copySheet.getrange(SourceLr+1,1,200,7);

var Source_Lr = copySheet.getLastRow();
sp.setProperty("Source_Data_Rows", Source_Lr);


问:
Running VSS 2005 Client on a the same server as VSS 6.0
Is it possible to run client-server combination of VSS 2005 (client)/VSS 6.0 (server) on the same box?</p>

答: Yes, absolutely. I've been doing it for about a year with no problems</p>

OwnerDisplayName: Danny G

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jirwin


问:
Handle dialog immediately opened in new tab
I'm writing a Playwright test for the case in which a link opens an application via a new tab. The user clicks a link, and a new tab is opened with a custom application url.

The browser normally asks "Do you want to open this link," and the user must click accept or cancel.

In Playwright, the new page is blocked until after the dialog is confirmed. If I don't have access to the page, is it somehow possible to listen for the dialog event?

```<code>const context = page.context();

async function newPageOpened(): Promise<void> {
  const newPage = await context.waitForEvent('page')
  // I won't have access to newPage unless I manually click the Accept button

  newPage.on('dialog', (dialog) => {
    void dialog.accept();
  });
}

async function action(): Promise<void> {
  // Click the link
}

await Promise.all([newPageOpened, action()])
</code>```

答:
The dialog is a Chrome (only) implementation. Playwright doesn't know how to handle them. So, you won't be able to dismiss it using the dialog event.

You can follow this issue here.

Body:
I'm writing a Playwright test for the case in which a link opens an application via a new tab. The user clicks a link, and a new tab is opened with a custom application url.

The browser normally asks "Do you want to open this link," and the user must click accept or cancel.

In Playwright, the new page is blocked until after the dialog is confirmed. If I don't have access to the page, is it somehow possible to listen for the dialog event?

const context = page.context();

async function newPageOpened(): Promise<void> {
  const newPage = await context.waitForEvent('page')
  // I won't have access to newPage unless I manually click the Accept button

  newPage.on('dialog', (dialog) => {
    void dialog.accept();
  });
}

async function action(): Promise<void> {
  // Click the link
}

await Promise.all([newPageOpened, action()])


问:
Why output control doesn't catch sql?
I wrote a code which is changing headings h1 to h2 if it's not first heading of that type. It works, but only when I'm using just PHP. If I want to use it on website, which one is using database to output content, that code doesn't work.

I'm using ob_start() before  and ob_get_contents() + ob_end_clean() + rest of my code after , so I think that has to be something wrong "catching" content from database, but I'm not sure. I tried to use that code on a website based on WordPress.

My code (I know it isn't probably the best solution, but it works when I'm using it on any website without CMS):

```<code><!DOCTYPE html>
<?php
    ob_start();
?>
<html>
    <head>
        <title>random page</title>
    </head>
    <body>
      <div class="container">
        <div class="row">
          <div class="col-md-5">
            <h1>afdsfdassfdfdsa</h1>
          </div>
        </div>
      </div>
      <h1>sadffsadf afdsfdsa afsdfs?</h1>
      <h1 class="superclass">random text?</h1>
      <div>
          <p>some ending content</p>
      </div>
    </body>
</html>

<?php
    $bufferContent = ob_get_contents();
    ob_end_clean();

    $matchedContent = '';
    $endContent = '';
    $modifiedContent = '';
    $firstHeadingBoolean = true;
    $h1Pattern = array();
    $h1Pattern[0] = '%<h1(.*?)>%';
    $h1Pattern[1] = '%</h1>%';
    $h1Replacement = array();
    $h1Replacement[0] = '<h2$1>';
    $h1Replacement[1] = '</h2>';
    if(preg_match_all('%((.|\n)*?)(<h1.*?>.*?</h1>)%', $bufferContent, $contentMatches)){
        foreach($contentMatches[0] as $matches) {
            $matchedContent .= $matches;
        }
        $endContent = str_replace($matchedContent, '', $bufferContent);

        foreach ($contentMatches[0] as $matches) {
            if(!$firstHeadingBoolean){
                $firstHeadingBoolean = false;
            } else {
                $matches = preg_replace($h1Pattern, $h1Replacement, $matches);
            }
            $modifiedContent .= $matches;
        }
        echo $modifiedContent;
        echo $endContent;
    } else {
        echo $bufferContent;
    }
?>
</code>```

EDIT: I tried to use solutions from there but nothing has changed: WordPress filter to modify final html output
Now, after some testing, I can see it's not working because preg_match_all doesn't work correctly. Anyone has an idea what is wrong with that preg_match_all? I tested that regex pattern inside that in regex101 and on my localhost and everything worked fine. I don't understand, why isn't it working here?

答:
Ok, so that wasn't problem with sql but with regex. To solve that problem I used code like that:</p>
```<code>    <?php
ob_start();
?>

<!-- html code -->

    <?php

        $bufferContent = ob_get_contents();
        ob_end_clean();

        $bufferContent = preg_split("%(?=<h1)%",$bufferContent);
        $i = 0;
        $h1Pattern = array();
        $h1Pattern[0] = '%<h1(.*?)>%';
        $h1Pattern[1] = '%</h1>%';
        $h1Replacement = array();
        $h1Replacement[0] = '<h2$1>';
        $h1Replacement[1] = '</h2>';
        foreach($bufferContent as $bufferElement){
            if(preg_match("%<h1%", $bufferElement)){
                if($i > 0){
                    echo preg_replace($h1Pattern, $h1Replacement, $bufferElement);
                } else {
                    echo $bufferElement;
                    $i++;
                }
            } else {
                echo $bufferElement;
            }
        }
    ?>
</code>```

Title: Why output control doesn't catch sql?

Body:
I wrote a code which is changing headings h1 to h2 if it's not first heading of that type. It works, but only when I'm using just PHP. If I want to use it on website, which one is using database to output content, that code doesn't work.

I'm using ob_start() before  and ob_get_contents() + ob_end_clean() + rest of my code after , so I think that has to be something wrong "catching" content from database, but I'm not sure. I tried to use that code on a website based on WordPress.

My code (I know it isn't probably the best solution, but it works when I'm using it on any website without CMS):

<!DOCTYPE html>
<?php
    ob_start();
?>

        <title>random page</title>

afdsfdassfdfdsa

sadffsadf afdsfdsa afsdfs?

random text?

some ending content

<?php
    $bufferContent = ob_get_contents();
    ob_end_clean();

    $matchedContent = '';
    $endContent = '';
    $modifiedContent = '';
    $firstHeadingBoolean = true;
    $h1Pattern = array();
    $h1Pattern[0] = '%
%';
    $h1Pattern[1] = '%
%';
    $h1Replacement = array();
    $h1Replacement[0] = '
';
    $h1Replacement[1] = '
';
    if(preg_match_all('%((.|\n)*?)(
.*?
)%', $bufferContent, $contentMatches)){
        foreach($contentMatches[0] as $matches) {
            $matchedContent .= $matches;
        }
        $endContent = str_replace($matchedContent, '', $bufferContent);

        foreach ($contentMatches[0] as $matches) {
            if(!$firstHeadingBoolean){
                $firstHeadingBoolean = false;
            } else {
                $matches = preg_replace($h1Pattern, $h1Replacement, $matches);
            }
            $modifiedContent .= $matches;
        }
        echo $modifiedContent;
        echo $endContent;
    } else {
        echo $bufferContent;
    }
?>

EDIT: I tried to use solutions from there but nothing has changed: WordPress filter to modify final html output
Now, after some testing, I can see it's not working because preg_match_all doesn't work correctly. Anyone has an idea what is wrong with that preg_match_all? I tested that regex pattern inside that in regex101 and on my localhost and everything worked fine. I don't understand, why isn't it working here?

Body:
Ok, so that wasn't problem with sql but with regex. To solve that problem I used code like that:

    <?php
ob_start();
?>

<!-- html code -->

    <?php

        $bufferContent = ob_get_contents();
        ob_end_clean();

        $bufferContent = preg_split("%(?=<h1)%",$bufferContent);
        $i = 0;
        $h1Pattern = array();
        $h1Pattern[0] = '%<h1(.*?)>%';
        $h1Pattern[1] = '%</h1>%';
        $h1Replacement = array();
        $h1Replacement[0] = '<h2$1>';
        $h1Replacement[1] = '</h2>';
        foreach($bufferContent as $bufferElement){
            if(preg_match("%<h1%", $bufferElement)){
                if($i > 0){
                    echo preg_replace($h1Pattern, $h1Replacement, $bufferElement);
                } else {
                    echo $bufferElement;
                    $i++;
                }
            } else {
                echo $bufferElement;
            }
        }
    ?>