text:
Q: prove or disprove that $\sum_{k=0}^n (k-1)^2 p_n(k) = n!$
Prove or disprove that $\sum_{k=0}^n (k-1)^2 p_n(k) = n!$ for $n\ge 2,$ where $p_n(k)$ is the number of permutations of $\{1,\cdots, n\}$ with exactly $k$ fixed points.

I know how to show that $\sum_{k=0}^n p_n(k) = n!$ by counting the total number of fixed points among all permutations of length n in two different ways. But the method for this doesn't seem to work when showing that $\sum_{k=0}^n (k-1)^2 p_n(k) = n!.$ I know also that $p_n(k) = {n\choose k}p(n-k)$ and $kp_n(k) = np_{n-1}(k-1)$, where $p(n-k)$ is the number of derangements of length $n-k$. So maybe some sort of induction using these recurrences will help?

A: Hint: Write this as
$$
\sum_k k(k-1)p_k(n) -\sum_k kp_k(n)+\sum_k p_k(n)
$$
You already found a neat double-counting argument which shows that the last sum is $n!$. There exist clever double-counting arguments which allow you to simplify the first two sums as well.
For a further hint, see Prove that $\sum_{k = r}^{n} k(k - 1)(k - 2)\cdots(k - r+ 1)D_n(k) = n!$.

A: I hope this makes sense:

*

*$\sum_{k=0}^{n}(k-1)^2p_n(k)=\sum_{k=0}^{n}k(k-2)p_n(k)+\sum_{k=0}^{n}p_n(k)$
We know $\sum_{k=0}^{n}p_n(k)=n!$ we have to check that $\sum_{k=0}^{n}k(k-2)p_n(k)=0$.\

*First write it like this:
$\sum_{k=0}^{n}k(k-2)p_n(k)=\sum_{k=0}^{n}k(k-1)p_n(k)-\sum_{k=0}^{n}kp_n(k)$

*Compute the last part with the last propriety you gave: $kp_n(k)=np_{n-1}(k-1)$ and use the fact that $p_n(l)=0$ for $l<0$:
$\sum_{k=0}^{n}kp_n(k)=\sum_{k=0}^{n}np_{n-1}(k-1)=n\sum_{l=0}^{n-1}p_{n-1}(l)=n(n-1)!=n!$

*Use two times the last propriety you gave: $kp_n(k)=np_{n-1}(k-1)$
$\sum_{k=0}^{n}(k-1)kp_n(k)=\sum_{k=0}^{n}(k-1)np_{n-1}(k-1)=n\sum_{k=0}^{n}(n-1)p_{n-2}(k-2)=$
$n(n-1)\sum_{j=0}^{n-2}p_{n-2}(j)=n(n-1)(n-2)!=n!$

*Combine the results above:
$\sum_{k=0}^{n}(k-1)^2p_n(k)=n!-n!+n! = n!$

A: Let $D_n$ denote the number of derangements in $S_n$: it is well known that
$$ \sum_{n\geq 0}\frac{D_n}{n!}z^{n} = \frac{e^{-z}}{1-z} \tag{1}$$
(where by convention $D_0=1$) so $D_n = n!\sum_{k=0}^{n}\frac{(-1)^k}{k!}$. It is also clear that
$$ p_n(k) = \binom{n}{k}D_{n-k} \tag{2}$$
so
$$ \sum_{k=0}^{n}(k-1)^2 p_n(k) = \sum_{k=0}^{n}\binom{n}{k}(k-1)! D_{n-k}=\sum_{k=0}^{n}\binom{n}{k}(n-k-1)^2 D_k = n!\sum_{k=0}^{n}\frac{D_k}{k!}\cdot\frac{(n-k-1)^2}{(n-k)!}\tag{3}$$
where
$$ \sum_{m\geq 0}\frac{(m-1)^2}{m!}z^m = e^z(1-z+z^2)\tag{4} $$
so by $(3)$
$$ \sum_{k=0}^{n}(k-1)^2 p_n(k)= n![z^n]\left(\frac{e^{-z}}{1-z}\cdot e^z(1-z+z^2)\right)=n![z^n]\left(1+\frac{z^2}{1-z}\right)\tag{5} $$
and the LHS always equals $n!$, except in the case $n=1$ where it equals $0$.


text:
Q: touch event binding for knockout.js I've just started learning Knockout.js and I've run into some trouble, which I need some help to resolve.
Basically I want to add my touchend event to my Knockout generated list. At the moment I'm doing something like this:
HTML:

JS:
var names = ['Tom','Jennifer','Jack','Poul'];

ko.observableArray(names);

ko.applyBindings(names);

$('li').on('touchend, function(){
 ... do something
});

But I assume this is not the proper way to do it? How do I 'data-bind' my 'touchend' with Knockout (if thats is the way to do it)?
Thanks in advance :)

A: You can use knockoutjs event binding:

http://knockoutjs.com/documentation/event-binding.html
You viewmodel binding doesn't look quite right either, try this instead:
function NamesViewModel() {
    var self = this;
    self.names = ko.observableArray(['Tom','Jennifer','Jack','Poul']);
    self.touchEndHandler = function(data, event) {
        var element = $(event.target);
        alert("TouchEnd Triggered");
        // can access self here which is the viewmodel
    };
}

var viewModel = new NamesViewModel();
ko.applyBindings(viewModel);

Example - http://jsfiddle.net/infernalbadger/pjG8r/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drupal 8 how to use different themes on subsites I have been requested to architect and develop a "site collection" where there are different sub-sites below the main umbrella site. Let's call the umbrella www.umbrella-site.net.
The subsites should be of form www.umbrella-site.net/sitex etc.
Now the subsites should use different themes from a finite set of themes. The theme should be selectable by the end user without changes in the code. The themes themselves shall be pre-programmed (as they should be approved by the PR). And the theme should be used by whole /sitex tree (based by the url)
I am not asking the full solution but a few pointers. The problems I see are:

*

*how to use a different theme in the subtree of urls

*how to point a theme for a subsite without changes in the code

*how to get the information of selected theme in the pages below the subsite

I would rather not to use javascript based solutions to achieve this functonality.
Of course there might be other problems when really implementing this, but I would be more than thankful if I could get any insight for the questions above.
wbr
hank

A: There is a module "Theme key"
https://www.drupal.org/project/themekey
..but there's no stable version of it. Unfortunately, that's the situation for many D8 modules.


text:
Q: Images working in Debug but not working in Microsoft Store - UWP Xamarin.Forms I have created scale-100 folder in UWP project, added multiple images to it with Build Action set to Content and Copy to Output Directory set to Copy Always.
In code I use image name + extension and the images work while debugging locally.
However, when I create package and upload it to Microsoft Store, the application seems to work, but images are not loaded and are not visible.
Anyone could help me with this??


text:
Q: CRC computation I would like to understand the CRC computation using CCITT CRC-16 $x^{16} + x^{12} +x^{5} +1$. I was able to successfully implement it in a program but I would like to understand the computation behind it. I was not succesful in the paper-n-pen technique. Is the CRC computation with CRC-16 different.
Any useful hints in this direction.
P.S : I am not keen on the program or the shift register implementation but the traditional way of computing CRC with polynomials or binary sequence using binary division technique.
Thanks for reading

A: A CRC computation is as follows.  You have a data polynomial
$d(x) = \sum_{i=0}^{n-1} d_ix^i$ where the $d_i \in \{0, 1\}$ are
$n$ bits to
be transmitted (or recorded).  What is actually transmitted (or
recorded) is
$$t(x) = x^{16}d(x) + p(x)$$
where $p(x)$ is the ${\textit remainder~polynomial}$
when $x^{16}d(x)$ is divided by the CRC polynomial
$C(x) = x^{16} + x^{12} + x^5 + 1$.  Note that polynomial division yields
$$
x^{16}d(x) = q(x)C(x) + p(x)
$$
where the quotient $q(x)$ is discarded.  But the above equation
can be re-arranged as
$$
q(x)C(x) = x^{16}d(x) - p(x) = x^{16}d(x) + p(x) = t(x)
$$
(because arithmetic on the polynomial coefficients is done modulo $2$
and subtraction is thus the same as addition),
and thus $t(x)$ is a multiple of the CRC polynomial $C(x)$.
Since $p(x)$ is of degree $15$ or less, the
high-order coefficients of the polynomial $t(x)$ are the data bits
while the low-order coefficients are the so-called CRC bits or parity
bits, that is
$$
t(x) = d_{n-1}x^{n-1 + 16} + d_{n-2}x^{n-2+16}
+ \cdots d_0x^{16} + p_{15}x^{15} + p_{14}x^{14} + \cdots + p_0.
$$
In computing $p(x)$ via polynomial long division using paper and pencil,
you need to remember that
(i) $\quad \quad$ $d(x)$ is multiplied by $x^{16}$ before
beginning the long division
(ii) $\quad \quad$ the subtractions of polynomial coefficients that occur in
the long division process are all done modulo $2$ and thus are the same as additions modulo $2$ (that is, the XOR operation)
(iii) $\quad \quad$ the long division continues till $x^{16}d_0$ is processed
and the remainder is a polynomial of degree $15$ or less.
Practical CRC systems often have bells-and-whistles (such as the high-order
bits $8$ bits in $x^{16}d(x)$ are complemented before the division process
begins etc.) which I have not included above because these are likely
not  of interest in this forum.  However, ignoring such details in your
paper-and-pencil computations will make your results differ
from the ones your machine is giving you.
At the receiving (or reading) end, what you have is a polynomial
$r(x)$ which might be $\textit slightly$ different from $t(x)$
if transmission (or read) errors changed some of the bits.  The
CRC error detection process merely divides $r(x)$ by $C(x)$; no
need to multiply $r(x)$ by $x^{16}$ first.   If
the remainder is nonzero, then $r(x)$ is $\textit not$ a multiple
of $C(x)$ and so the receiver knows that transmission (or read) errors
have occurred.  But if the remainder is $0$, then $r(x)$ is a
multiple of $C(x)$, and
with high probability, is the same as $t(x)$.  The low-order
$16$ bits in $r(x)$ are discarded and the high-order $n$ bits
are accepted as error-free data. When the remainder is $0$, there
is a small probability that the difference between $r(x)$ and $t(x)$
is a multiple of $C(x)$.  Such errors are referred to as undetected
errors.  The probability of undetected error decreases as the degree
of $C(x)$ increases.  For this reason, many modern systems use
CRC polynomials of degree 32.


text:
Q: Probability that half of a sample from a normal distribution will be above a threshold Suppose we have $n$ samples drawn from a standard normal distribution.
What is the probability that at least half $(\frac{n}{2})$ of these samples are above some threshold above that mean, say, above $1.5\sigma$?
I understand that the probability of a single draw from a normal distribution is $1 - \Phi(1.5)$ (where $\Phi$ is the cumulative distribution function).
My immediate thought is to suggest that the probability of the first $(n/2)$ draws being above the threshold is the product of this, i.e.:$\Pi_0^{n/2} 1 - \Phi(1.5)$. And then I need to take into account all the permutations in which this can occur, ie. every odd draw might be above $1.5\sigma$, or alternatively, all $n$ draws might be above $1\sigma$, which would involve a summation over the permutations.
Is this correct?

A: Your general idea is sort of along the right lines but it looks like you didn't quite get there.
Consider the case where $n$ is even and let's define $m=n/2$. Take that the probability of exceeding the threshold $t$ is $p=1-\Phi(t)$. Let $X$ be the number of values that exceed the threshold; and assume that the events are independent. Then the distribution of $X$ will be binomial$(n,p)$ (as suggested by Hugh in comments).
So the probability of observing exactly $x$ observations over the threshold will be given by the binomial pmf $P(X=x)={n\choose x} p^x(1-p)^{n-x}$ (there's that number of combinations you suggested).
Consequently the probability of at least $m$ observations above the threshold is the same as $m$ or fewer observations below it, so the answer can be obtained from the cdf for a $\text{binomial}(n,p)$. Similar calculations occur for the case where $n$ is odd.
Many packages will evaluate the binomial cdf for you, though for small $n$ it's feasible to do it by hand and for large $n$ and $p$ not close to $0$ or $1$ you can use a normal approximation.


text:
Q: meaning of the phrase "telling effect" It is from a BBC sports article. Here is the excerpt:

The Briton, 28, used his left hand to telling effect throughout an intriguing affair, in which New Zealand's Parker displayed swift hands, movement and impressive durability.

What does telling effect mean there, and why was an article omitted before it?

A: telling effect means "effective" or "striking", that causes a particular reaction as intended. If I say something offensive to somebody and it has a telling effect then it means it is very striking.

A: Effect can be a noun or a verb. I can have a "strong effect" on something or I can "effect a change". It can also be replaced by "result" in this context.
Telling means:

Having force or producing a striking effect
Revealing previously unknown information

So the Briton was (possibly) previously unknown for his left handed abilities but he used them to achieve a striking result.


text:
Q: Loop through the first level in array and assign it to a variable I would like to have 10 variables named from day1 to day10, and for each of them the arrayOne[][] would increase only the first value before each Date function method, so for day1 it would be arrayOne[0][0], for day2 arrayTwo[1][0], day3 would be arrayThree[2][0] - so the second value would always would stay the same.
This code works but it seems extremely inefficient, is there a way to put it into a loop that would increase only the first "level" of array and assign it to the corresponding day?
var day1 = arrayOne[0][0].getDate() + "." +  arrayOne[0][0].getMonth() + "." +  arrayOne[0][0].getFullYear() + "." +
    " - " + arrayOne[0][6].getDate() + "." + arrayOne[0][6].getMonth() + "." +  arrayOne[0][6].getFullYear() + ".";

var day2 = arrayOne[1][0].getDate() + "." +  arrayOne[1][0].getMonth() + "." +  arrayOne[1][0].getFullYear() + "." +
    " - " + arrayOne[1][6].getDate() + "." +  arrayOne[1][6].getMonth() + "." +  arrayOne[1][6].getFullYear() + ".";

A: Using a for loop:

//generator function to test principle
var arrayOne = [];
a = new Date();
for (var i = 0; i < 5; i++) {
  arrayOne[i] = [a, a, a, a, a, a, a];
}
//end

for (var i = 0; i < arrayOne.length; i++) {
  //note how we use window to assign day variable with index.
  window["day" + (i + 1)] = arrayOne[i][0].getDate() + "." + arrayOne[i][0].getMonth() + "." + arrayOne[i][0].getFullYear() + "." +
    " - " + arrayOne[i][6].getDate() + "." + arrayOne[i][6].getMonth() + "." + arrayOne[i][6].getFullYear() + ".";

}

console.log(day2);


text:
Q: Insert Screenshot of just captured Geocoded image? I am performing a GoogleMaps/VirtualEarth geocode-request and the resulting image ( showing the location on a map ) is displayed on my site.
The problem is, I need part of this graphic 'captured' and displayed on the form.
Is it possible to do this and add the result to the form?

A: You should look into Google Maps Static API, they provide such functions


text:
Q: How to use the aws-sdk in nativescript 6.0? I am currently using nativescript 6.0.2 to build a cross-platform app and I need to be able to upload files to s3 using aws-cognito authentication to upload.
I have tried installing the javascript aws-sdk using npm install but I am getting these errors before the build.
ERROR in ../node_modules/aws-sdk/lib/credentials/process_credentials.js
Module not found: Error: Can't resolve 'child_process' in '/Users/nabhanmaswood/Desktop/Computer/Quadrant2/wowza-nativescript-plugin/demo-angular/node_modules/aws-sdk/lib/credentials'
 @ ../node_modules/aws-sdk/lib/credentials/process_credentials.js 2:11-35
 @ ../node_modules/aws-sdk/lib/node_loader.js
 @ ../node_modules/aws-sdk/lib/aws.js
 @ ./app/home/home.component.ts
 @ ./app/home/home.module.ts
 @ ../$$_lazy_route_resource lazy namespace object
 @ ../node_modules/@angular/core/fesm5/core.js
 @ ./app/app.module.ts
 @ ./main.ts

ERROR in ../node_modules/aws-sdk/lib/publisher/index.js
Module not found: Error: Can't resolve 'dgram' in '/Users/nabhanmaswood/Desktop/Computer/Quadrant2/wowza-nativescript-plugin/demo-angular/node_modules/aws-sdk/lib/publisher'
 @ ../node_modules/aws-sdk/lib/publisher/index.js 2:12-28
 @ ../node_modules/aws-sdk/lib/node_loader.js
 @ ../node_modules/aws-sdk/lib/aws.js
 @ ./app/home/home.component.ts
 @ ./app/home/home.module.ts
 @ ../$$_lazy_route_resource lazy namespace object
 @ ../node_modules/@angular/core/fesm5/core.js
 @ ./app/app.module.ts
 @ ./main.ts

ERROR in ../node_modules/xml2js/lib/parser.js
Module not found: Error: Can't resolve 'timers' in '/Users/nabhanmaswood/Desktop/Computer/Quadrant2/wowza-nativescript-plugin/demo-angular/node_modules/xml2js/lib'
 @ ../node_modules/xml2js/lib/parser.js 17:17-34
 @ ../node_modules/xml2js/lib/xml2js.js
 @ ../node_modules/aws-sdk/lib/xml/node_parser.js
 @ ../node_modules/aws-sdk/lib/node_loader.js
 @ ../node_modules/aws-sdk/lib/aws.js
 @ ./app/home/home.component.ts
 @ ./app/home/home.module.ts
 @ ../$$_lazy_route_resource lazy namespace object
 @ ../node_modules/@angular/core/fesm5/core.js
 @ ./app/app.module.ts
 @ ./main.ts

I know that to use aws-sdk with nativescript you need the plugin nativescript-nodeify but the problem is that this plugin is not currently compatible with nativescript 6.0.2.
How would I fix this error or is there any other way I can use the aws-sdk to upload to s3 using cognito?
I know about the nativescript-aws-sdk plugin but that is ONLY for s3 and uses endpoints, access key and secret key when I NEED to use amazon cognito also.

A: I ran into this and indeed nativescript-nodeify is Not aligned with recent versions of nativescript (i am using 6.0.2).
I tried to fix them one at a time in my environment and found following solution.
In your webpack.config.js, add following 4 lines in the "node" block.
        node: {
            "child_process": "empty",
            "dgram": "empty",
            "net": "empty",
            "crypto": true,
        },

I was stuck at a later point when I was to use aws-amplify for S3/storage APIs, but this should get you moving.


text:
Q: Why doesn't this page redirect work in IE? I check for a session variable in my asp.net page and redirect to my default page.
 if (Session["OrgId"] != null)
   {
       // some logic
   }
 else
   {
             Response.Redirect("../Default.aspx?Sid=1", false);
   }

and in my default.aspx page i ve done this,
Int64 id = GetId(Request.RawUrl.ToString());
  if (id == 1)
 {
    // I ll show "Session Expired"
 }

public Int64 GetId(string url)
{
    Int64 id = 0;
    if (url.Contains("="))
    {
        if (url.Length > url.Substring(url.LastIndexOf("=")).Length)
        {
            id = Convert.ToInt64(url.Substring(url.LastIndexOf("=") + 1));
        }
    }
    return id;
}

This works in googlechrome,firefox but not in IE. "Operation aborted" exception.

A: try changing
 Response.Redirect("../Default.aspx?Sid=1", false);

to
 Response.Redirect("../Default.aspx?Sid=1");

or
Response.Redirect("../Default.aspx?Sid=1", true);

A: HttpResponse.Redirect Method

Redirect(String, Boolean)
  Redirects a client to a new URL.
  Specifies the new URL and whether
  execution of the current page should
  terminate.

That means that Response.Redirect("../Default.aspx?Sid=1", false); won't terminate the current response.

A: IE is much more sensitive than other browsers about changing the DOM after headers have been sent but before the page terminates.
Here is your problem:
Response.Redirect("../Default.aspx?Sid=1", false);

Try changing false to true.
Also, be very careful about the casing in your page names.  "Default.aspx" and "default.aspx" are really not the same page even if Windows lets you get away with it.


text:
Q: What is the smallest number $d$ such that $H^1(X,\pi^*\mathcal{O}_{\mathbb{P}_k^1}(d))$ vanishes? Let $X$ be a reduced projective scheme of pure dimension 1 over the field $k$. Let $\pi: X \to \mathbb{P}_k^1$ be a finite, flat and surjective morphism onto the projective line.

What is the minimal $d \in \mathbb{Z}_{\geq 1}$ such that $H^1(X,\pi^*\mathcal{O}_{\mathbb{P}_k^1}(d)) = 0$?

I could already show that $d \geq -\chi(\mathcal{O}_X)/\deg(\pi)$ is necessary. But I was wondering whether $d \in O(-\chi(\mathcal{O}_X)/\deg(\pi))$ holds.
I am grateful for any kind of help or maybe even an example of such a situation where $d \notin O(-\chi(\mathcal{O}_X)/\deg(\pi))$ holds.

Edit: If $X$ is integral, then $d$ is in the desired order:
We then have
$$
H^1(X,\pi^*\mathcal{O}_{\mathbb{P}_k^1}(d)) \cong H^0(X,\omega_X \otimes_{\mathcal{O}_X}\pi^*\mathcal{O}_{\mathbb{P}_k^1}(-d))
$$
which is zero if $\deg \pi^*\mathcal{O}_{\mathbb{P}_k^1}(d) > \deg \omega_X = -2\chi(\mathcal{O}_X)$.
 So what happens otherwise?


text:
Q: Log MySQL general log to file slow query log to table I would like to log my slow queries to a table, but keep my general log(?) logged in a table. I assume the general log is my binary log?  MySQL docs are less than clear on this stuff. My MySQL server is setup as a replication master and these are the relevant logging stanzas from my.cnf.
# BINARY LOGGING #
log_bin                        = /var/log/mysql/mysql-bin.log
expire_logs_days               = 3
max_binlog_size                = 1000M
sync_binlog                    = 1

# LOGGING #
log_error                      = /var/log/mysql/mysql-error.log
slow_query_log                 = 1
slow_query_log_file            = /var/log/mysql/mysql-slow.log
long_query_time                = 2
log_queries_not_using_indexes  = 0

I'm afriad if I add something like this:
log_output = TABLE
general-log
expire_logs_days = 1

it will affect my binlog or start logging everything that's already written to my binlog to a table, which I don't want. I'm essentially just looking to have slow queries (a day or two's worth maybe) written to a table rather than a file, without affecting any of my other current logging.
I'm using Server version: 5.5.22-0ubuntu1-log (Ubuntu)
Thanks.

A: The setting log_output doesn't affect the binary log. It affects the general query log and the slow query log.


text:
Q: How to disable Galactic Civilization 3 debug log I am playing Galactic Civilization 3 and I pressed several keys to try to do something. I then got a debug log on the ui, that I can't get rid of. What is the key combination to make it go away?

A: With default keybindings, D will make this graphics debug log appear/disappear.
To change this, from the options click on Input

From the Main tab, change the Toggle Debug Text Overlay to something other than D


text:
Q: How do I convert this into a linear programming problem? A farmer is planning to raise wheat and barley. Each acre of wheat yields a profit of \$50 and each acre of barley yields a profit of \$70. To sow the crop, two machines, a tractor and tiller, are rented. The tractor is available for 200 hours, and the tiller is available for 100 hours, Sowing an acre of barley requires 3 hours of tractor time and 2 hours of tilling. Sowing an acre of wheat requires 4 hours of tractor time and 1 hour of tilling. How many acres of each crop should be planted to maximize the farmer's profit?
I'll try to use simplex method, afterwards.

A: The first step is to describe what your variables are: $x$ which could be the number of acres of Barley sown, and $y$ which could be the number of acres of wheat.
Now, what is the profit function: $P = 70x + 50y$ (70 dollars per acre of barley + 50 dollars per acre of wheat).
Now, what are the constraints: certainly $x\geq 0$ and $y\geq 0$.  What about not overusing the tiller?
$$2x + 1y \leq 100$$  2 hours on tiller for each acre of barley, 1 hour for each acre of wheat... not more than 100 hours available.
Similarly, what about not overusing the tractor?
$$3x + 4y \leq 200$$  3 hours on tractor for each acre of barley, 4 hours on the tractor for each acre of wheat... not more than 200 hours total on the tractor.
Condensing all those constraints you have:
Maximize $P=70x + 50y$
Subject to
\begin{align*}
2x + 1y &\leq 100 \\
3x + 4y &\leq 200 \\
x, y &\geq 0
\end{align*}


text:
Q: How to add new ssh keys to an existing droplet? I have an existing droplet that I can connect to from my ubuntu machine via ssh. I would like to also be able to connect to it from my mac via ssh. I added a new ssh key to my account here, but when I try to connect from my mac I get:
root@<ip_of_droplet>: Permission denied (publickey)
I know I added my ssh keys correctly to my droplet and they are stored in the default location on my mac. Any help would be greatly appreciated.

A: In your mac, you should have an ssh public key located at ~/.ssh/id_rsa.pub. Copy the contents of that file, and add it to the end of /root/.ssh/authorized_keys in your droplet. Make sure it's on its own line.


text:
Q: RCU.bat file not opening on virtual machine I have installed a Windows 2008 Server on my VM. I am trying to run a .bat file (on my VM).  This .bat file is stored on my local Windows 7 PC, and I'm using shared folders to access it.
The .bat file does not work on my virtual machine. There is no error shown. The command prompt window pops up and then goes away..
However this file works fine on my PC. What could be the reason for the file to run on one system and not run on the other?
How can I run this .bat using the command prompt of my virtual machine? To check if any error log shows up? What could be done? Please advise.
Thanks,

A: Are you double-clicking on the .bat file through windows explorer? Open the command prompt, then cd to where you have the file and just run it.

A: cmd cannot use UNC paths as the current path. I'm guessing your shared folders use a network share in the guest machine. Map that share to a drive letter and try again.


text:
Q: Using pgfplotstabletypeset to conditionally bold small p-values Following advice seen in other entries about using pgfplotstable on tex.stackexchange.com (such as pgfplotstable: Conditional post-processing of cell content on a per-column basis), I have encountered the puzzling behavior seen below, where I can successfully bold p-values less than 1x10^-4 (see Table 1 image), but the exact same code fails to work if I try to bold only p-values less than 1x10^-5 (see Table 3 image).
\documentclass{article}

\usepackage{pgfplotstable}
\usepackage{longtable}
\usepackage{caption}
\usepackage{colortbl}
\definecolor{lightgray}{gray}{0.9}
\usepackage{filecontents}
\begin{filecontents*}{test.csv}
A, B
1, 0.01
2, 0.001
3, 0.0001
4, 1.93E-14
5, 1.44E-09
6, 3.90E-06
\end{filecontents*}

\pgfplotstableread[col sep=comma]{test.csv}\mytable

\begin{document}
\captionof{table}{With threshold $1.0E-04$}
\newcolumntype{C}{>{\centering\arraybackslash}p{17mm}}
\pgfplotstabletypeset[
begin table=\begin{longtable},
end table=\end{longtable},
column type=C,
every even row/.style={
before row={\rowcolor[gray]{0.9}}},
every head row/.style={before row=\hline,after row=\hline\hline},
every last row/.style={after row=\hline},
columns/A/.style={column type=c},
columns/B/.style={column type=c,column name=$p_{B}$,
  postproc cell content/.style={
      /pgfplots/table/@cell content/.initial={}{%
% However, all calculations must not exceed ±16383.99999 at any point.
 % Scientific notation in the form 1.234e+4 is recognized.
 % The exponent symbol can be upper or lower case (i.e., E or e).
      \pgfmathparse{int(less(##1,1.0E-04))}
       \ifnum\pgfmathresult=1
           \textbf{##1}
           \else
             {##1}
            \fi
      },
    },
},
     col sep=comma,
     string type]\mytable

\captionof{table}{With threshold $1.0E-05$}
\newcolumntype{C}{>{\centering\arraybackslash}p{17mm}}
\pgfplotstabletypeset[
begin table=\begin{longtable},
end table=\end{longtable},
column type=C,
every even row/.style={
before row={\rowcolor[gray]{0.9}}},
every head row/.style={before row=\hline,after row=\hline\hline},
every last row/.style={after row=\hline},
columns/A/.style={column type=c},
columns/B/.style={column type=c,column name=$p_{B}$,
  postproc cell content/.style={
      /pgfplots/table/@cell content/.initial={}{%
      \pgfmathparse{int(less(##1,1.0E-05))}
       \ifnum\pgfmathresult=1
           \textbf{##1}
           \else
             {##1}
            \fi
      },
    },
},
     col sep=comma,
     string type]\mytable

\end{document}

A: Since you may want to set a pretty small threshold, it is not efficient to try out combinations like 30*##1<3E-6. Simply enable fpu and use \ifpgfmathfloatcomparison. (The latter seems to be undocumented. And its friend \ifpgfmathcomparison is mentioned once. However you may take a look at pgfmathfloat.code.tex.)

columns/B/.style={column type=c,column name=$p_{B}$,sci,
  postproc cell content/.style={
    /pgfplots/table/@cell content/.initial={}{%
      \pgfkeys{/pgf/fpu=true}
      \pgfmathparse{##1<1.0E-06}
      \ifpgfmathfloatcomparison
        \textbf{##1}
      \else
        {##1}
      \fi
      \pgfkeys{/pgf/fpu=false}
      },
    },
  },

Yet one more example:


text:
Q: Getting other PC microphone audio input using python I would like to know how to save other PC microphone audio input into my PC using python.I use below code but it is not work for getting other PC microphone input.Please help to advise.
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 8000
CHUNK = 1024
RECORD_SECONDS = 2
WAVE_OUTPUT_FILENAME = "tester_0_0.wav"

audio = pyaudio.PyAudio()
# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)
print("recording...")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
print("finished recording")

# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()


text:
Q: Integrating OOS(Office Online Server) with .NET web applications I would like to build some sort of API for my Office Online Server Farm, so I could call the opening and editing of documents from within a web application.
I want the web application to be separated from MS products so my intentions are not to use SharePoint or Exchange in order to work with the OOS.
Is there a way to mimic the process that SharePoint and Exchange use to work with Office Online, in such a way it could be used within other web applications? Any idea would suffice.


text:
Q: Java+Discord - Creating a transparent frame for Chat Overlay So I play Destiny 2, which doesn't allow Discord to inject their overlay code since they don't have cheat protection yet. So what I was trying to accomplish was to create a transparent window, which is set to always be on top, which I could point Discord too in order to have the overlay appear on their instead of the actual Destiny 2 application. My issue is, I can't seem to figure out how to make the discord overlay be stay opaque while the frame is transparent. This is the code I have
import javax.swing.*;
public class window {
    public JFrame win = new JFrame("Discord Overlay");

    window(int x, int y){
        win.setUndecorated(true);
        win.setAlwaysOnTop(true);
        win.setSize(x, y);
        win.setOpacity(0f);
        win.setVisible(true);
        win.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Timer update = new Timer(10, null);
        update.addActionListener(e -> {
            win.repaint();
        });
        update.start();
    }

    public static void main(String[] args) {
         new window(300, 500);
    }
}

As of right now, the overlay matches the opacity of the frame, as I don't fully understand how the discord overlay works, does anyone have any idea of how to bypass this? Thank you.


text:
Q: Adding point data from text file when coordinates are in OSGB36 I have a text file in which coordinates are in the OSGB36 National Grid reference system used in Great Britain, so the coordinates are not in longitude and latitude (e.g. coordinates look like this: SD481731, and are only in one column).
I would like to display these points in QGIS 2.4.0.
However, when adding a delimited text layer, it is mandatory to specify the X and the Y fields.
Can I circumvent this and display OSGB36 coordinates imported directly from one column in a text file?

A: Okay I see SD481731 needs to be separated into Eastings and Northings
which is
X=348100&Y=473100
http://www.nearby.org.uk/coord.cgi?p=SD481731&f=full
For Lat/LNG
https://www.google.co.uk/maps/place/54%C2%B009%2703.9%22N+2%C2%B047%2746.1%22W/@54.1636496,-2.7901201,13z/data=!4m2!3m1!1s0x0:0x0
You will need to do this to all your OS Grid References
http://en.wikipedia.org/wiki/Ordnance_Survey_National_Grid

A: What you have are Ordnance Survey National Grid References. To batch convert these to Ordnance Survey Coordinates I'd suggest you have a look at NG Converter, see:
  http://digimap.edina.ac.uk/webhelp/os/data_information/os_data_issues/ng_converter.htm


text:
Q: add_rewrite_rule() returns 404 page I'm using add_rewrite_rule function to add this rule:
function custom_rewrite_rules() {

    add_rewrite_rule(
        'category/books/crime',
        'category/books/?filter_category=crime',
        'top'
    );

    flush_rewrite_rules();
}

add_action('init', 'custom_rewrite_rules');

But it only returns Error 404 Page not found.
When I use this kind of URL https://example.com/category/books/?filter_category=crime the result is ok. But I would expect this URL https://example.com/category/books/crime return the same result because of added rewrite rule.
I'm also using WooCommerce plugin where "books" category and "category" attribute with "crime" term are created.
Is there something wrong in my function? If the function is good, where else could be the problem?


text:
Q: Uninitialized string offset error from PHP import script I have an import-from-excel script as part of a CMS that previously ran without issue.
My shared-hosting provider has recently upgraded their infrastructure, including PHP from 5.1 to 5.2.6, and the script now returns "Uninitialized string offset: -XXX in /path/scriptname.php on line 27" (XXX being a decreasing number from 512 and /path/scriptname.php of course being the full path to script in question).
It returns this error for every line of the excel file. Line 27 is just a return from within a function that is the first point at which the imported data is being processed:
function GetInt4d($data, $pos) {
        return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24);
}

It finally implodes with a "Fatal error: Allowed memory size of 47185920 bytes exhausted (tried to allocate 71 bytes) in /path/scriptname.php on line 133".
There's nothing useful in Apache error logs. I am stumped. Anyone have any ideas of at least where to look? Even knowing if it's likely to be something within my script or something to do with upgrade would be useful. I had another issue with a different site on same provider that (after upgrade) couldn't write sessions to tmp directory (since resolved), but am pretty sure it's not that (?).
EDIT: As it turned out that the answer was to do with the version of the parser being incompatible in some way with PHP 5.2.6, I thought it might be of use to someone that the parser in question is Spreadsheet Excel Reader .

A: Solved here:
http://www.phpbuilder.com/board/archive/index.php/t-10328608.html

A:
Uninitialized string offset:

... means that $data is not an array.

A: Thanks for the input, the situation has 'resolved itself' via me finding a more recent version of the parsing library I was using. My guess is the issue was something to do with the difference between php versions, though I'm unsure exactly what. Fixed but frustrating.
EDIT: I'm going to accept Till's answer purely in the interests of closing the question. Thx again for input.


text:
Q: Generating React routes on the fly I am currently developing an event management application that allows customers to register for events created by multiple event organisers. The backend API routes look like this:
http://my-app.com/eventorganizer1/events/event_id=1/new
http://my-app.com/eventorganizer1/events/event_id=2/new
http://my-app.com/eventorganizer2/events/event_id=1/new
http://my-app.com/eventorganizer3/events/event_id=1/new

Instead of explicitly declaring all the routes by the event organiser inside React Router, what strategy can I adopt to generate them on the fly (for example, assuming all the event organisers are stored inside a mongoose model)?r

A: For posterity, I found the answer to my question.
The idea is to generate 'Links' from mongoose/array/API through something like a map function,then funnel the routes using React-Router and finally, processing these routes through match.params:
const EventOrganisers = () => (

      {
        eventorganisersAPI.all().map(p => (

            <Link to={`/eventorganiser/events/${p.number}`}>{p.name}</Link>

        ))
      }

)

...

<Route path='/eventorganiser/events/:event_id' component={Event}/>

A: If you want to setup a more generic route handler you could add the following route and create a component to process all requests:

Route path="*" component={RouteHandler} />


text:
Q: Javascript node.js callback function variable scope problems I am in the process of relearning Javascript and last week when writing this code for a university assignment I think that there is probably a much better way of executing this code
app.get('/member/all', function(req, res) {
    connection.query('CALL GetAllMembers()', function(err,rows){
        connection.query('CALL CountMembers()', function(err, allMembers){
            console.log(err);
            connection.query('CALL CountAllIndMembers()', function(err,indMembers){
                console.log(err);
                connection.query('CALL CountInactiveMembers()', function(err,inactiveMembers){
                    console.log(err);
                    connection.query('CALL CountAllMembersInGroups()', function(err,groupMembers){
                        console.log(err);
                        res.render('members', {members : rows[0], title : "All Members",  groupMembers : groupMembers[0][0].AllGrpMembers,
                            inactiveMembers : inactiveMembers[0][0].AllInactiveMembers, indMembers : indMembers[0][0].AllIndMembers,
                            allMembers : allMembers[0][0].AllMembers, statistics : true});
                        });
                    });
                });
            });
        });
    });
});

When I was trying to declare variables under the app.get such as var allMembers... when the callback was executed I was unable to set allMembers = rowsFromTheCallback. It seemed that it was a local variable to that callback. I'm sure this is something to do with the variable scope and/or hoisting. Just wanted to ask you guys if there would be a better way to do this as even though this function works. It is very ugly to look at haha!
Thanks in advance
Jack

A: As far as scope goes, all the inner functions should be able to read and write to the outer variable unless it is shadowed by an inner variable declaration or function parameter.
The problem you are having might be related to the async-ness of the code. See this code:
function delay(n, cb){
    setTimeout(function(){ bs(delay) }, delay);
}

function main(){
    var allMembers = 17;
    delay(500, function(){
        console.log(allMembers);  // This looks at the outer "allMembers"
        allMembers = 18;

        delay(200, function(allMembers){  // <-- SHADOW
            console.log(allMembers); // This looks at the allMembers from "delay 200"'s callback
            allMembers = 42;
        });

        delay(300, function(){
            console.log(allMembers); //This is the outside "allMembers" again
        });
    });

    return allMembers; // Still 17!
}

main();

main will return before the setTimeouts have even fired so its going to return the original value of that variable. In order to wait for the inner callbacks to run, the only way is to make main take a callback to signa when its done, instead of just returning.
function main(onResult){
   delay(500, function(){
      //...
      onResult(allMembers);
   });

   // <-- no return value
});

main(function(allM){
    console.log(allM);
});

A: See async library: https://github.com/caolan/async
async.series([
  getAllMembers,
  countMembers,
  ...
], function(err, results) {
  // err contains an error if any of the functions fails. No more functions will be run.
  // results is an array containing results of each function if all the functions executed without errors
}));

function getAllMembers(callback) {
  connection.query('CALL CountMembers()', callback);
}

function countMembers(callback) {
 ...
}

If the execution order of the functions does not matter, async.parallel can be used instead of async.series.

A: There is power in using a library to handle and encapsulate "Continuation Passing Style" (CPS) interactions with your asynchronous calls. The following code isn't from a library, but I'm going to walk through it and use it as an example of one way to implement CPS.
Setting up a scope appropriate queue is the first step. This example uses about the most simple method for doing so:
var nextList = [];

After that we need a method to handle our first case, the need to queue tasks to be performed in the future. In this case I was focused on performing them in order so I named it next.
function next() {
    var todo,
        current,
        task,
        args = {};
    if (arguments.length > 0) { // if called with parameters process them
        // if parameters aren't in an array wrap them
        if (!Array.isArray(arguments['0'])) {
            todo = [arguments];
        } else { // we were passed an array
            todo = [];
            arguments['0'].forEach(function (item) {
                // for each item we were passed add it to todo
                todo.push(item);
            });
        }
        nextList = todo.concat(nextList);
        // append the new items to the end of our list
    }
    if (nextList.length > 0) { // if there are still things to do
        current = Array.prototype.slice.apply(nextList.shift());
        task = current[0];
        args = current.slice(1);
        task.apply(null, args); // execute the next item in the list
    }
}

This allows us to make calls like:
.map(function (filepath) {
    tasks.push(
        [
            handleAsset,
            {
                'path': filepath,
            }
        ]
    );
});
tasks.push([done]);
next(tasks);

This will call handleAsset, which is async, once for each file, in order. This will allows you to take your code and change each of the nested calls into a separate function in the form:
function memberAll() {
    app.get('/member/all', function(req, res) {
        if (err) {
            handleError(err, 'memberAll');
        } else {
            next(getAllMembers, 'parameters to that call if needed');
        }
    });
}

where handleError is a common error handler, and the next call allows you to pass on relevant parameters to the next function that is needed. Importantly in the success side of the if statement you could either:

*

*conditionally call one of several functions

*call next with an array of calls to make, for instance if you had functions for processFolder and processFile you could expect that processing a folder might involve processing other folders and files and that the number would vary

*do nothing except call next() with no parameters and end the current branch

Embellishments can include writing a clean function for emptying the nextList, adding items to nextList without calling an item from the list, etc. The alternative at this point is to either use an existing library for this or to continue writing your own.


text:
Q: Google oauth authorization code expired? After finally getting something besides NULL to be returned for an access token or refresh token, I am now getting an error saying my authorization token is expired. I've tried authorizing with 2 different Google accounts at different hours of the day, but I keep on getting the same authorization token.
How do I get a new, valid authorization token? When I go to account settings to remove authorization access for the app I am building in hopes to reset it, it isn't listed as an authorized app / service.
Here is my code:
require_once 'vendor/autoload.php';
$redirect_uri = 'site url';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->authenticate($_GET['code']);
$refreshToken = $client->getRefreshToken();
var_dump($refreshToken);
$accessToken = $client->getAccessToken();
$aT = $client->fetchAccessTokenWithAuthCode($_GET['code']);
var_dump($accessToken);
var_dump($aT);

The last line is what returns the error. The other var_dumps return NULL.

A: The process you are following for authentication is not the proper one, or at least that what it seems. After setting the client configuration you have to check if you have an access code, if there is no access code then you redirect the user to authenticate and after the user is authenticated, you redirect the user to do what you want. You are also missing the scopes your app needs in order to get proper access. Delete your app from the connected apps and sites in your Google profile and then try the following please:
<?php session_start();

//INCLUDE PHP CLIENT LIBRARY
require_once 'vendor/autoload.php';

$scopes = array("email");

// Create client object
$client = new Google_Client();
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/index.php');
$client->setAuthConfig("client_secrets.json");
$client->addScope($scopes);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');

if ( isset($_SESSION['access_token']) && $_SESSION["access_token"]){

  $client->setAccessToken($_SESSION['access_token']);

  print_r($_SESSION['access_token']);

  echo "
***************************************************************************************************************************************
";

  print "Access token creation time: ".date('M d, Y - H:i:s', $_SESSION['access_token']['created']);

  echo "
*********************************************************************
";

  print "Refresh token: ".$_SESSION['access_token']['refresh_token'];

} else {

    if (!isset($_GET['code'])) {

      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

    } else {

      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();

      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

    }

}

?>

Please don't forget to review the documentation that explains the authorization process wich is found here.


text:
Q: String concatenation and appening are not working inside foreach I have an array of objects, let's say Cars. There's an attribute in the object called "selected" with setters and getters.
The user can select/deselect cars form a recycleview and I update the data correctly using the adapter. Now when the user clicks a button I want to extract a string of IDs of all the selected cars.
So I did this.
 String cars_ids = "";
 StringBuilder car_builder = new StringBuilder();
        for (Car car: carList) {
             // I added this log to make sure that there are in fact selected cars. and there are!
            Log.e("==>> cicarty ",  car.isSelected() +"");
            if (car.isSelected()) {
                car_builder.append(car.getID()).append(",");
            }
        }

        if (!cars_ids.isEmpty()){
            cars_ids = car_builder.toString().substring(0, car_builder.toString().length() - 1).trim();
        }
        // cars_ids is always empty...!!
        Log.e("=>> ", " cars_ids : " + cars_ids );

And I also tried with concatenation and it didn't work either
 String cars_ids = "";
        for (Car car: carList) {
            Log.e("==>> cicarty ",  car.isSelected() +"");
            if (car.isSelected()) {
                cars_ids.concat(car.getID() + ",");
            }
        }

        if (!cars_ids.isEmpty()){
            cars_ids = cars_ids.substring(0, cars_ids.length() - 1).trim();
        }
        // cars_ids is always empty again...!!
        Log.e("=>> ", " cars_ids : " + cars_ids );

A: if (!cars_ids.isEmpty()){

is always false with the StringBuilder because it is always empty: you are appending to the StringBuilder, then checking the String.
Use:
if (car_builder.length() > 0){

instead. And then
// cars_ids is always empty...!!
Log.e("=>> ", " cars_ids : " + cars_ids );

Yep, always empty because you didn't change it. Assign car_ids = car_builder.toString() first.

cars_ids.concat(car.getID() + ",");

won't do anything useful because you're ignoring the return value. Instead:
car_ids = cars_ids.concat(car.getID() + ",");

or, more idiomatically:
car_ids += car.getID() + ",";

It's worth mentioning that in Java 8+, you could more easily use a StringJoiner to achieve the same.

A: Alternatively you can reduce your code to a one liner using Java 8:
String cars_ids = carList.stream().filter(Car::isSelected).map(Car::getID).collect(Collectors.joining(","));

A: Since strings are immutable , stringObject.concat does not change the string but actually returns a new string. Thus, you should use reassignment. See the following code.
 String cars_ids = "";
    for (Car car: carList) {
        Log.e("==>> cicarty ",  car.isSelected() +"");
        if (car.isSelected()) {
            cars_ids = cars_ids.concat(car.getID() + ","); // This line is changed
        }
    }

    if (!cars_ids.isEmpty()){
        cars_ids = cars_ids.substring(0, cars_ids.length() - 1).trim();
    }
    // cars_ids is always empty again...!!
    Log.e("=>> ", " cars_ids : " + cars_ids );

A: More better:

String cars_ids = "";
 StringBuilder car_builder = new StringBuilder();
        for (Car car: carList) {
             // I added this log to make sure that there are in fact selected cars. and there are!
            Log.e("==>> cicarty ",  car.isSelected() +"");
            if (car.isSelected()) {
                 cars_ids+=","+(car1.getID());
            }
        }
        Log.e("=>> ", " cars_ids : " + cars_ids.replaceFirst(",", ""));

A: The if condition will always be false, change it to
if (cars_ids.isEmpty())

The string builder values will be assigned to the cars_ids variable


text:
Q: Can I modify a value inside a BinaryHeap that isn't the top value? Is there any way I can modify a value inside a Min-Heap that isn't the top, and have the heap updated to do so? Looking at the API, there doesn't seem to be any clear way to access these elements and invoke any type of update method.

A:
modify a value [...] and have the heap updated

No, the standard library's implementation of BinaryHeap does not allow adjusting any values that would require the heap ordering to change. The documentation even specifically calls out interior mutability as a bad idea (emphasis mine):

It is a logic error for an item to be modified in such a way that the item's ordering relative to any other item, as determined by the Ord trait, changes while it is in the heap. This is normally only possible through Cell, RefCell, global state, I/O, or unsafe code.

There may be alternate implementations of binary heaps on crates.io, however.

A:
Is there any way I can modify a value inside a Min-Heap that isn't the top, and have the heap updated to do so?

You can modify values inside a Min-Heap, but no, the modification shall not alter the ordering of the item relatively to any other item in the BinaryHeap. Otherwise, the BinaryHeap will not be a max heap any more and there is no way to update it. You could convert the BinaryHeap to a sorted Vec, modify, re-sort, and convert the sorted Vec back into a BinaryHeap.
Example of how to modify elements inside a BinaryHeap without changing the relative order (full example in the playground):
struct Foo(i32, Cell<bool>);
impl Ord for Foo {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

fn main() {
    let mut bh = BinaryHeap::new();
    bh.push(Foo(0, Cell::new(true)));
    bh.push(Foo(1, Cell::new(false)));
    bh.push(Foo(2, Cell::new(false)));

    println!("{:?} => {:?}", bh, bh.peek());
    // prints:
    // [..., Foo(1, Cell(false))] => Some(Foo(2, Cell(false)))

    // Modify `Foo(1, false)` to `Foo(1, true)`:
    for i in bh.iter() {
        if i.0 == 1 {
            i.1.set(true);
        }
    }

    println!("{:?} => {:?}", bh, bh.peek());
    // prints:
    // [..., Foo(1, Cell(true))] => Some(Foo(2, Cell(false)))
}

Here, Foo's Ord implementation only depends on the value of first field (i32). That is, modifying the value of Foo's second field (bool) does not change the ordering of any Foo relatively to any other Foo.
The requirements of BinaryHeap let us go one step further and also modify the first field of Foo as long as we don't change the ordering of any Foo relatively to any other Foo in the BinaryHeap. That is, we can change Foo(0,..) to Foo(-3,..) in this particular BinaryHeap without issues.
If the BinaryHeap were to contain a Foo(-2,...), then changing Foo(0,..) to Foo(-3,..) would leave the BinaryHeap in an inconsistent state: it wouldn't be a max heap anymore. Still, note that no unsafe code is required anywhere to modify the elements of the BinaryHeap. That is, BinaryHeap upholds all safe Rust guarantees (no undefined behavior) even in the presence of "logic errors" that produce an inconsistent state.
What you can do instead is to convert the heap into a vector, modify it, and convert it back into the heap which will rebuild the whole heap (playground):
let mut bh = BinaryHeap::new();
bh.push(0);
bh.push(1);
bh.push(2);

println!("{:?} => {:?}", bh, bh.peek());

// convert into a vector:
let mut v = bh.into_vec();
println!("{:?}", v);

// modify in a way that alters the order:
v[1] = -1;
println!("{:?}", v);

// convert back into a binary heap
let bh: BinaryHeap<_> = v.into();
println!("{:?} => {:?}", bh, bh.peek());


text:
Q: Downgrading libxml2 on 12.04 For some reason, on one of the servers that we have in our network running Ubuntu Server 12.04, the version of libxml2 is 2.8.0 (which is the one from Ubuntu 12.10).
This creates some issues, especially since I need to install libxml2-dev and I get some unmet dependencies. I get the following error:
libxml2-dev : Depends: libxml2 (= 2.7.8.dfsg-5.1ubuntu4.9) but 2.8.0+dfsg1-5ubuntu2.2 is to be installed

I do not know why the newer version of libxml2 is present on the system, but is there a way to either use the new version of libxml2-dev (which is not present in the default sources.list) or to safely downgrade libxml2 to the correct version for 12.04?

A: try:
apt search libxml2

this command show search from any evidence: repositories and installed packages.
so if you will see for example for trusty:
libxml2/trusty-updates,trusty-security,now 2.9.1+dfsg1-3ubuntu4.3 amd64
[installed]
  GNOME XML library

libxml2-dbg/trusty-updates,trusty-security 2.9.1+dfsg1-3ubuntu4.3 amd64
  Debugging symbols for the GNOME XML library

libxml2-dev/trusty-updates,trusty-security,now 2.9.1+dfsg1-3ubuntu4.3 amd64
  [installed,automatic]
  Development files for the GNOME XML library

so, obviously, if you see this output you are have alot of chances to install version.
However if you need the package strictly by version, try indicate the version alike this:
sudo apt-get install libxml2=2.9.1+dfsg1-3ubuntu4.3
sudo apt-get install libxml2-dbg=2.9.1+dfsg1-3ubuntu4.3
sudo apt-get install libxml2-dev=2.9.1+dfsg1-3ubuntu4.3

OR by indicating target repository:
sudo apt-get install libxml2/precise libxml2-dbg/precise libxml2-dev/precise

After it's installed, run the following command to hold your installed version, preventing the package manager from automatically updating it in the future:
sudo echo "libxml2 hold" | sudo dpkg –set-selections

With --no-remove option apt-get will exit installation process anytime without any prompts if any packages are to be removed:
sudo apt-get install --no-remove libxml2=2.7.8.dfsg-5.1ubuntu4.9

Other goody: --no-install-recommends which claim the apt-get do not consider recommended packages as a dependency for installing.
Read apt-get precise pangolin manpages
Hope it help you.


text:
Q: Send and Rcived Image from Json webservice error: NotFound I have create a jSON web service to save profile data with image. my service work properly but when send data  to service HttpWebRequest return "The remote server returned an error: NotFound."
My code is this
 void SendPost()

 {

            string webServiceAddress = @"http://localhost:51018/AMFDecember/WebService.asmx";
            string methodName = "Register";
            string url = string.Format("{0}/{1}", webServiceAddress, methodName);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
           webRequest.ContentType = "application/x-www-form-urlencoded";
           webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackx), webRequest);
      }

void GetRequestStreamCallbackx(IAsyncResult asynchronousResult)
        {
            HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            // End the stream request operation
            Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
            StreamReader streamReader = new StreamReader(postStream);
            string Response = streamReader.ReadToEnd();
 string img="";

  try
            {

                string img = Convert.ToBase64String(imageBytes);
            }
            catch { }
            // Create the post data
          string postData = "";

      // <emailID>string</emailID>
      //<pwd>string</pwd>
      //<name>string</name>
      //base64Binary

          postData = "emailID=pr@pr.pr&pwd=1234&name=test&img=" + Convert.ToBase64String(imageBytes) + "";

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            try
            {
                postStream.Write(byteArray, 0, byteArray.Length);
            }
            catch { }
            postStream.Close();

            // Start the web request
            webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
        }

        void GetResponseCallback(IAsyncResult asynchronousResult)
        {

            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;
                // End the get response operation
                response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);

                Stream streamResponse = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(streamResponse);
                string Response = streamReader.ReadToEnd();

                streamResponse.Close();
                streamReader.Close();
                response.Close();

            }
            catch (WebException e)
            {
                // Error treatment
                // ...
            }
        }

A: I think your problem might be "http://localhost" - this means the service should be on localhost - i.e. within your phone?
Maybe try using the network ip address of your PC instead - you might need to use full IIS or IISExpress to host your service for this.


text:
Q: What does "comfortable" really mean? I'm a native English speaker and I've learned the word "comfortable" by example, but based on the structure of the word and all of the other examples of "V-able" that I've heard, it seems that "comfortable" is usually used inaccurately.
To say "I am comfortable" would seem to mean "I can be comforted", but most people would seem to think it means "I have been comforted".
Does "V-able" not mean "can be V-ed"?
Is there a more accurate word for the way most native speakers would seem to use "comfortable"?
We say "I am pleased", not "I am pleasable".

A: Originally the word referred to something that provided (was able to provide) spiritual comfort. The meaning later extended to providing physical comfort and also being the recipient of that comfort.
https://www.etymonline.com/word/comfortable
To say the modern meaning of the word is "wrong" is an example of the etymological fallacy.

A: You're going to run into a lot of trouble if you're bothered by inconsistency in the meaning of suffixes. There are other "irregularly" formed -able words, like reliable and dependable (we say that we rely on or depend on something), and there are also other derived words that have developed meanings that don't correspond exactly to the meaning of the base word (for example, the adverbs practically and virtually are often used to mean "nearly, almost" in a way that doesn't mesh very well with the literal or original meanings of the words practical and virtual).
With a non-technical word like comfortable, it really doesn't make much sense to say that it is "usually used inaccurately". The meaning is defined by the usage.
If you really want a different word for it, you can check a thesaurus. Thesaurus.com shows some words with similar meanings, like cozy, snug, relaxed, contented. But vague words like this generally don't have exact synonyms.


text:
Q: How to make subscript enclosed in empheq environment I was trying to use pandoc to generate beamer slides with equation highlighted using empheq package, then I have this problem of equations with subscripts are not able to convert to proper latex code. I made a minimal case here, and hopefully anyone of you out there can help me to get the subscript correctly converted. Thanks in advance for your help.
I have a minimalist markdown file buggy.md here that reproduced my issue. The file contains two coloured equations, one without subscript and one with subscript:
\begin{empheq}[box=\mymath]{equation*}
   c
\end{empheq}

\begin{empheq}[box=\mymath]{equation*}
   c_n
\end{empheq}

Then, I tried to convert it into buggy.tex file using pandoc using the following command
pandoc buggy.md -o buggy.tex

The results of the two equations are very different. The one without subscript are converted to tex without any issue, but the one with subscript is totally wrong. I have the content of the buggy.tex here:
\begin{empheq}[box=\mymath]{equation*}
   c
\end{empheq}

\textbackslash{}begin\{empheq\}{[}box=\mymath{]}\{equation*\} c\_n
\textbackslash{}end\{empheq\}

I would expect that after the pandoc conversion, the output buggy.tex should be the same as the original buggy.md, but it is not the case. The same issue happened if the environment used is align* or eqnarray*.
How do I get back my coloured equation with subscript? Thank you for your help and time.

A: I cannot reproduce this, the issue has likely been resolved in newer pandoc versions.
If you are using pandoc 2.0 or later, then you can also explicitly mark your LaTeX snippets as such:
```{=latex}
\begin{empheq}[box=\mymath]{equation*}
   c
\end{empheq}
```

See the manual for the raw_attribute extension for details.


text:
Q: Binary search in 2D array using custorm Comparator I have a 2D integer array [n][3] and a target value.
I sort the array using
Arrays.sort(arr, (a,b)->Integer.compare(a[1],b[1]));

How can I use Arrays.binarySearch and a custom comparator to search arr along index 1 for a target value?  Something that could replace the following:
   int binSearch(int[][] arr, int target) {
      int low=0, high=arr.length-1;
      while( low < high ) {
         int mid=(low+high)/2;
         if( arr[mid][1] == target ) {
            return i;
         }
         else if( arr[mid][1] < target {
            low=mid+1;
         }
         else {
            high=mid-1;
         }
      }
      return -(low+1);
   }

EDIT: Arrays.sort works how I need it to - my initial array for example {{1,3,5},{7,1,6},{4,2,1}} sorts on the middle value to {{7,1,6},{4,2,1},{1,3,5}}
I thought I could write a similar expression for Arrays.binarySearch where each element (1x3) of the array is compared to a target integer.  Something like:
int idx = Arrays.binarySearch(arr, target, (a,b)->Integer.compare(a[1],b));

I can't really use the same comparator as in the sort because they are different types - the search array is an array of 1x3 sized elements and my target is a single integer.  I need to do a binary search.

A: Static method Arrays.binarySearch() has the following declaration:
public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)

Where T is the type of the elements in the array. In this case, it happens to be int[].
The important distinction between your method binSearch() and Arrays.binarySearch() is that your method expects an int argument target, meanwhile you need to pass int[] into binarySearch().
Since the required comparator needs only the second element (i.e. at index 1) of the array, the other elements of the key can have any value. Therefore, an array of two elements, like that
new int[]{0, target} // the first value, is arbitrary

will be a sufficient in order to utilize the built-in binarySearch().
int index = Arrays.binarySearch(source, new int[]{0, i}, comparator);

To define a comparator, you might make use of static methods comparing() and comparingInt() of the Comparator interface introduced with Java 8.
With that, the code bowls down to a couple of lines, and might be written like that:
public static void main(String[] args) {
    int[][] source = {{1, 3, 5}, {7, 1, 6}, {4, 2, 1}};

    Comparator<int[]> bySecondElement = Comparator.comparingInt(arr -> arr[1]);

    Arrays.sort(source, bySecondElement);

    for (int i = 0; i < 4; i++) { // searching for arrays having a value of i as second element
        int index = Arrays.binarySearch(source, new int[]{0, i}, bySecondElement);
        System.out.printf("target: %d\tindex: %d\n", i, index);
    }
}

Output
target: 0   index: -1   // no such element
target: 1   index: 0    // {7, 1, 6}
target: 2   index: 1    // {4, 2, 1}
target: 3   index: 2    // {1, 3, 5}


text:
Q: Is there a way to run scripts when someone is answering to a Google Form? So, here at the company I work for we usually manage the workforce weekends schedules in a very manual way using Excel, and then upload a pdf version of the sheet in our intranet so everyone can see their own schedule for the rest of the month and look up for swaps if they need to.
The problem is that the workforce recently has grown up a lot and we're spending a lot of time validating and reuploading the schedule everytime we need to do the shift swaps. So I decided to start a project using Google Sheets and Google Forms, so we could just show iFrame of the sheet in the view mode, and their supervisors could make their swaps via a google form, which would update the sheet and they could see it happening on-the-fly, I guess.
Now that I gave you some context, what I really need is to discover if there's actually a way to accomplish what I'm trying to, because I already stuck once realizing that the script running from a Google Sheet only works with edit permissions (I need to no one have permission to change manually the sheet and preferably not even needing to link account to Google), but now I realized even when scripting inside of the form it doesn't run when people are answering to the form, but only in the edit mode, which I think it's useless for me since questions should be dynamic (the form would look for the available weekends and employees in the sheet using some validations).
For example, the code below runs when I open the form in Edit mode, but not when I open the shared link:
function onOpen() {
 var ui = FormApp.getUi();
  ui.alert('test');
}

So, my question is if this project is possible using Google Scripts and the suite, if there's some kind of option or permission I'm missing to make it work, or if it's worth I try to do it using an not inbound countainer script, or maybe HTML Service, or if I should forget Google and look for another tools for this job.
Thanks.


text:
Q: How to handle permission in rails Normal User adds a post to the system, he then has the ability to update and delete this post. In the future, he may want to assign other users the ability to edit, delete, update etc.
My models are
class Post
  has_many :post_users
  has_many :users, through: :post_users
end

class PostUser
  belongs_to :post
  belongs_to :user
end

class User
  has_many :post_users
  has_many :posts, through: :post_users
end

I need something like this in my ability.rb
user ||= User.new # guest user (not logged in)

can :read, :all
can :manage, Post, postuser: postuser.user.id

So I could manage posts only when in clients_users table is a record with user_id and id of this post. How do I make it work?

A: I have not used cancancan gem.
But reading through your add_user action and cancancan documentation for Defining abilities for associations, I think you need to define you code similar to following:
class Ability
  include CanCan::Ability

  def initialize(user)
    if user.present?  # additional permissions for logged in users (they can read their own posts)
      can :manage, Post, post_users: { user_id: user.id }
    end
  end
end

Try and let me know if you face any issues. Might need some debugging and changes.


text:
Q: I want to get the substring from string displayed in dropdown Dropdown has value like Pune (Maharastra). I want to display only Pune. There are almost 250 records, I want to do it for all.
Please help.

A: You can do that like following example
String oldValue = "Pune (Maharastra)";
String newValue = oldValue.substring(0,oldValue.indexOf("("));

With Regular Expression:
 String oldValue = "Pune (Maharastra)";
 Pattern pattern = Pattern.compile("\\w+");
 Matcher matcher = pattern.matcher(oldValue);
 String newValue = "";
 while (matcher.find()) {
          newValue = matcher.group();
          break;
 }

A: you can put some condition and get string in split form. For how to spil check the below links.
    http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
    http://www.tutorialspoint.com/java/java_string_substring.htm


text:
Q: Typescript: get type of generic type I'm new to Typescript (come from C#) and i'm struggeling with the "special" generic implementation.
Here is my code:
function createValue<TValue extends string | boolean>(): TValue[]
{
    let result = new Array<TValue>();

    if (typeof TValue === "string") // error 'TValue' only refers to a type, but is being used as a value here
    {
        result[0] = "abc" as TValue;
    }
    else
    {
        result[0] = false as TValue;
    }

    return result;
}

console.log(createValue<boolean>());

How did i get the type?
I'm allready tried pretty ugly solutions to create a value, but this also don't behave as expected.
let value : TValue = new Array<TValue>(1)[0];
let type = typeof value; // undefined

There exists several solutions for object types but i didn't get it for primitives.
Could you give me any help?
Thanks

A: Because Types did not exists at runtime i end up with a solution like this:
enum Types
{
    string,
    boolean,
    number
}

function getType<TValue extends Types.string | Types.boolean>(t: TValue): Array<TValue extends Types.string ? string : boolean>
{
    if (<Types>t == Types.string)
    {
        let arr = new Array<string>();
        arr[0] = "abcd";
        return arr as Array<TValue extends Types.string ? string : boolean>;
    }

    let arr = new Array<boolean>();
    arr[0] = false;
    return arr as Array<TValue extends Types.string ? string : boolean>;
}

console.log(getType(Types.boolean));

A: Your problem lies in using the TypeScript type at runtime.
TypeScript is compiled to JavaScript, therefore your execution does not see the the type TValue at all.
The typeof operator is used to reuse type information at other places but not at runtime. E.g.
function test(arg: string): boolean;

function test2(func1: typeof test): boolean;

Depending on what you want to achieve, you need to give a string argument that specifies your operation.
function createValue(type: 'string' | 'boolean') {
    let result = new Array();

    if (type === "string")
    {
        result[0] = "abc";
    }
    else
    {
        result[0] = false;
    }

    return result;
}

console.log(createValue('boolean'));

TypeScript should be able to infer your types from there. If not, you could look into conditional types.


text:
Q: AWS lambda missing events from dynamodb stream I am consistently missing lambda triggers from a dynamodb stream. I am mapping the dynamodb stream to the lambda function with event_source_mapping resource.
resource "aws_lambda_event_source_mapping" "history" {
  event_source_arn  = "${data.aws_dynamodb_table.auditlogDynamoDB.stream_arn}"
  function_name     = "${module.cx-clientcomm-history-lambda.lambda_function_arn}"
  starting_position = "LATEST"
  maximum_retry_attempts = 0
  maximum_record_age_in_seconds = 604800 // adding to explicitly set. QA plan was providing invalid value
  #(Optional) An Amazon SQS queue or Amazon SNS topic destination for failed records.
  destination_config {
    on_failure {
      destination_arn = "${data.aws_sns_topic.cx-clientcomm-sns-slack.arn}"
    }
  }
}

It appears when there are entries in dynamodb are coming it very close to each other, some are not picked up by the event_source_mapping and not sent to the lambda.
Is there a way to make sure this doesn't happen? This needs to be very reliable


text:
Q: MYSQL Date of monday in given week and year, mode 7 I'm trying to get the date of the first Monday by given week number and year.
I found this code: SELECT STR_TO_DATE(CONCAT('20131',' Monday'), '%x%v %W') as MQK;
It works in most cases, following mode 3, but I want it in mode 7. Date and Time Functions
For example, if the year is 2013 and week 1, it gives:
mysql> SELECT STR_TO_DATE(CONCAT('20131',' Monday'), '%x%v %W') as first_day;
+------------+
| first_day  |
+------------+
| 2012-12-31 |
+------------+
1 row in set (0.00 sec)

I'm expecting date 2013-01-07.
Is it possible?

A: You would have to implement a conditional to emulate the mode 7 behavior.
SELECT @y := 2013 as `@y`, @w := 1 as `@w`,
       @d := STR_TO_DATE(CONCAT(@y, @w, ' Monday'), '%x%v %W') as `@d`,
       IF (YEAR(@d) < @y, DATE_ADD(@d, INTERVAL 1 WEEK), @d) as first_day;

You would get:
+------+----+------------+------------+
| @y   | @w | @d         | first_day  |
+------+----+------------+------------+
| 2013 |  1 | 2012-12-31 | 2013-01-07 |
+------+----+------------+------------+

And, in 2007 where Jan 1 is the first Monday of the year:
SELECT @y := 2007 as `@y`, @w := 1 as `@w`,
       @d := STR_TO_DATE(CONCAT(@y, @w, ' Monday'), '%x%v %W') as `@d`,
       IF (YEAR(@d) < @y, DATE_ADD(@d, INTERVAL 1 WEEK), @d) as first_day;

+------+----+------------+------------+
| @y   | @w | @d         | first_day  |
+------+----+------------+------------+
| 2007 |  1 | 2007-01-01 | 2007-01-01 |
+------+----+------------+------------+

Added 2018-10-25:
So, apparently this doesn't work for 2013 week 2, which using the above query results in 2013-01-07 which is actually the Monday for week 1.  In hindsight, this was kind of obvious based on the approach I originally proposed and the obvious solution just jumped out at me.
SELECT @y := 2013 as `@y`, @w := 1 as `@w`,
       @d := STR_TO_DATE(CONCAT(@y, @w, ' Monday'), '%x%v %W') as `@d`,
       IF (WEEK(@d, 7) <> @w, DATE_ADD(@d, INTERVAL 1 WEEK), @d) as first_day;

+------+----+------------+------------+
| @y   | @w | @d         | first_day  |
+------+----+------------+------------+
| 2013 |  1 | 2012-12-31 | 2013-01-07 |
+------+----+------------+------------+

SELECT @y := 2013 as `@y`, @w := 2 as `@w`,
       @d := STR_TO_DATE(CONCAT(@y, @w, ' Monday'), '%x%v %W') as `@d`,
       IF (WEEK(@d, 7) <> @w, DATE_ADD(@d, INTERVAL 1 WEEK), @d) as first_day;

+------+----+------------+------------+
| @y   | @w | @d         | first_day  |
+------+----+------------+------------+
| 2013 |  2 | 2013-01-07 | 2013-01-14 |
+------+----+------------+------------+

Heh.


text:
Q: Plugin Test fails with NPE New to the grails testing, and trying to get a spock test to work in our application. The main grails application is not much more than a container for plugins which provide the real functionality.
So in one of the plugins, I created a functional test using spock.
package com.my.package

import grails.test.mixin.TestFor
import grails.test.mixin.Mock
import spock.lang.Specification

@TestFor(MessageController)
class MessageControllerSpec extends Specification {

    def "markMessageSent missing id should return 404"() {
        given:
        def result = controller.markMessageSent()
        expect:
        result.status = 404
    }
}

Error Error executing script TestApp: java.lang.NullPointerException: Cannot get property 'contextPath' on null object.
I use this to run the tests:
grails -Dsis.type=colleague -Dserver.port=8001 test-app :spock

Ideas?


text:
Q: Android Data Binding Library vs Kotlin Android Extensions I'm reading about how the MVVM architecture works and how to use Android Data Binding Library help.
In a very general way I understand that Android Data Binding creates a link between UI layer and the underlying data model that holds the information to display.
Kotlin Android Extensions are another Kotlin plugin that will allow you to recover views from Activities, Fragments and Views. The plugin will generate some extra code that will allow you to access views in the XML layout, just as if they were properties with the name of the id you used in the layout definition.
What is the difference between using Android Data Binding Library and Kotlin Android Extensions? Are they for different purposes? Do they complement each other, in what way?
Thank you for your answers.

A: Both, Kotlin Android Extensions and Android Data Binding Library help to eliminate the use of findViewById.
But there are also more things that these do, that can complement one another.
To elaborate, with the Android Data Binding library, you can 'set' models in your xml files, which can then directly be leveraged to set values for the views in the layout. See how a <data> tag can be used with the data binding library.
Kotlin android extensions does not provide for this.
At the same time, Kotlin android extensions provides for some amazing features like @parcelize annotation to make classes parcelable with almost no boilerplate code, etc.
To conclude, while they both eliminate the use of findViewById, they have their own features too which can complement one another well.

A: Kotlin Android Extensions does not stand for only view binding. It contains other features as well. But I guess you're talking about the view binding/caching features of Kotlin Android Extensions and wonder whether we still need data binding, since we already got rid of the findViewById calls with the synthetic properties of Kotlin. That was the question I asked to myself and my conclusion is, yes, data binding is still worth using.
From official documentation:

The Data Binding Library creates an immutable field in the binding
  class for each view that has an ID in the layout… The library extracts
  the views including the IDs from the view hierarchy in a single pass.
  This mechanism can be faster than calling the findViewById() method
  for every view in the layout.

So data binding doesn't call findViewById on views one by one. Kotlin's synthetic classes, on the other hand, still calls findViewById on the views under the hood, but it calls it only once for each view and caches the view reference for next calls. (Here is an article about it)
Besides, data binding has more to offer than only view caching. You can use data tags for passing data to the binding implementation and declare them in your xml, instead of setting them programmatically. This way you can get rid of the boilerplate code that you use for populating data, like those "setText"s, "setImageResource"s etc. You can set event listeners from xml using data binding. You can also come up with your own attributes using custom binding adapters.  When used to its whole power, it can significantly reduce your Java/Kotlin code.
Edit: It seems that Google Android team recommends against use of kotlin synthetic properties. This article summarizes the discussion around this issue. And you can see in the new Udacity course prepared by Google that they use data binding as recommended practice.
Edit2: If you don't like the idea of "putting business logic in your xml", if you are not interested in setting or getting data from xml, if you simply want to avoid use of findViewByIds in a safe and efficient manner, than you can go with ViewDataBinding library instead. It is a simplified version of data binding library. It doesn't let you set data from your xml but it binds your views in a safe and efficient manner.

A: I strongly disagree with the points mentioned above. maybe because I hate writing logic in XML. so both comments mention the use of <data> tags not found in Kotlin Android Extensions (KTX). with kotlin and KTX you can do better than data tag.
let's say we have
data class Person(val name:String,
                   val phone:String,
                   val isMale:Boolean,
                   val isMarried:Boolean)

in the activity or fragment, we can do
fun updateView(data:Person){
    with(data){

     nameTextField.text = if(isMale){
                            "Mr. $name"
                          } else {
                             if(isMarried){
                              "Mrs. $name"
                             }else{
                              "Miss $name"
                             }
                          }
     phoneTextField.text = phone
    }
 }

in data-binding, you have to do
android:text='@{person.isMale ? "Mr."+user.name: ((user.isMarried ? "Mrs. " :
                 "Miss. ") + user.name)}'
KTX code is way cleaner than what you have to do with data binding to achieve the same result. when you need conditions to set values to view data binding gets ugly.
so for me, Kotlin Android Extensions work better. I like my code clean. you can still use both the decision is yours to make.


text:
Q: passing instance name as string in a function I am creating an Adobe Air Desktop project which has many MovieClips in the MainTimeline (RadioSel, CarMC1, CarMC2, CarMC3, etc).
When you click on any of CarMC  it shows RadioSel (another movieclip)
function showRadio(event: MouseEvent) {
    RadioSel.visible = true;
    RadioSel.instance = event.currentTarget.name;
    trace (RadioSel.instance);
}

The CarMC are MovieClips that have many frames. Each one shows a different shape which depends on RadioSel choice.  The RadioSel is a MovieClip that has multiple radio buttons, each of which changes CarMC to a different shape, and a var called instance which carries the clicked CarMC instance as string.
I created a function inside the RadioSel (called when radiobuttongroup changes) which changes the clicked CarMC to a specified frame and hides the RadioSel.
function chooseCar(CarInstance: String, frame: Number) {
    this["Object(root)."+CarInstance].gotoAndStop(frame);
    this.visible = false;
    //trace(event.target)
}

When I change RadioSel choice, I call this...
chooseCar(instance, frameNo)

... where instance is the name of the CarMC, and frameNo is a number defined by the radio button clicked, however, I get an error every time I call the function. I believe the error is in this part:
this["Object(root)."+CarInstance].gotoAndStop(frame);

How do I fix it?

A: You are not passing an instance (movieclip) but the instance name (string). You should just pass the car instance (movieClip) to make things easier - then you don't care where your cars are and how to access them:
function showRadio(event: MouseEvent)
{
    RadioSel.visible = true;
    // I assume the currentTarget is your car you've clicked on
    // pass the movieclip instance to the radiosel and not just the name
    RadioSel.instance = event.currentTarget as MovieClip;
    trace (RadioSel.instance.name);
}

In your RadioSel:
public var instance:MovieClip;

// no need to pass the instance here as it is saved in the instance property anyway
function chooseCar(frame: Number)
{
    instance.gotoAndStop(frame);
    this.visible = false;
}


text:
Q: Can SMB3 Multipathing be weighted by policy? Consider a configuration with two identical WS2012R2 servers. Both have quad-port network boards. Each has one NIC connected to a subnet shared by other servers and ultimately accessible to client machines. The remaining three ports on each server are 'nic teamed' and connected to a different subnet shared only by the two servers in question. What I would like to see is SMB traffic preferentially going over the faster 3-nic path and only resorting to the more congested 1-nic path if necessary.
Can I trust the load-balancing in SMB3 to do the right thing here? If not, can I apply some sort of weighting similar to tcp/ip route costing?

A: I'm feeling fairly comfortable telling you that the product will "do the right thing" but I don't have a representative environment to simulate exactly what you're talking about.
To talk about it technically, the devil is in details after the server computers communication details of their network interfaces via the FSCTL_QUERY_NETWORK_INTERFACE_INFO API. This negotiation is actually shown as an example in section 4.8 of the [MS-SMB2]: Server Message Block (SMB) Protocol Versions 2 and 3 specification. Unfortunately, the portion of the specification that would contain the logic associated with network connection selection just says "The client selects any one network interface pair to establish a new connection ...". There is some nuance in the interface selection protocol (which, helpfully, Microsoft has omitted from the specification, though I suppose one could argue that this behavior is outside the specification). This article, for example, describes how "non-routable" (read: APIPA and link-local addresses) are not used for SMB multichannel.
Aside from the "non-routeable" addresses described in the article above, this really makes me wonder if there's an implicit assumption in the product that arbitrary network interfaces on a client/server pair are capable of communication. (This could well be a vein of fail just waiting to be mined in some oddball scenarios where traffic filtering / policy makes that assumption untrue.) I'm going to guess there's probably some preference for interfaces in the same subnet as the interface the initial channel was created on. (It would sure be nice if Microsoft published this behavior!) (I see that I'm not the only one who has been thinking about this, at least...)
You can do a Get-SmbMultichannelConnection from the machine to see if SMB multichannel connection between the servers is being created during a long-running copy operation. Add the -IncludeNotSelected argument if you want to see the "not-selected" paths.
You can out-right exclude connections from SMB multichannel with the New-SmbMultichannelConstraint cmdlet, but that's not weighting the channel priority, per se-- it's just exclusion (which isn't what you're looking for).
As an aside: I assume you're using the built-in NIC teaming functionality in W2K12. You may want to check, with your switches, that the LACP hashing algorithm (called the "Load balancing mode" in Windows Server) chosen is optimal. I've seen some talk of changing that mode offering higher throughput with different switches.


text:
Q: keras model equivalent of tf.depth_to_space I want to accomplish the equivalent of tf.depth_to_space in a Keras model.  Specifically, the data in the Keras model is shaped H x W x 4 (i.e., depth of 4) and I want to permute the data so that the output is sized H x W x 1, with the mapping done as viewing the 4 input channels as 2x2 blocks; i.e.,
input location is y, x, k
output location is 2*y+(k//2), 2*x+(k%2), 1
I know that I can get the correct shape with:
outputs = keras.layers.Reshape((H*2,W*2,1), input_shape=(H,W,4))(inputs)

But I think that the mapping will be
input location is y, x, k
Linear_addess is y*W*4+x*4+k
output location is Linear_addess//(H*2), Linear_addess % (H*2), 1
which is not what I want
I tried directly using the
outputs = tf.depth_to_space(inputs, 2)

but that lead to an error:
TypeError: Output tensors to a Model must be Keras tensors. Found Tensor("DepthToSpace:0", shape=(?, 1024, 1024, 1), dtype=float32)
the problem can be seen with this simple function
def simple_net(H=512, W=512):

    inputs = keras.layers.Input((H, W, 4))

    # gets the correct shape but not the correct order
    outputs = keras.layers.Reshape((H*2,W*2,1), input_shape=(H,W,4))(inputs)

    # Run time error message
    #outputs = tf.depth_to_space(output_planes, 2)
    model = keras.models.Model(inputs, outputs)
    return model

A: you should use Keras Lamda layer
from keras.layers import Lambda
import tensorflow as tf

Subpixel_layer = Lambda(lambda x:tf.nn.depth_to_space(x,scale))
x = Subpixel_layer(inputs=x)

MINIMAL MODEL
import tensorflow as tf
from keras.layers import Input,Lambda

in=Input(shape=(32,32,3))
x = Conv2D(32, (3,3), activation='relu')(in)
x = Conv2D(32, (3,3), activation='relu')(x)
sub_layer = Lambda(lambda x:tf.nn.depth_to_space(x,2))
x = sub_layer(inputs=x)
model = Model(inputs=in, outputs=x)
# model.compile(optimizer = Adam(), loss = mean_squared_error)
model.summary()

Summary


text:
Q: Not getting the Tag's nodeValue using DOMDocument class in PHP? i am using DOMDocument class, to parse HTML document in PHP.
     the code of table i am using...

       123 employees

       $50,000

i am not able to fetch nodeValue of the  tag, which are like in the above format,
i.e ($50,000, 123 employees ).

A: Maybe you could use XPath queries. For example:
$doc = new DOMDocument();
$doc->loadHTML(...your html...);

$xpath = new DOMXPath($doc);
$query = '//table/tr/td';

$entries = $xpath->query($query);

foreach ($entries as $entry)
    print_r($entry->nodeValue); (*)

Just replace the line marked with (*) with code that suites your needs.
Cheers.

A: It's hard to say what you are doing wrong if you don't say, what you are doing at all.
But in principle you must get a reference to the table (as a DOM element), then get the rows and cells (child nodes) and get the node value from there.
If your table is the only one in the document, you'll get it via $doc->getElementsByTagName('table')->item(0) (with $doc being the DOM document object).


text:
Q: How to make React Suspense and pending promise working Many articles writing about how to return pending promise and work with React suspense but it's not working in real world.
They don't consider if the component got visited second time, and it won't refetch the data from the server.
e.g. => https://dev.to/darkmavis1980/a-practical-example-of-suspense-in-react-18-3lln?signin=true
The below example would only work for the first time we visit the component but not re-fetch data for the following times.
Any idea to let it work to prevent not doing re-fetching?
Component

const dataFetchWithWrapPromise = (url) => {
    return wrapPromise(window.fetch(url, {
    }));
}

const resource = dataFetchWithWrapPromise('http://localhost:3000/data');

function Articles() {
    const data = resource.read();

    React.useEffect(() => {
        return () => {
            resource.reset();
        }
    }, []);
    return (
        <>

Data

                {JSON.stringify(data, null, 4)}

        </>
    );
}

export default Articles;

function wrapPromise(promise) {
    let status = 'pending';
    let response;

    const suspender = promise.then(
        async res => {
            status = 'success';
            response = await res.json();
        },
        err => {
            status = 'error';
            response = err;
        },
    );

    const handler = {
        pending: () => {
            throw suspender;
        },
        error: () => {
            throw response;
        },
        success: () => {
            console.log(response)
            return response
        },
        default: () => {
            throw suspender;
        },
    };

    const read = () => {
        const result = handler[status] ? handler[status]() : handler.default();
        return result;
    };
    const reset = () => {
        if(status!=='pending') {
            status = 'pending';
            response = undefined;
        }

    }
    return { read, reset };
}

export default wrapPromise;

A: Ok, so I think I got you covered.  It so happens that I liked <Suspense> ever since I heard of it.  I stumbled with it in my learning of asynchronous JavaScript because I was coding wj-config.  This preface is just to let you know that I'm no React master, but it so happens that I ended up creating a React example for wj-config v2.0.0, which is currently in BETA 2.  This example does what you want.
So no more chit-chat.  The code of interest is here.
It is a table component that loads person data from Mockaroo.  The web page (parent) has two controls to specify the number of rows wanted as well as the minimum birth date wanted.  Whenever the value of any of those controls change, the person data is re-fetched.  The table itself uses <Suspense> in two places.
The component module starts by defining the fetching functions needed for person and country data.  Then it declares some variables that are captured in scopes later on.  The starting promise is required for the first render.  Its resolver is exposed through startingResolver, and the starting promise is wrapped as per the <Suspense> mechanics that you clearly know.
Focus your attention now to the PersonsTable function.  It sets up a useEffect call to re-trigger the data fetching operations based on changes of props.  As I'm not a super master in ReactJS, maybe there's a better way than props.  I just know props will trigger the effect automatically, so I used them.
On the first render, the starting promise is thrown, but it will never be fulfilled since it is a bogus promise.  The code inside useEffect makes this promise resolve at the same time the fetching promise resolves.  Then, using the fetching promise, the readPersons function is defined.
NOTE:  I'm not a native English speaker.  Pardon my horrible "persons" instead of "people" mistake. :-(  I'll correct whenever I have time.
Anyway, with this set up, you'll have completed your goal.  The linked code sample goes beyond this by having an inner <Suspense> that waits for country data, but I suppose an explanation is not needed since I believe the question is now covered.
Hope this helps!


text:
Q: How can I change HTML page with jQuery? I use jQuery in the index.html page. The goal is to send a json to another page:
postUploadUrl = "https://localhost:1580/ean/send/file";
$.post({
  url:postUploadUrl,
  contentType: "application/json",
  dataType: "json",
  data: resJson
});

otherpage.html is in another flow.
index.html and otherpage.html are in two different parse template
When I put a break point on the parse template of otherpage.html, I see that Mule goes in the good flow and stops on parse template of otherpage.html.
The problem is that he is not displaying the page autrepage.html. He still on the index.html page.
Part of the flow where there is index.html
<choice doc:name="Choice" doc:id="15c0c63d-4071-4d60-8817-5642ead5fbb6" >
            <when expression="#[vars.isLog != 'true']">
                <parse-template doc:name="index.html" doc:id="bba0a925-fcf3-46cd-9060-cdc4708ae418" location="ean\index.html"/>

</when>
            <otherwise >
            <flow-ref doc:name="Go_Login.hml" doc:id="0e2e49ac-92eb-4376-83ac-33b5c9ff3139" name="Login-Flow"/>
          </otherwise>
      </choice>

Part of the flow where there is otherpage.html
<flow name="Insert-EanFlow" doc:id="16164463-1067-4fd9-9631-5836f4979e8e" >
        <http:listener doc:name="Listener" doc:id="fdd02707-02a8-4b3b-beee-79770b5f6eae" config-ref="HTTP_Listener_config" path="/ean/send/file">

...
...
...
        <parse-template doc:name="Parse Template" doc:id="3dfe5b15-e3fa-4763-b5f4-d0ed41d05eb8" location="ean\otherpage.html" />
    </flow>

Please help.
Best regard.


text:
Q: Integrate Millennial Media Ads using GET Method in Android Android 2.3.3
The documentation of Millennial Media says that I can use a HTTP GET Query to get the AD as a  HTML Response.
My client application needs the ads to be embedded in an article, that comes as a response from server. After getting the response, we construct the page, using HTML tags and display it in a viewpager. While constructing the page, since the response is HTML, i can add it to the page before it gets displayed.
To construct a HTTP GET query, we need to have

*

*APID The Ad Placement ID.

*AUID The Unique Identifier for the device.

*UA   User Agent.

*UIP  The User's Public IP Address.
Where do I get the above to construct the GET query,

*

*APID - from the mmedia site (in my account)

*AUID - ?

*UA - ?

*UIP - ?
How can I query these details?
If someone has previously done this or has an example or a link, please guide me.
EDIT :::
@Millennial Mark
Thanks for the help. Now I have, APID and AUID. I am building this on the client side. So, I can query your server with just these two values and I get a response. - Understood till here.
So assuming my apid = 123149 and auid = eeabcef75ce706b4, my url would be,
http://ads.mp.mydas.mobi/getAd?apid=123149&auid=eeabcef75ce706b4
that's it. No other data needed?
Next question is :::
Can I query the server, with what size of the AD i want. For example, if the app is running on an tablet, I would need a larger banner (for ex: 728x90) than the one I display on the phone(for ex: 320x50). So, can I send the needed banner size along with the HTTP Get request? If so, how?
If I still have questions after this, I will use the support ticket.

A: I've seen a few integrations done this way-- usually in a server-side language like PHP, JSP, or ASP. Depending on what server-side technology you're using, where these variables come from is going to look different. The UA (user agent string) and the UIP (user's external IP address) usually comes from an inbound HTTP request headers. PHP, for instance, has a variable called $_GET for retrieving these parameters so you can pass them onto your Millennial API call. In these cases, it's acceptable but not optimal to pass the same value for AUID as you do for UIP. Then, you can echo out the response of your call to Millennial onto the webpage on its way into your app.
On the other side, if you're trying to build this into your Android app ("client-side")-- getting the AUID is as easy as calling Secure.getString(this, Secure.ANDROID_ID); and UA and UIP can be omitted since your WebView object will populate them in their request headers, and Millennial's servers will be able to recognize them.
If you'd like more guidance (since Stack Overflow is more of a Q&A environment and not a discussion board), I recommend putting in a support ticket at https://tools.mmedia.com/user/supportDevPortal