Solve Non-Linear DOE with Dirac Delta Function in the denominator

Question: I found a differential ordinary equation that uses Diric Delta Function that I don't know how to solve. Thank you if you can help me.
The ODE is like that
$$
z' = \rho \cdot \sqrt{1+z^2} + w \cdot \delta(x-x_0)
$$
And my domain is $\left[a, \ b\right]$ with $a < x_0 < b$. With $\rho$ and $w$ constants.
How can I solve it?

The solution I tried was:
$$
\dfrac{z'}{\rho \cdot \sqrt{1+z^2} + w \cdot \delta(x-x_0)} = 1
$$
$$
I = \int_{a}^{b} \dfrac{z'}{\rho \sqrt{1+z^2}+w\delta} dx = \int_{a}^{b} 1 \ dx = b-a
$$
Now I divide the domain $\left[a, \ b\right]$ in three domains $\left[a, \ x_0 - \varepsilon\right] \cup \left[x_0 - \varepsilon, \ x_0 + \varepsilon\right] \cup \left[x_0 + \varepsilon, \ b\right]$ with $\varepsilon > 0$ small and then make three integrals separately $I_1$, $I_2$ and $I_3$.
$$
I = \lim_{\varepsilon \to 0^{+}} I_{1}(\varepsilon)+I_{2}(\varepsilon)+I_{3}(\varepsilon) = \lim_{\varepsilon \to 0^{+}} \left(\underbrace{\int_{a}^{x_0 - \varepsilon} \square \ dx}_{I_1(\varepsilon)} + \underbrace{\int_{x_0 - \varepsilon}^{x_0 + \varepsilon} \square \ dx}_{I_2(\varepsilon)} + \underbrace{\int_{x_0 + \varepsilon}^{b} \square \ dx}_{I_3(\varepsilon)}\right)
$$
With
\begin{align*}
I_{1}(\varepsilon) & = \int_{a}^{x_0-\varepsilon} \dfrac{z'}{\rho \sqrt{1+z^2}+w\underbrace{\delta}_{0}} dx  = \dfrac{1}{\rho}\int_{z(a)}^{z(x_0-\varepsilon)} \dfrac{dz}{\sqrt{1+z^2}} = \dfrac{1}{\rho} \ln \left(z + \sqrt{z^2-1}\right)_{z(a)}^{z(x_0-\varepsilon)} \\
I_2(\varepsilon) & = \int_{x_0-\varepsilon}^{x_0+\varepsilon} \dfrac{z'}{\rho \sqrt{1+z^2}+w\delta} dx  \overset{\underset{\mathrm{?}}{}}{=}  \int_{x_0-\varepsilon}^{x_0+\varepsilon} 1  \ dx = 2\varepsilon  \\
I_{3}(\varepsilon) & = \int_{x_0+\varepsilon}^{b} \dfrac{z'}{\rho \sqrt{1+z^2}+w\underbrace{\delta}_{0}} dx  = \dfrac{1}{\rho}\int_{z(x_0+\varepsilon)}^{z(b)} \dfrac{dz}{\sqrt{1+z^2}} = \dfrac{1}{\rho} \ln \left(z + \sqrt{z^2-1}\right)_{z(x_0+\varepsilon)}^{z(b)}
\end{align*}
And therefore
\begin{align*}
b - a = I & = \lim_{\varepsilon \to 0^{+}} I_1 + I_2 + I_3 \\
& = \lim_{\varepsilon^{+}} \dfrac{1}{\rho} \ln \left(z + \sqrt{z^2-1}\right)_{z(a)}^{z(x_0-\varepsilon)}  + 2 \varepsilon + \dfrac{1}{\rho} \ln \left(z + \sqrt{z^2-1}\right)_{z(x_0+\varepsilon)}^{z(b)} \\
& = \dfrac{1}{\rho} \ln \left(z + \sqrt{z^2-1}\right)_{z(a)}^{z(b)} + \lim_{\varepsilon \to 0^{+}} \dfrac{1}{\rho} \ln \left(z + \sqrt{z^2-1}\right)_{z(x_0-\varepsilon)}^{z(x_0+\varepsilon)} \\
& \overset{\underset{\mathrm{?}}{}}{=} \dfrac{1}{\rho} \ln \left(z + \sqrt{z^2-1}\right)_{z(a)}^{z(b)}
\end{align*}
I thought about using another function in the place of $\delta$, like
$$
\delta_\varepsilon(x-x_0) =
\begin{cases}
0 \ \ \ \text{if} \ x < x_0 - \varepsilon \\
\frac{1}{2\varepsilon} \ \ \ \text{if} \ x_0 - \varepsilon < x <  x_0 + \varepsilon \\
0 \ \ \ \text{if} \ x_0 + \varepsilon < x \\
\end{cases}
$$
or even a continuous function, but it's harder(or impossible) to calculate the integral:
$$
\delta_\varepsilon(x-x_0) =
\dfrac{1}{\varepsilon \sqrt{\pi}} \exp\left(-\dfrac{1}{\varepsilon^2}(x-x_0)^2\right)
$$
Unfortunately, the physical problem (of this ODE) suggests that $z$ has a linear term of Heaviside Function at the point $x_0$.
Comment: As general advice, a route that seems to require dividing by Dirac $\delta$ is probably not-so-good. Dirac's intuition allowed him to reach useful conclusions doing "(mathematically) crazy" things with $\delta$ and such, but I think he saw no reason to "divide"... and, for all the work I myself have done trying to understand the Schwartz-Grothendieck rigorous basis for much of that, I have absolutely no idea how to make sense of such a division...
Answer: If you divide by $\frac{1}{\sqrt{1+z^2}}$ and integrate you get
$$\int_a^x \frac{z'(w)dw}{\sqrt{1+z(w)^2}}=\rho(x-a)+\frac{w}{\sqrt{1+z^2(x_0)}}\theta(x-x_0)$$
Where $\theta(x)$ is the Heaviside step function. With the substitution $y=z(w)$ in the first integral the antiderivative is elementary and is $\sinh^{-1}y$, so that the solution becomes
$$z(x)= \sinh \bigg [\sinh^{-1}z(a)+\rho(x-a)+\frac{w}{\sqrt{1+z^2(x_0)}}\theta(x-x_0)\bigg]$$
Admittedly, this is a pretty weird solution though given the two initial conditions; do you have any physical reason to know the value of $z$ at $x=a$ and $x=x_0$?
Comment: Thank you! My original question involves the [catenary](https://en.wikipedia.org/wiki/Catenary) which ODE is in fact $y'' = \rho \sqrt{1+(y')^2}$ where $\rho$ is the cable density. When the density is constant, the function $y$ is well known, but when I add some concentrated weights $w$ somewhere, the shape changes, and I didn't know how to proceed. In this problem, I only know $y(a)$, $y(b)$, $\rho$ and $w$. Probably I will need a numerical solution once I don't know $z(x_0)$. I will work on it! Thank you!


Jest testing: How do I correctly write expect assertions witin a setTimeout?

Question: I want to JEST test a React Component which updates state after a timeout both before and after rendering state. The expect() assertion works fine in a test() but breaks when used inside a SetTimeout callback. An error states that expect is not defined within the setTimeout callback.
I have created a sandbox here:
https://codesandbox.io/s/jest-delayed-render-test-j5b7l
Simple component update state after SetTimeout.

// delayed.js
import { useEffect, useState } from "react";

export const Delayed = () => {
  let [value, setValue] = useState("foo");

  useEffect(() => {
    let handle = setTimeout(() => {
      setValue("bar");
    }, 3000);

    return () => {
      clearTimeout(handle);
    };
  }, []);

  return (
    <>

MyPromise

value = {value}

    </>
  );
};

Simple test asserts the component before and update timeout
// delayed.test.js

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import { Delayed } from "./delayed";

let container = null;
beforeEach(() => {
  container = document.createElement("div");
  document.body.appendChild(container);
});
afterEach(() => {
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

it("checks initial value", async () => {
  await act(async () => {
    render(<Delayed />, container);
  });
  expect(container.textContent).toContain("foo");
});

it("checks final value", async () => {
  await act(async () => {
    render(<Delayed />, container);
  });

  setTimeout(() => {
    // this doesnt get executed!
    // error: expect is not defined
    expect(container.textContent).toContain("1234");
  }, 2000);
});

Answer: this is easily fixed passing in done as a param on the test.
it("checks final value", async (done) => {
  await act(async () => {
    render(<Delayed />, container);
  });

  setTimeout(() => {
    expect(container.textContent).toContain("bar");
    done();
  }, 3000);
});

as described here:
https://www.pluralsight.com/guides/test-asynchronous-code-jest


A nice way to build a related content algorithm

Question: I am making a custom D7 module which has a block that lists related nodes of the current node you're viewing. The relation is determined by Taxonomy terms (from 1 vocab). The complication is that the related nodes need to be ordered by how many tags are matched in descending order.
How can you order nodes by matching tags? I have an idea of how to select nodes with matching tags, but have no clue as to how to order these by the number of matching tags. Any suggestions? Do it in SQL or in PHP?
Are there any modules that implement such functionality?
Simple case study for clarity
I have 2 content types: basic_page, article
Both of these content types have a same term reference field: field_tags
When someone opens a basic_page node that has been tagged with Tag A, Tag B and Tag C, I want to show article nodes that have been tagged with Tag A, Tag B and Tag C. But these article nodes need to be ordered by 'relevancy'. For example: the article nodes with all 3 tags matched must be at the top, and article nodes with 2 matching tags comes next, then the ones with 1 matching tag.
Comment: possible duplicate of [How to create a list of similar nodes in Drupal 7/Views 3](http://drupal.stackexchange.com/questions/27844/how-to-create-a-list-of-similar-nodes-in-drupal-7-views-3)
Comment: Maybe an average of levenshtein sums could fit? See [Levenshtein Wikipedia](http://en.wikipedia.org/wiki/Levenshtein_distance), and [Levenshtein PHP](http://php.net/manual/en/function.levenshtein.php).
Comment: @Letharion It's not a duplicate.
Comment: It's quite close :) The answer on that question, particularly the module there has helped me come up with a solution. Thanks @Letharion
Comment: @kiamlaluno I defer to your judgement, but I don't see why? If it's because the other question has "Views" in the title, then wouldn't it make more sense to just remove that?
Comment: @Letharion The other question is asking how to achieve something with Views, while this question is asking how to achieve something using a custom module. A question is about how to use a module to achieve something; the other question is about code to write.
Answer: This was what I ended up writing to select nodes:
$query = db_select('node', 'n');
$query->addField('n', 'nid');
$query->addExpression('COUNT(n.nid)', 'ncount');
$query->innerJoin('taxonomy_index', 'ti', 'n.nid = ti.nid');
$query->condition('ti.tid', $tids, 'IN');
$query->condition('n.type', $types, 'IN');
$query->condition('n.nid', $node->nid, '<>'); // Exclude current node
$query->condition('n.status', 1); // Published
$query->condition(
  db_or()->condition('n.language', 'und')
         ->condition('n.language', $node->language)
);
$query->groupBy('n.nid');
$query->groupBy('n.title');
$query->groupBy('n.created');
$query->orderBy('ncount', 'DESC');
$query->range(0, 10);

$results = $query->execute();

Kudos to Similar by Terms module, as I copied most of it from there. The magic happens when you order by ncount field.


What are the potential functions of the cliques in Markov random field?

Question: I have been trying to understand the representation of the joint probability density of Markov random fields in the form of factors of the potential functions. I am finding it difficult to grasp the idea of potential functions and how we are supposed to choose a potential function. Any suggestions on how I should get started. I have gone through the wiki page and some other resources, but still I couldn't grasp the essence of it.
Answer: All potential functions can be written in a log-linear form as described in the Wikipedia article.  This however may not be that useful, as it requires you to specify a weight for all possible configurations of your clique.
Your choice of potential function depends on the properties of the variables you are modelling. For example, if you are implementing a Kalman filter (which is an autoregressor for continuous variables assuming Gaussian noise), your potential functions are Gaussian.  For binary variables ($x_1$, and $x_2$) that should approximate an XOR relationship you could specify the following potential function:
$$1/Z \cdot \exp(a + b \cdot x_1 + b \cdot x_2 + c \cdot x_1 \cdot x_2)$$
where a and b are positive and c is negative.
For a very good introduction to probabilistic models I'd recommend Mike Jordan's technical report / book Graphical Models, Exponential Families and Variational Inference or consider taking a look at Chris Bishop's book.


Prove the identity: $\frac {1} {1+x^2} = \sum^{n-1}_{j=0} (-1)^j x^{2j} + (-1)^n \frac {x^{2n}} {1+x^2}, x\in \mathbb R, n \in \mathbb N$

Question: I want to prove that $$\frac {1} {1+x^2} = \sum^{n-1}_{j=0} (-1)^j x^{2j} + (-1)^n \frac {x^{2n}} {1+x^2} = 1-x^2 +x^4 -x^6 +...+(-1)^{n-1}x^{2n-2}+(-1)^n \frac {x^{2n}} {1+x^2},  x\in \mathbb R, n \in \mathbb N$$.
That is, the identity in question holds for $n \in \mathbb N$ and $x \in \mathbb R$.
How can I prove this ? I cannot use induction since every time I change $n$ the sum changes ? I'm quite confused on how to proceed.
Comment: What convergens do you want to prove? You just have a geomeric sum. $a+aq+\ldots+aq^{n-1} = a\frac{1-q^n}{1-q}$
Answer: $1-x^2+(x^2)^2+\ldots+(-x^2)^{n-1}=\frac{1-(-x^2)^n}{1-(-x^2)}=\frac{1+(-1)^{n+1}x^{2n}}{1+x^2}$
Comment: what rule are you using here ?
Comment: The rule is written above in my comment.
Comment: But $\frac 1 {1+x^2} \neq \frac{1+(-1)^{n+1}x^{2n}}{1+x^2}$ ??
Comment: $\frac{1}{1+x^2}=\frac{1}{1+x^2}+\frac{(-1)^{n+1}x^{2n}}{1+x^2}+(-1)^n\frac{x^{2n}}{1+x^2}$ exactly  what you want to prove.
Comment: Thank you, by the way, how is the last equality in the identity I want to prove proved ? Is it trivial that the sum equal the sum of the right side ?
Comment: It is the same identity written in an expanded form
Comment: I see that now - I interpreted it as $(-1)^n \frac {x^{2n}} {1+x^2}$ was part of the summation. There should be parentheses to avoid this ambiguity. In summation, is it always only the first term that is part of the summation ($\sum$) ?


Parse this Json to NSmutablearray

Question: i've this unique text plain
{"id":"AALI.NG","data":["AALI","NG",19312,0,0,0,0,0,0,0,0,0,0,0,70,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}
{"id":"AALI.RG","data":["AALI","RG",19500,0,0,0,0,0,0,0,0,0,0,0,26,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}
{"id":"AALI.TN","data":["AALI","TN",19500,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}
{"id":"ABBA.NG","data":["ABBA","NG",60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}
{"id":"ABBA.RG","data":["ABBA","RG",85,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}
{"id":"ABBA.TN","data":["ABBA","TN",85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}
{"id":"ABDA.NG","data":["ABDA","NG",3500,0,0,0,0,0,0,0,0,0,0,0,6000,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}

then i change it to :
 {"stockQuote":[{"id":"AALI.NG","data":["AALI","NG",19312,0,0,0,0,0,0,0,0,0,0,0,70,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"},
{"id":"AALI.RG","data":["AALI","RG",19500,0,0,0,0,0,0,0,0,0,0,0,26,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"},
{"id":"AALI.TN","data":["AALI","TN",19500,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"},
{"id":"ABBA.NG","data":["ABBA","NG",60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"},
{"id":"ABBA.RG","data":["ABBA","RG",85,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"},
{"id":"ABBA.TN","data":["ABBA","TN",85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"},
{"id":"ABDA.NG","data":["ABDA","NG",3500,0,0,0,0,0,0,0,0,0,0,0,6000,0,0,0,0,0,0,0,0,0,0,0,0],"req":"SQ"}]}

basicly type  of data i get from server is text/plain  and i need to add {"stockQuote":[,  "," and also }]} to make it like json...
the question is, how to parse it to json an NSMutableArray then i draw it to UITableView, how to do it?? should i change it to NSDictionary first and  then insert it to NSMutableArray?
Comment: you fix your problem?
Comment: almost.. let me try the code :)
Answer: Your second JSON is just an NSDictionary with a single object that is an NSArray.  So just take your normal array that you have in the first JSON, and do this:
NSArray *jsonArray = [jsonDic objectForKey:@"stockQuote"];

where jsonDic is your json's parse object with NSJSONSerialization method.

Parse this Json to NSmutablearray


ZFS: SAS v SATA - does it matter?

Question: I understand from NEC's white paper, Silent data corruption in disk arrays, that:

some SAS drives should have a "T10-DIF" feature to detect silent data corruption; whereas
"There is no standard for ATA-based drives (including SATA) that protects against silent data corruption at the SCSI level in the storage technology stack."

The point of that white paper is to inform people of NEC's proprietary technology for protecting against silent data corruption in SATA drives. However, ZFS seems to provide at least equivalent protection, and is preferable to me as it is not proprietary (except for Oracle's most recent ZFS revisions).
I have two questions:

Am I right in thinking that using ZFS with T10-DIF SAS drives would give an additional layer of protection against silent data corruption as compared to using just one of those two technologies alone?
Given that T10-DIF SAS drives do not seem to be readily available, what reasons are there - if any - to prefer non-T10-DIF SAS drives over equivalent* SATA drives, or vice versa?

* By this, I mean comparing like with like: e.g. enterprise class SAS drives from a given manufacturer vs enterprise class SATA drives from the same manufacturer.
Comment: Having the array manager check the disks for corruption on a regular basis is a tried and true method of preventing/detecting silent data corruption. ZFS and many other managers call it "Scrubbing". It should be done regularly, and results reported if abnormal (most frequently for critical data, but at least monthly as a dead minimum). Great little writeup on what's going on: [how multi-disk failures happen](http://sysadmin1138.net/mt/blog/2012/12/how-multi-disk-failures-happen.shtml).
Answer: If you can avoid SATA disks, please do so. Nearline SAS is a good compromise for people using ZFS who want stability, performance and capacity. You don't need proprietary silent data corruption technologies from the disk manufacturers...
The arguments against SATA really come down to the implementation and choice of storage hardware, controllers, enclosure, etc. It's much easier to go wrong or to find a particularly toxic combination when SATA is in the mix; e.g. behind an expander, using bad controllers and in various failure modes.
See: How can a single disk in a hardware SATA RAID-10 array bring the entire array to a screeching halt?

ZFS: SAS v SATA - does it matter?


Reducing 12 modulo 9

Question: This example is from a text on Modular Arithmetic

We want to reduce 12 modulo 9. Here are several results which are
correct according to the definition:
1) 12 ≡ 3 mod 9,     3 is a valid remainder since 9|(12−3)
2) 12 ≡ 21 mod 9,    21 is a valid remainder since 9|(21−3)
3) 12 ≡ −6 mod 9,    −6 is a valid remainder since 9|(−6−3)

I understand the first one.
For a ≡ r mod m, we can write m | (a - r)
So in the first example, a = 12 r = 3 m = 9.
So from that we get 9 | (12 - 3)
But for the second, a similar substitution would be
9 | (12 - 21) - But in the example, they have (21 - 3) instead of (12 - 21)
Likewise in the $3^{rd}$, they have (-6 -3) instead of (12 + 6)
How do they arrive at this in the $2^{nd}$ & $3^{rd}$ example?
Comment: That seems like sloppy editing. They probably had $3\equiv12$, $3\equiv21$ and $3\equiv-6$ as the modular equations at first, but then swapped the 3 and 12 in order to talk about reduction rather than equivalence (which seems a bad idea to me), but then forgot to update the second parts. Note however that since it is an equivalence relation it still is true: if $p|(a-b)$ and $p|(b-c)$ then $p|(a-c)$ because $(a-c)=(a-b)+(b-c)$
Comment: They are using example 1.
Comment: @QiZhu `That are using example 1` - what are using example 1?
Comment: Sorry, I typo'd, I meant to say "They".
Comment: @JaapScherphuis - I don't understand - can you please elaborate? This is from the book "Understanding Cryptography" by Christof Paar
Comment: @QiZhu - I still don't get what you are saying
Comment: Mod ( n)  is an equivalence relation. So you can use transitivity and symmetry
Comment: @JaapScherphuis - I think you are correct. The author is trying to find the equivalence class rather than do reduction.
Answer: If $a \equiv b \pmod m$ and $b \equiv c \pmod m$, then $a \equiv c \pmod m$. This is called transitivity and you should prove that it is true.
For your second example: The author in your text uses $12 \equiv 3 \pmod 9$ and $3 \equiv 21 \pmod 9$, so $$ 12 \equiv 3 \equiv 21 \pmod 9.$$ Of course, you can also just check $9 \mid 12 - 21$, as you said.
Comment: `For your second example: The author in your text uses 12≡3(mod9) and 3≡21(mod9),` - where did the 3≡21(mod9) come from? I know his end conclusion is correct but where did he get 3≡21(mod9) from?
Comment: I am a total beginner at Modular arithmetic - this is almost the first couple of pages I am reading - so nothing he has explained till now tells me how he came upon `3≡21(mod9)`
Comment: It comes from $9 \mid (21-3)$ as you have quoted in your second example. It just means that they leave the same remainder upon division by $9$.
Comment: Ok, got it. They should have written `9 | (21 - 3)` in the first half of the line & `12 ≡ 21 mod 9` in the 2nd half of the line. Writing it in the way they did, made me believe that the 2nd half comes from the first half. So what you are saying is that they found `( a - b )'s` which are divisible by 9 & then got the first half from that
Answer: I am answering my own question. I think the author is trying to find all answers which form an equivalence class for mod 9.
3, 21 & -6 are all part of the equivalence class for mod 9.
{ ...-15, -6, 3, 12, 21, ... } is one of the 9 equivalence classes for mod 9.
That's how he gets to (2) & (3) from (1)

Reducing 12 modulo 9


Adjust jQuery datepicker selected date

Question: I need to adjust a date selected in jQuery's datepicker. For example, whatever user chooses, change to closest weekend.
Is there a way to do this? Some validation / filtering support. Or maybe it can be done with a help from some other validation library that will track text in the text box, not the datepicker value?
Answer: What you can do is subscribe to the select event and change the date:
$('.selector').datepicker({
    onSelect: function(dateText, inst) {
        var date = $(inst).datepicker('getDate'); // Date should be a Date object
        // do some calculation and set the date via:
        $(inst).datepicker('setDate', date);
    }
});

Note: not tested.

Adjust jQuery datepicker selected date


Passar variável do PHP para o Python com mais de 14 caracteres

Question: Problema ao passar variável Python para PHP com mais de 14 caracteres
Código PHP
 $p = 123456789101112
 $pyscript = 'C:\\Users\\python\\teste.py';
 $python = 'C:\\Python34\\python.exe';
 $run = shell_exec("$python $pyscript $p");

Código Python
import sys
print(sys.argv[1])

Se $p conter até 14 caracteres, ex: $p = 1234567891011, o Python imprime: 1234567891011
Porém se existir mais de 14, ex: $p = 12345678910111213, o Python imprime: 1.2345678910111E+16
Como vou recuperar o valor exato da variável quando excede 14 caracteres?
Comment: O estranho é que o argumento passado via *shell* será *string*, não um inteiro. Eu executei o código aqui e não tive o problema citado na pergunta. O código é só esse mesmo ou ocultou partes dele?
Comment: @Anderson Carlos Woss, você tentou simular com um número maior ou igual a 12345678910111213, pois pode ser uma questão de versão do Python
Comment: @Bacco, estou utilizando o PHP 7.0.4 x86
Answer: Você está esbarrando num problema de precisão numérica.
O PHP tem como máximo inteiro em 32 bits o valor 2147483647, em 64 bits o valor 9223372036854775807 e acima disto terá um float, com possível perda de precisão (vide links ao final da resposta para mais detalhes).
Ocorre que, mesmo que o float possa exibir um número razoável de casas, há uma configuração para exibição destas, que por padrão é 14. Uma vez ultrapassado este comprimento, a exibição será "abreviada".
Mais especificamente, a diretiva é esta:
Arquivo php.ini
precision 14

Link para o manual:

Diretiva precision

Usando strings:
Uma solução possível é usar uma string em vez de número. Passando o valor como string a saída é textual, será desconsiderado o armazenamento numérico:
 $p = '123456789111315171921'; // note as aspas aqui
 $pyscript = 'C:\\Users\\python\\teste.py';
 $python = 'C:\\Python34\\python.exe';
 $run = shell_exec("$python $pyscript $p");

Se precisar realmente trabalhar com números grandes, o PHP tem funções específicas para tal, nas biblioteca BCMATH e GMP (vide links abaixo).
Links relevantes:

Como obter o maior valor numérico suportado pelo php?

Qual é o máximo de casas decimais permitidas no float em PHP?

Precisão arbitrária no PHP com BCMATH

Precisão arbitrária no PHP com GMP
Comment: Perfeito, resolveu o problema, obrigado!


Access field of a generic type in function

Question: I have spent the last 4 days trying to figure this one out and I'm really really stuck. Basically I have a large number of similar structs, all containing one particular field. let's call it data of type u32:
struct A {
    data: u32,
}

struct B {
    data: u32
}

...

struct N {
    data: u32
}

What I need to do is write a function outside those structs, which takes a generic type (that is, either one of those structs) perform some manipulation on the field and return the value. Basically something along the lines of:
fn some_manipulation<T>(st: &T) -> u32 {
    st.data * 10
}

Which, as it stands, is not possible because there is no data field on type T. Another thing is I cannot modify the structs. Is there a sensible way to achieve this?
Comment: You could use a trait for abstracting the access to the attribute plus a macro for implementing such trait for the types maybe.
Also, are the struct attributes private?
Answer: So exactly as @Netwave pointed out, to make it work you need a trait that some_manipulation would use to access the data field, but to implement this trait for all the types you can use a custom macro.
Playground
I defined my macro to look like this impl_BorrowData!{u32, [A, B, N]} (where first argument is type of data field and then a list of structs follows, but macros are flexible enough and you can make it look as you wish.
trait BorrowData {
    type Output;
    fn borrow_data(&self) -> &Self::Output;
}

macro_rules! impl_BorrowData {
    ($out:ty, [$($t:ty),+]) => {
        $(impl BorrowData for $t {
            type Output = $out;
            fn borrow_data(&self) -> &Self::Output {
                &self.data
            }
        })*
    }
}

impl_BorrowData!{u32, [A, B, N]} // first the output type <u32>, then names of structs

fn some_manipulation<T: BorrowData<Output=u32>>(st: &T) -> u32 {
    st.borrow_data() * 10
}

fn main() {
    let a = A { data: 2 };
    println!("{}", some_manipulation(&a));
    let b = B { data: 50 };
    println!("{}", some_manipulation(&b));
}

Answer: The other answers explain how to use a trait to abstract over different types, and how to use macros to automate the process for fields of the same name in different types. There are two possible improvements (or, one addition and one improvement):

If there is only one data field that you need to borrow, you don't need to define a custom trait, you can use the AsRef trait from the standard library, and just implement it for your types.

To mutate the structs, which your question also asks about, your function must accept &mut T and your trait must return &mut u32. Because of the latter you cannot reuse the access trait for mutation, you have to have two traits, or always have the possibility of mutation. The standard library provides the AsMut trait as the mutating equivalent of AsRef.

Using the standard traits and allowing for mutation, the code would look like this (playground):
impl AsRef<u32> for A {
    fn as_ref(&self) -> &u32 {
        &self.data
    }
}

impl AsMut<u32> for A {
    fn as_mut(&mut self) -> &mut u32 {
        &mut self.data
    }
}

// and the same for B, or use a macro
...

fn some_manipulation<T: AsRef<u32>>(st: &T) -> u32 {
    *st.as_ref() * 10
}

fn mutating_manipulation<T: AsMut<u32>>(st: &mut T) {
    *st.as_mut() *= 10;
}

Answer: Rust generics are based around traits and trait bounds: a generic function can only access the features guaranteed by trait bounds. This is very much unlike e.g. C++ templates.
Here T has no bounds, so it can be (almost) anything and thus there is essentially no universally applicable operation (to say nothing of field access which is simply not an option in generic code, as fields are not a concept of traits).
There are two ways to perform this operation:

if you really want to use a generic function, you need to define a trait defining the relevant operation and implement that trait for every structure, using a declarative macro is a common way to make "bulk" definition of trait impls less annoying

alternatively, you could probably use a macro instead of a function, macros are more structural and will just fail to compile after macro expansion, though there are limit to what "declarative" macros can do, and "procedural" macros are not trivial


Particle motion and frenet frame

Question: I am given that $\hat{t}=\dfrac{\hat{x}+y'\hat{y}}{\sqrt{1+y'^2}}$ and $\hat{n}=\dfrac{y'\hat{x}-\hat{y}}{\sqrt{1+y'^2}}$ are the tangential and normal vector in frenet frame. We are considering only 2 dimensional case, where a particle moves along a curve.
Then the author state a equation (second law of motion)
${\vec{F}}=mv\left(\dfrac{dv}{ds}\hat{t}+v\dfrac{d\hat{t}}{ds}\right)=mv\dfrac{dv}{ds}\hat{t}+mv^2\kappa \hat{n}$, which i am able to understand how it comes.
However afterwards, the author defines (Kinetic energy) $K=\frac12mv^2(x,y)$ and claims that $\vec{F}=\nabla K$ I am not able to arrive at the normal $\hat{n}$ component of the result. Can anyone help me and also is there a gradient operator in terms of frenet frame?
Answer: Just simplify,
\begin{align*}
  dW &= \mathbf{F} \cdot d\mathbf{r} \\
     &= \mathbf{F} \cdot \mathbf{T} \, ds \\\
     &= mv \, dv
\end{align*}
Comment: Sorry, I am kinda not able to understand how to utilize that.
Comment: Do you know $\mathbf{F}=-\nabla U=\nabla K \iff \Delta K=\int_{C} \mathbf{F} \cdot d\mathbf{r}$?
Comment: Oh sorry, I know that but I actually wanted to take gradient of $\frac12 mv^2$ to arrive at the result $mv\dfrac{dv}{ds}\hat{t}+mv^2\kappa \hat{n}$
Comment: That's rather strange, we usually using $\mathbf{F}=-\nabla U(x,y)$ and $\displaystyle \mathbf{v}=\frac{\partial K}{\partial \mathbf{p}}$
Comment: http://academics.smcvt.edu/abrizard/Classical_Mechanics/Notes_070707.pdf

Page 32 and 33
Comment: After looking the whole paragraph, I think the line in equation (2.4) is component extraction rather than logical derivation.  $\mathbf{F}=\nabla K=\mathbf{T} (\mathbf{T} \cdot \nabla K)+\mathbf{N} (\mathbf{N} \cdot \nabla K)$ so $mv^2 \kappa=\mathbf{F} \cdot \mathbf{N}$
Comment: Yes i am kinda confused with that, I just don't get how did he claim $F=\nabla K$ rest i kind of understood.
Comment: Note that $mv^2 \kappa$ is simply the centripetal force.

Particle motion and frenet frame


Custom notification: java.lang.RuntimeException: ..crash on notification

Question: I am trying to make a custom notification reminder, but there is a crash after this exception in the code.
10-11 11:13:01.445  2816  4383 E JavaBinder: *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
10-11 11:13:01.445  2816  4383 E JavaBinder: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
10-11 11:13:01.445  2816  4383 E JavaBinder:    at android.os.Handler.<init>(Handler.java:197)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at android.os.Handler.<init>(Handler.java:111)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at com.android.server.NotificationManagerService$9.<init>(NotificationManagerService.java:2800)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at com.android.server.NotificationManagerService.sendMsg(NotificationManagerService.java:2800)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at com.android.server.NotificationManagerService.updateSoundLocked(NotificationManagerService.java:2787)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at com.android.server.NotificationManagerService.enqueueNotificationInternal(NotificationManagerService.java:2055)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at com.android.server.NotificationManagerService.enqueueNotificationWithTag(NotificationManagerService.java:1911)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at android.app.INotificationManager$Stub.onTransact(INotificationManager.java:103)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at android.os.Binder.execTransact(Binder.java:388)
10-11 11:13:01.445  2816  4383 E JavaBinder:    at dalvik.system.NativeStart.run(Native Method)
10-11 11:13:01.445  8979  8979 D AndroidRuntime: Shutting down VM
10-11 11:13:01.445  8979  8979 W dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41786700)
10-11 11:13:01.445  2357  2631 E AudioResampler: Unsupported sample format, 1 bits, 2 channels
10-11 11:13:01.445  8979  8979 E AndroidRuntime: FATAL EXCEPTION: main
10-11 11:13:01.445  8979  8979 E AndroidRuntime: java.lang.RuntimeException: bad array lengths
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.os.Parcel.readIntArray(Parcel.java:789)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:339)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.app.NotificationManager.notify(NotificationManager.java:139)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.app.NotificationManager.notify(NotificationManager.java:112)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at com.android.systemui.screenshot.SaveImageInBackgroundTask.onPostExecute(GlobalScreenshot.java:380)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at com.android.systemui.screenshot.SaveImageInBackgroundTask.onPostExecute(GlobalScreenshot.java:126)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.os.AsyncTask.finish(AsyncTask.java:631)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:137)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:5419)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at java.lang.reflect.Method.invokeNative(Native Method)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Method.java:525)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
10-11 11:13:01.445  8979  8979 E AndroidRuntime:    at dalvik.system.NativeStart.main(Native Method)

My code snippet where I am having problem is:
private void sendMsg(boolean delayed) {
    if(mNotificationSoundHandler == null) {
        mNotificationSoundHandler = new Handler() { //may be some prob with this

            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.d(TAG, " !!!Handle Message !!!");
                updateSoundLocked();
            }

    };
}

Comment: Fix the format of your logCat
Comment: sry for the inconvenience..
Answer: You cannot update your UI outside the UI Thread. You should do something like this:
getActivity().runOnUiThread(new Runnable() {
    updateSoundLocked();
});

Or even:
private void sendMsg(boolean delayed) {
    if(mNotificationSoundHandler == null) {
        mNotificationSoundHandler = new Handler(Looper.getMainLooper()) {

            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.d(TAG, " !!!Handle Message !!!");
                updateSoundLocked();
            }
        };
    }
}

Please, refer to the official documentation for more details.
Comment: Thanks a lot .. the later solution worked for me.. It took the hell out of me .. was working on it since 5 days.. thanks a lot...
Comment: Glad to hear that. Please, don't forget to check the answer as accepted. Thanks.


Sincronizar Banco de dados Local e Web

Question: Tenho um sistema rodando em um servidor web, e também quero colocá-lo pra rodar no servidor local da empresa (intranet), por questões de desempenho...
Percebi que teria um problema com relação à sincronização do banco de dados entre os dois servidores... Pesquisei alguma coisa sobre Replication, mas nada muito esclarecedor...
Gostaria de saber como eu posso fazer essa sincronização instantaneamente - Tudo que for gravado no servidor local, também estar disponível no web, e vice-versa?
Dá pra alguma ferramenta do próprio servidor pra isso?
Preciso nem que saiba de uma função pra quando o cara clicar em um botão, automaticamente transferir os dados do servidor local pro web, e vice-versa.
Alguém poderia me dar um HELP?
Desde já agradeço!
Answer: Caro, de fato a maneira mais segura de fazer isso é através do Replication. Porém este recurso é para replicação ativa-passiva assíncrona, é mais comumente utilizado para fins de backup e/ou redundância de dados.
Se você precisa de uma replicação ativa-ativa, o único modo seguro que vejo é através do Mysql Cluster:
https://www.mysql.com/products/cluster/ porém esta não é uma solução free e acredito que não seja barata. De qualquer forma a performance de um cluster depende também da qualidade da rede (e no final das contas terá um único ip).
Você poderia explorar outras alternativas (cache local ou remoto ex CloudFront na AWS) ou apenas subir a aplicação na rede local e apontar para o banco remoto.
Também dê uma olhada nesta resposta: Como fazer backup do banco de dados para nuvem e como ter os dados sincronizados em vários dispositivos?
Espero ter ajudado de alguma forma.
abs,

Sincronizar Banco de dados Local e Web


What is the difference between [ ] and [[ ]] in R?

Question: <code>  > levels(state.region)[2]
    [1] "S"
    > levels(state.region)[[2]]
    [1] "S"
</code>
They return the same value, so I don't know what is the difference between them.
Answer: [] = always returns object of same class (out of basic object classes), can select more than one element of an object
[[]] = can extract one element from list or data frame, returned object (out of basic object classes) not necessarily list/dataframe
Comment: `[[` can extract from more that just a list or data.frame. It also works with vectors, matrices, environments, etc.
Comment: very late here... but what use is `[[` when applied to a vector or matrix?  I can't think of any examples where it differs from `[` (just like the OP's question demonstrates).


Rails associating multiple :has_many

Question: I'm new to Rails and trying to understand associating entities.
I have three entities right now: Users, Companies, and Productlines.
company.rb:
class Company < ActiveRecord::Base
    has_many :users
    has_many :productlines
end

user.rb:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :company
end

productline.rb:
class Productline < ActiveRecord::Base
    belongs_to :company
end

I've done the migration scrips to associate them, however when I click into a Company on Rails Admin, I'm getting this:
SQLite3::SQLException: no such column: productlines.company_id: SELECT "productlines".* FROM "productlines" WHERE "productlines"."company_id" = ?
Extracted source (around line #91):
#
def prepare sql
  stmt = SQLite3::Statement.new( self, sql )
  return stmt unless block_given?
begin
Edit: Here is my migration:
class AddProductlineIdToCompanies < ActiveRecord::Migration
  def change
    add_column :companies, :productline_id, :integer
    add_index :companies, :productline_id
  end
end

Comment: post your migrations.... the `company_id` is missing in the `productlines` table
Comment: Just edited my question
Comment: Did you remember to run `rake db:migrate` after adding that migration?
Answer: You should add the company_id to productlines and not product_line_id to companies...
class AddCompanyIdToProductlines < ActiveRecord::Migration
  def change
    add_column :productlines, :company_id, :integer
  end
end

Comment: Do I need to rollback the previous migration?
Comment: yep: `rake db:rollback`

Rails associating multiple :has_many


ROC-style curves for calculating sample size, power, alpha, and effect size

Question: I found an awesome R package called pwr that does all sorts of calculations about sample sizes, power, effect sizes, and so on, and I've been playing.
I have a number of tests that I've run. Now I want to know what kind of power to reject I can get. That's an easy calculation in pwr. However, if it comes up that I only get $77\%$ when I wanted $80\%$, perhaps I can get $80\%$ power with a minor adjustment to alpha up to $0.06$ instead of the usual $0.05$.
Or maybe I've determined that I want a certain level of power, but I can show that, perhaps I could only get $77\%$ power to reject if I have an effect size of $\delta$, but for some tiny (acceptable) $\epsilon$, I get $80\%$ power with an effect size of $\delta - \epsilon$.
Or maybe I want to play games with the sample size. Perhaps it takes 101 observations to get power up to $80\%$, but if I require $80\%$ power and play games with the sample size to compare with alpha, then for the 100 experiments that I am willing to run, I get $79\%$ power that I consider good enough.
I have a function that plots curves comparing what happens at all of these values: at $\alpha=0.05$, power is $80\%$, at $\alpha=0.06$, power is $82\%$, etc, and ditto for the other pairings (e.g. sample size vs effect size).
I have reservations about doing this, since it feels like p-hacking. At the same time, it feels an awful lot like machine learning using an ROC curve to inform the cutoff threshold for classification.
Is this a legitimate approach? I would (probably) be doing this before I've seen or perhaps even collected the data.
Answer: A classic way to proceed is to determine the difference that you wish to be able to detect at a given combination of Type I error and Type II error, and then design a study with a large enough sample size to meet your requirements, given the variability you expect in your measurements.
All of the "playing" you are doing is legitimate in some sense. In particular, "playing games" with sample size is the classic application of power calculations for study design. You should nevertheless be aware of the following.
First, the standard frequentist requirement for "statistical significance" is p < 0.05, so if you plan on publishing the results of your study it would be wise to stick with $\alpha = 0.05$.
Second, the power represents your willingness to miss a truly "significant" (in the sense noted above) result. If you are willing to risk a 21% or 23% chance of such a miss then you can go ahead with 79% or 77% power. A funding agency or a supervisor, however, might not be willing to go so low. 80% power is commonly used; you might want to go even higher.
Third, what is most important (if perhaps most difficult) is having a good handle on the difference you would like to detect and the variability in the measurements. If you have made an unreasonable choice for the difference you're trying to detect, then no playing with power calculations will help. If you don't have a reliable estimate of measurement variability, the power calculations will be correspondingly unreliable. Focus on those matters.


How does term association work in text mining

Question: Before performing word association, we create a term document matrix after removing punctuations, capitals, etc. How does the association algorithm work? Since we have removed the markers to identify sentences and breaks, how would we identify if two words are appearing in the same sentence? Or does the algorithm only capture words appearing next to each other? In that case, isn't there the possibility of two words of different sentences appearing next to each other?
Answer: Text mining is a very wide field of research. Many approaches exist, using different kind of analysis. Then your question might be unclear since you don't give any detail. I will try to give you an overview.
You're right when you say that we usually preprocess the texts at first. This is based on assumptions: is the punctuation meaningful ? you I split words connected by a dash sigh ? by an underscore ? Should I cut sentences ? Should I use n-grams ? These are your choices.
You talk about term document matrix. We usually use TF-IDF to compute the words importance in the corpus of documents. After this step, you have a matrix where each row is a document, each column is a word. The elements of the matrix represent the importance of the corresponding words in the particular document.
Then several methods exist to capture the proximity of two words. One is called Latent Semantic Analysis. The idea is to decompose the previous matrix with the singular value decomposition (SVD). You get a matrix of lower dimension in which we can consider similar vectors (using cosine similarity for example) representing similar documents.
This similarity could be computed in the the original space (our first matrix). But the SVD compressed the information in a way that words description overlap on the reduced dimensions, such that similar words have similar vectors. Finally, when you compare two vectors in the TF-IDF space you get no similarity:
v1 = [0,0,0,0.48,0,0,0,0,0,0,0,0,0,0,0]
v2 = [0,0,0,0,0,0,0,0,0,0,0.34,0,0,0,0]
cosine(v1,v2) = 0

Whereas if you look at their compressed version, you can get their similarity:
v1 = [0.12,0.24,0.64]
v2 = [0.10,0.30,0.60]
cosine(v1,v2) = 0.468

To answer your question: the relative position of the two words doesn't affect word association. Actually, two words can be very close and never appear in the same document. But if their context (the others words in the documents) are similar, they will be close in the reduced space. Please read this article if you want to know more.
At the end, if you want to capture sequences of words, you'd better look at recurrent or convolutional neural networks for text mining or Markov processes that attempt to learn the underlying generative process to build sentences. In both technique, I don't see why term document matrix would be useful since it doesn't capture sequences of words.


Find marginal distribution

Question: The random vector $(X,Y)$ is uniformly distributed over $$D=\{(x,y): 0 \leq x \leq 2 , 0 \leq y \leq 2-x\}.$$ Find the marginal distribution of the random variables $X$ and $Y$.
For the radom vector $(X,Y)$ we have $$f_{(X,Y)}(x,y)=\frac{1}{2}$$ for $(x,y) \in K$ and $$f_{(X,Y)}(x,y)=0$$ otherwise. Then,
$f_X(x)=\int_{0}^{2-x}\frac{1}{2}dy=1-\frac{1}{2}x$ for $x \in [0,2]$ and $f_X(x)=0$ otherwise.
$f_Y(y)=\int_{0}^{y+2}\frac{1}{2}dx=1+\frac{1}{2}y$ for $y \in [0,2]$ and $f_Y(y)=0$ otherwise.
I kindly ask for confirmation if my solution is correct.
Comment: One easy check is to integrate the answers to confirm they are both $1.$  (They are not.)  I warmly recommend drawing pictures of this setting and the operations you are performing.
Comment: Thank you. Could you please tell me where I am doing wrong? Is the pdf of $(X,Y)$ correct?
Comment: Drawing the picture will make the problem obvious.
Answer: In deriving the marginal distribution of y, x should go from 0 to 2-y.
Comment: Of course... Now everything is clear. I did not notice that I had incorrectly rewritten the boundary of the integral. Thank you very much!
Comment: Np. Sometimes it can be tricky to "debug" your own work :)

Find marginal distribution


error 7-zip running on Powershell script

Question: I am writing a powershell script to generate backup using the 7-zip, but something is not working. When I run the code below
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
$BACKUP_DATE = Get-Date -UFormat "%Y-%m-%d"
$LOCAL_BKP = 'E:\_Bkp_Producao'

New-PSDrive –Name "s" –PSProvider FileSystem –Root "\\server\myfolder"
sz a $LOCAL_BKP\bkp_siemens_$BACKUP_DATE.7z S:\*

return the following messages:
7-Zip [64] 9.38 beta  Copyright (c) 1999-2014 Igor Pavlov  2015-01-03
Scanning
S:\:  WARNING: The system cannot find the path specified.
Creating archive E:\_Bkp_Producao\bkp_siemens_2015-08-31.7z
WARNINGS for files:
S:\ : The system cannot find the path specified.

What's wrong?
Comment: Did you remember to create the `$LOCAL_BKP` folder?
Comment: yes, he already existed (again, the 7z file was created at that location). Thank you.
Comment: Try adding `-Persist` to the `New-PSDrive` command.
Comment: It worked! As my script creates and deletes mapping at the end, I didn't think I would need to use the -Persist. Thank you! Please enter an answer, so I can vote.
Answer: -- Old & Busted Answer --
I know this is really a duplicate of powershell string interpolation, but I can't find that one right now.
Alternatives that work:
$sz = "${env:ProgramFiles}\7-Zip\7z.exe"
$sz = $env:ProgramFiles + "\7-Zip\7z.exe"
$sz = '{0}\7-Zip\7z.exe' -f $env:ProgramFiles

You could also try using Join-Path, but I find it troublesome.
-- New Hotness --
You need to add the -Persist option to New-PSDrive. If you don't use -Persist, the "drive" is only visible to powershell cmdlets. Adding it makes the "drive" available to all commands, including native windows command line applications.
Comment: Thanks for your reply, but the problem is not the 7-zip (see that it returns the installed version and also creates the 7z file), but to see the sharing.
Comment: You should click the checkmark icon to Accept the answer. Voting doesn't mark it as the accepted answer.


App returns null value for device token from app store

Question: I have released my app update with push notifications however when I check my server, I notice that the token that was sent to the database is "null". I did lots of testing using a development certificate AND a production certificates for ad hoc. Both worked succesfully but the version on the app store does not and I have no idea why. I posted about this issue about 2 weeks ago and someone told me I should not use the provisioning profile I used for ad hoc so I created a new provisioning profile with the same id. Update got releases yesterday and I still have the same problem. I need to find a permanent solution since my users are getting annoyed with all these updates but I don't know how to test until it gets approved on the app store.
If anyone can please offer thoughts or assistance I would really appreciate it. Thanks in advance.
P.S. if it helps, I deleted my app from my device and installed it again from the app store... It did not ask me if I wanted to receive push notifications but push is enabled for the app from the phone settings...
Comment: @StevenKramer Way to much code. If it worked for ad hoc, why didn't it work for app store? I feel no code would be necessary?
Comment: Well, yes, but there's a bug here. Either in your code or in the system frameworks. The documentation says "Sent to the delegate when the application successfully registers with Apple Push Service (APS)." That whole process depends on a valid device token being exchanged between APNS and the OS.
Comment: I think you need to re-generate your p12 file after you enable the push notification for production in the apple developer portal.
Answer: There are 3 steps in an APNs communication:

Your app registers to receive APNs in your appDelegate within your iOS. This will give you a deviceToken that you should use to send notifications.
Your app sends the deviceToken to your management server
Your management server connects with Apple APNs server to send the Push Notification

In your case, I understand that your problem is in step 1 because you said that you are having a null device id and the app is not asking you about the APNs permission. Therefore, changing your server certificate or switching from gateway.sandbox.push.apple.com to gateway.push.apple.com is not going to help because the error happens before.
This is clearly a problem with your certificates. You should check that you have done all the required steps in your Apple iOS Provisioning Portal:

Create an AppId with the bundle identifier of your app. Avoid wildcars such as *.
Configure your InAppPurchase options for your app (this is not the problem because is used for step 3 in the communication)
Create a provisioning profile for Distribution which uses the AppId used in 1. (I suspect that this could be your problem), and download it
Open XCode project settings and check that your archiving operation uses the correct profile donwloaded in 3. Be sure that you pick the correct one when Organizer asks for one. (if the previous step was OK, then this is definetely your problem, so double or triple check it).

If your want to be sure that your binary was generated with the correct profile before submitting it again to AppStore, do the following:

Open the binary with Finder (first, open the archive at Library/Developer/XCode/Archives/..., right click on it and "Show package contents", navigate to /Products/Applications/youApp, show package contents again),
Look for the file embedded.mobileprovision and open it with a text editor
Among the binary content, you should be able to localize a couple of fields called "application-identifier" and "aps-environment". Check they have the correct values.

I bet that if you check your previously archived apps you will see an incorrect profile. This is the only cause for your app not to return a deviceToken. (unless it receives it but it is not correctly sent to your server, a problem in step 2 of the communication above).
Comment: How could he submit an app that has the incorrect distribution provisioning profile? It would be rejected by iTunes.
Comment: Not really. It can be a correct profile but using a wildcard as bundleId. This will work normally, but not for the APNs. In fact, this is a very common problem when deploying APNs enabled apps.
Answer: Do you use gateway.push.apple.com and not gateway.sandbox.push.apple.com?
Comment: I use gateway.push.apple.com... thanks though I know this is a classic mistake
Comment: Btw I'm pretty sure it wouldn't work for ad hoc if it was .sandbox
Answer: If you can check your app logs in 'console app'(organizer>device>console ) by connecting device installed with your app containing device token null issue.

 Based on this
no valid 'aps-environment' entitlement string found for application

The problem is due to current Provisioning Profile does not contain
APNS information, as the Provisioning Profile is created BEFORE
creating the APNS certificate.
Solution: create a new Provisioning Profile & select the Provisioning Profile in Xcode will clear the error.
You can execute terminal command to check 'production provisional
profile' supports apns environment or not and it should look similar to the following:

security cms -D -i Path_Of_Your_AppStoreDistribution.mobileprovision
<code><key>Entitlements</key>
<dict>
    <key>application-identifier</key>
    <string>H22LLUHM4D.com.company.appName</string>
    <key>aps-environment</key>
    <string>production</string>
    <key>get-task-allow</key>
    <false/>
</dict>
</code>
Answer: If you have created a new provisioning profile for your application, I think you need to generate new certificates on your server as well.
Comment: No the certificates are linked to the Appid and not to the app provison


Identificar execução de arquivo dentro de um ZIP

Question: Eu criei um aplicativo que foi disponibilizado para download dentro de um .zip. Dentro do .zip tem um .exe e alguns arquivos necessários para realizar uma instalação. Até ai tudo certo.
Porém alguns usuários não realizam a extração dos arquivos antes de instalar, eles executam o arquivo .exe diretamente de dentro do .zip. Ista gera um erro pois o aplicativo não consegue encontrar os arquivos necessários para prosseguir com a instalação.
Então a minha dúvida é a seguinte: Como eu faço para identificar se o meu aplicativo está sendo executado de dentro de um .zip?
Considerações:
1) Por necessitar de uma solução rápida eu não posso colocar tudo dentro de um .msi ou como recursos incorporados no .exe. Isto implicaria em alterar o aplicativo que no momento não é uma boa opção.
2) Estou usando C# + VS 2012 com Windows Forms
Comment: Porque não cria um SFX ou um EXE do winzip.
Comment: Até onde sei, quando executamos os EXE dentro do arquivo zip, o Winrar, por exemplo, descompacta na pasta temp do windows.
Compartilha o erro que da quando é executado o teu sistema dentro do zip.
Comment: @GuilhermeNascimento poderia explicar melhor?
Comment: @PabloVargas o aplicativo não dá erro, ele verifica antes de iniciar a instalação se os arquivos existem, caso não exista ele não prossegue. Mas os arquivos podem não existir por mais de um motivo, não apenas pelo fato de estar em uma pasta temp.
Comment: por acaso o teu executável não tem os caminhos de arquivos fixo?
Comment: @PabloVargas Não são caminhos fixos, são relativos a pasta de execução do aplicativo
Answer: A solução que encontrei para a solução do meu problema foi criar um executável que continha o arquivo zip com todos os arquivos e colocar ele como Recurso incorporado ou Embedded resource e realizar a extração do conteúdo e iniciar o executável do zip na sequência.
Sei que existem opções melhores, como a utilização de instaladores de ampla utilização no mercado, mas por algumas particularidades do software não foi possível fazer isto.
Answer: Seu processo ta certo. Um tecnico deveria fazer a instalação do soft, seja ele seu ou da empresa cliente. Isso é um erro no procedimento de instalação por parte do usuário. O que você deve fazer é colocar uma observação quando o usuário baixar seu soft. A maioria sabe que deve descompactar antes de executar o instalador, mas é claro sempre tem os desinformados.
Comment: Nesse caso como o software é para cliente final, não teria a necessidade de ter um técnico sempre disponível para executar a instalação.


FieldPluginBase: How to test based on views field raw value?

Question: I know that the render method is not the right place to do conditional logic but I have no clue where I should implement my tests.
This is my render method I want to access the raw value of a field to do a test on it (conditional field):
  public function render(ResultRow $values) {

    $field_abnormal_category = $this->view->field['field_abnormal_category']->original_value->__toString();

    if($field_abnormal_category == 'No') {
      $field_category_image = $this->view->field['field_category_image']->original_value->__toString();
    }
    else {
      $field_category_image = '';
    }

    return [
    '#type' => 'inline_template',
    '#template' => $field_category_image
    ];

  }

The original_value object is returning the translation not the original string.
How can I access the original value of my field (not translated)?
Answer: For the untranslated field value get first the untranslated entity:
if ($entity = $this->getEntity($values)) {
  $untranslated_entity = $entity->getUntranslated();
  $untranslated_value = $untranslated_entity->field_example->value;
}


Need row returned from upsert

Question: I have a table that I need to upsert. If the row already exists then I want to update and return the row. If the row doesn't already exist then I need to insert and return the row. With the query I have below I get the row returned on insert, but not on update.
Table "main.message_account_seen"
    Column      |           Type           |                             Modifiers
----------------+--------------------------+-------------------------------------------------------------------
id              | integer                  | not null default nextval('message_account_seen_id_seq'::regclass)
field_config_id | integer                  | not null
edit_stamp      | timestamp with time zone | not null default now()
audit_stamp     | timestamp with time zone |
message_id      | integer                  | not null
account_id      | integer                  |

Here's the sql.
with upsert as (
    update message_account_seen set (message_id, account_id, field_config_id ) = (1, 60, 980)
    where message_id = 1 and account_id = 60 and field_config_id = 980 returning *
)
insert into message_account_seen (message_id, account_id, field_config_id)
select 1, 60, 980
where not exists (select message_id, account_id, field_config_id from upsert) returning *;

I can't do a postgres function, it needs to be handled in a regular sql query. Also, there is no constraint on the table for uniqueness of row otherwise I would use on conflict. But I'm willing to scrap this query and go with something else if need be.
These are the results when I run the query, and then run it again. You can see that on the insert or first run I get the row returned. However on subsequent runs of the query I get 0 rows returned. I know that it's working because the edit_stamp increases in time. That's a good thing.
# with upsert as (
    update message_account_seen set (message_id, account_id, field_config_id ) = (1, 60, 980)
    where message_id = 1 and account_id = 60 and field_config_id = 980 returning *
)
insert into message_account_seen (message_id, account_id, field_config_id)
select 1, 60, 980
where not exists (select message_id, account_id, field_config_id from upsert) returning *;
id | field_config_id |           edit_stamp           | audit_stamp | message_id | account_id
 --+-----------------+--------------------------------+-------------+------------+------------
38 |             980 | 09/27/2016 11:43:22.153908 MDT |             |          1 |         60
(1 row)

INSERT 0 1
# with upsert as (
    update message_account_seen set (message_id, account_id, field_config_id ) = (1, 60, 980)
    where message_id = 1 and account_id = 60 and field_config_id = 980 returning *
)
insert into message_account_seen (message_id, account_id, field_config_id)
select 1, 60, 980
where not exists (select message_id, account_id, field_config_id from upsert) returning *;
id | field_config_id | edit_stamp | audit_stamp | message_id | account_id
----+-----------------+------------+-------------+------------+------------
(0 rows)

INSERT 0 0

Comment: What version of postgres are you using? Also, it appears that the combination of `(message_id, account_id, field_config_id)` is unique, correct?
Comment: The version is 9.5.3, and the combination is unique, however there is no unique constraint and I'm unable to add it at this time. That would make things easier.
Comment: A unique index would make thinks easier. Also, it is unclear what you want it to do the case of update: currently in your code, you are assigning to the 3 columns the value that they already had, so this will have no effect.
Comment: An update to the edit_stamp is desirable, hence the update. However, I could probably get by for now with just doing an insert where not exists.
Comment: If you want to update the `edit_stamp`, you have to do it explicitly. Otherwise the `update` in the cte is useless. In fact, it makes things slower.
Answer: When the update succeeds its result is not returned in your query. This does it:
with upsert as (
    update message_account_seen
    set (message_id, account_id, field_config_id ) = (1, 60, 980)
    where (message_id, account_id, field_config_id) = (1, 60, 980)
    returning *
), ins as (
    insert into message_account_seen (message_id, account_id, field_config_id)
    select 1, 60, 980
    where not exists (select 1 from upsert)
    returning *
)
select * from upsert
union all
select * from ins
;

Comment: Works great! Thanks for the solution!
Answer: The best option here is to use the new upsert that postgres 9.5 offers, but this requires a unique index on (message_id, account_id, field_config_id). It can be used like this:
INSERT INTO message_account_seen(message_id, account_id, field_config_id)
VALUES (1, 60, 980)
ON CONFLICT (message_id, account_id, field_config_id)
DO UPDATE
SET edit_stamp=now() -- adjust here
RETURNING *;

This is probably the fastest way to do this and guarantees that nothing unexpected will happen if two processes try to upsert into the same table at the same time (your approach doesn't guarantee that).

Need row returned from upsert


Python argparse.FileType('w') creates only empty files

Question: I've been using argparse and have problems writing the output into a file with an optional output argument for argparse (--outfile). I always get an empty file when using the --outfile argument, but using standard output works. I am quite new to Python so there may be something obvious that I am missing.
I'm actually working on a more complex program that is a bit too long to share, so I created a simple dummy example that gets the same error.
This is the code:
import argparse
import sys

def print_content(file):
    for lines in file:
        print(f'This is the content: {lines}')

def create_argument_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser('printer',
                                     description='a commandline tool that prints the content of a file')
    parser.add_argument('input_file',
                        type=argparse.FileType(encoding='utf-8'),
                        default=[sys.stdin],
                        metavar='FILE')
    parser.add_argument('--outfile', '-o',
                        type=argparse.FileType('w', encoding='utf-8'),
                        default=[sys.stdout],
                        metavar='FILE')
    parser.add_argument('--print',
                        help='if present, prints the content of the file',
                        action='store_true')
    return parser

def main():
    parser = create_argument_parser()
    args = parser.parse_args()

    if args.print:
        print_content(args.input_file)

if __name__ == '__main__':
    main()

If I use standard output as below it works:
$ python program.py text.txt --print < output.txt
However, if I use the --outfile argument, the file is created but remains empty.
$ python program.py text.txt --print --outfile output.txt
What am I missing? (I use Python 3.8.5.)
Comment: and what does show print(args.outfile) ?
Comment: @user3732793 It shows: <_io.TextIOWrapper name='output.txt' mode='w' encoding='utf-8'>
Comment: So it opened the file for you, but you are not writing anything to it; of course then it remains empty.
Comment: @tripleee I am unsure as to how to write the output into the file then.
Answer: argparse creates the file for you, but it's still up to you to do anything with the new file.
For example, you might try
def write_contents(in_file, out_file):
    for line in in_file:
        out_file.write(line)

def main():
    parser = create_argument_parser()
    args = parser.parse_args()

    if args.print:
        write_content(args.input_file, args.output_file)

You seem to assume that print prints to the file, but it simply prints to standard output, always; argparse doesn't do anything to actually add any contents to the file (and it would be surprising if it did; what if you had an argparse configuration which requested for there to be several output files? Should it write to them all? Or the last one? Or the first one? So it's simply up to you to decide what to actually do with any files.)
Comment: You could close `sys.stdout` and reopen it to the new file. See e.g. https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python (and also notice how several answers there suggest that not doing this from Python at all might be a better solution).
Comment: Is there any possibility to write the entire output to that file? Of course the example code I gave is rather simple, in my actual program I don't just put the input file into the output file, but have a more complex console output. I'd like for the entire output to be put in that file. I guess there's no easy way to do that?
Answer: you could use this to write to a file for lines of a list
def file_write_csv(csv_name, csv_content):
""" generic csv writer """
print("writing " + csv_name)
with open(csv_name, "w") as out:
    for csv_line in csv_content:
        if not "\n" in csv_line:
            csv_line = csv_line + "\n"
        out.write(csv_line)


Laçamento de exceção

Question: Considerando que a tabela "usuarios" não existe,gostaria de entender porque ao invés do catch ser executado, a função "errors" é executada
Codigo :
<?php

$usuario = 'root';

$senha ='';

function errors($e)
{
    echo "Erro dados";
}

set_exception_handler('errors');

try
{

    $conn1 = new PDO('mysql:host=localhost;dbname=teste',$usuario, $senha);

}

catch(Exception $e){

    echo 'Erro ao conectar com o banco';

    die();
}

try
{

    $sql= "SELECT * FROM usuarios";

    $resul = $conn1->query($sql);

    $resul = $resul->fetch(PDO::FETCH_ASSOC);

    foreach ($resul as $key => $value) {
        echo $key .": ". $value. "
";
    }
}catch(Exception $e)
{

echo "Erro ao selecionar dados";

    die();

}

Answer: Basicamente não esta sendo lançada uma exception. Quando a sua query é executada, ela não retorna uma ResultSet, o que impossibilita a chamada da função fetch. Com isso o PHP lança um tipo de erro chamado E_NOTICE, o que não é uma instancia da classe Exception.
Enfim a única maneira (mais ou menos) de fazer o catch executar é lançar uma exception manualmente dentro do try. Algo mais ou menos assim:
throw new Exception("Erro na consulta sql");

Exemplo para que o segundo try/catch funcione:
try
{
    $sql= "SELECT * FROM usuarios";
    $resul = $conn1->query($sql);

    //quando a query sql falhar, por qualquer motivo,
    //será retornado o boolean false.
    if($resul === false){
        throw new Exception("Erro na consulta sql, algum campo não existe");
    }
    $resul = $resul->fetch(PDO::FETCH_ASSOC);

    foreach ($resul as $key => $value) {
    echo $key .": ". $value. "
";
    }
}catch(Exception $e)
{

    echo "Erro ao selecionar dados: " . $e->getMessage();
        die();

}

Nesse caso o seu set_exception_handler não será mais executado nessa situação especifica.
Comment: Mas erros não são tratados por `set_exception_handler` e sim por `set_error_handler`. Eu testei o código da pergunta aqui e a exceção foi capturada como esperado. Se o banco de dados `teste` não existe, o construtor do PDO lançará uma exceção. Tem como explicar melhor a parte em que você afirma que não é lançada?
Comment: Mas se uma exceção não é lançada, por quê a função definida em `set_exception_handler` é chamada?
Comment: Na resposta eu me referia ao segundo try/catch (que era a duvida da pergunta, quando a tabela usuarios não existisse). O primeiro try/catch realmente executa o catch (pois a classe pdo faz um throw de uma exception do tipo PDOException, que em algum momento estende a classe Exception). No segundo try/catch, quando a query falha, a variavel $resul vai receber o valor false, depois quando se tenta acessar a função fetch a partir da variavel $resul, acontece um erro (que não deixa de ser uma exception em relação ao que deveria acontecer). Para o catch não aconteceu nada.
Comment: Por que acontece um erro na execução do script (a chamada de uma função que não existe), embora esse erro não seja interpretado como uma instancia da classe Exception. Realmente aconteceu uma exceção na execução do codigo, mas não é o tipo que o laço try/catch espera.
Comment: Nossa, eu podia jurar que o problema era no primeiro. Eu havia lido que o banco de dados não existia. Agora tudo faz sentido. Nesse caso acho que o melhor seria mesmo utilizar um `if` verificando o retorno da *query*. Talvez você possa adicionar a sua resposta.

Laçamento de exceção


MKCOL 405 and LOCK 500 on git push (error: cannot lock existing info/refs)

Question: I'm having some troubles setting up a Git server with apache.
Here is my gitrepo.conf:
DavLockDB "opt/local/apache2/var/DavLock"

<Directory /opt/local/apache2/htdocs/repo>
  DAV On
  Deny from all
  AuthType Basic
  AuthName "Git repositories"
  AuthUserFile /etc/apache2/other/htpasswd
  AuthGroupFile /etc/apache2/other/htgroup-git
</Directory>

<Directory /opt/local/apache2/htdocs/repo/myproject.git>
  Allow from all
  Order allow,deny
  <Limit GET>
    Require group myproject-reader
  </Limit>
  <Limit GET PUT POST DELETE PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK>
    Require group myproject-writer
  </Limit>
</Directory>

When I git push to http://admin@localhost/repo/myproject.git, I get this:
error: cannot lock existing info/refs
fatal: git-http-push failed

Here is a snip from my access_log:
::1 - - [28/Jul/2012:19:05:52 +0100] "GET /repo/myproject.git/info/refs?service=git-receive-pack HTTP/1.1" 401 401
::1 - admin [28/Jul/2012:19:05:52 +0100] "GET /repo/myproject.git/info/refs?service=git-receive-pack HTTP/1.1" 401 401
::1 - admin [28/Jul/2012:19:05:55 +0100] "GET /repo/myproject.git/info/refs?service=git-receive-pack HTTP/1.1" 200 -
::1 - admin [28/Jul/2012:19:05:55 +0100] "GET /repo/myproject.git/HEAD HTTP/1.1" 200 23
::1 - - [28/Jul/2012:19:05:57 +0100] "PROPFIND /repo/myproject.git/ HTTP/1.1" 401 401
::1 - admin [28/Jul/2012:19:05:57 +0100] "PROPFIND /repo/myproject.git/ HTTP/1.1" 207 558
::1 - admin [28/Jul/2012:19:05:57 +0100] "HEAD /repo/myproject.git/info/refs HTTP/1.1" 200 -
::1 - admin [28/Jul/2012:19:05:57 +0100] "HEAD /repo/myproject.git/objects/info/packs HTTP/1.1" 200 -
::1 - admin [28/Jul/2012:19:05:57 +0100] "MKCOL /repo/myproject.git/info/ HTTP/1.1" 405 249
::1 - admin [28/Jul/2012:19:05:57 +0100] "LOCK /repo/myproject.git/info/refs HTTP/1.1" 500 535

I seem to be getting error 405 with MKCOL and error 500 with LOCK.
And here's my error_log:
[Sat Jul 28 19:05:52 2012] [error] [client ::1] user admin: authentication failure for "/repo/myproject.git/info/refs": Password Mismatch
[Sat Jul 28 19:05:57 2012] [error] [client ::1] Could not LOCK /repo/myproject.git/info/refs due to a failed precondition (e.g. other locks).  [500, #0]
[Sat Jul 28 19:05:57 2012] [error] [client ::1] The locks could not be queried for verification against a possible "If:" header.  [500, #0]
[Sat Jul 28 19:05:57 2012] [error] [client ::1] Could not open the lock database.  [500, #400]
[Sat Jul 28 19:05:57 2012] [error] [client ::1] (2)No such file or directory: Could not open property database.  [500, #1]

And I am entering the correct password as commands like git remote show origin which asks for the password accepts it fine.
Any ideas?
Answer: I finally found the fix, and it was such a simple one too.
This:
DavLockDB "opt/local/apache2/var/DavLock"
should've been this:
DavLockDB "/opt/local/apache2/var/DavLock"
notice the / at the beginning of the filename.


ArrayList not received from one Fragment to another using bundle and Parcelable

Question: I am passing the ArrayList from one Fragment to another.I am using Parcelable to achieve this.I am passing ArrayList using Bundle.But in another Fragment I am not able to receive this.
This is code for Class which implements Parelable
public class CurrentEntry implements Parcelable{

     String name;
     String people;
     String estimate;

    public CurrentEntry()
    {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPeople() {
        return people;
    }

    public void setPeople(String people) {
        this.people = people;
    }

    public String getEstimate() {
        return estimate;
    }

    public void setEstimate(String estimate) {
        this.estimate = estimate;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.name);
        dest.writeString(this.people);
        dest.writeString(this.estimate);
    }

    public static final Parcelable.Creator<CurrentEntry> CREATOR
            = new Parcelable.Creator<CurrentEntry>() {
        public CurrentEntry createFromParcel(Parcel in) {
            return new CurrentEntry(in);
        }

        public CurrentEntry[] newArray(int size) {
            return new CurrentEntry[size];
        }
    };

    public CurrentEntry(Parcel in)
    {
        this.name=in.readString();
        this.people=in.readString();
        this.estimate=in.readString();
    }
}

This is code for sending ArrayList from one Fragment to Another.
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                   try
                   {

                       JSONObject object=new JSONObject(response.toString());

                       JSONArray data=object.getJSONArray("results");

                       for( i=0;i<data.length();i++)
                       {
                           JSONObject json = data.getJSONObject(i);
                           final CurrentEntry c=new CurrentEntry();
                           userUrl=json.getString("list");
                           JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, userUrl, null, new Response.Listener<JSONObject>() {
                               @Override
                               public void onResponse(JSONObject response) {
                                   try {
                                       JSONObject temp=response.getJSONObject("user");

                                       String foodie_name=temp.getString("first_name");
                                           String lname=temp.getString("last_name");
                                       c.setName(name+"\t"+lname);
                                       progressDialog.dismiss();

                                   } catch (JSONException e) {
                                       e.printStackTrace();
                                   }
                                 //  adapt.notifyDataSetChanged();
                               }
                           }, new Response.ErrorListener() {
                               @Override
                               public void onErrorResponse(VolleyError error) {

                               }
                           })

                           AppController.getInstance().addToRequestQueue(request,second_req);
                           c.setPeople(json.getString("no_people"));
                           String temp=json.getString("predicated_t");
                           c.setEstimate(temp+"min");
                         //  c.setNo(count);
                           TempUserStatusInfo info=new TempUserStatusInfo();
                           Bundle bundle=new Bundle();
                           bundle.putParcelable("myList",c);
                           info.setArguments(bundle);
                           current.add(c);
                           adapt=new NewAdapter(current,getActivity().getApplicationContext());
                           recyclerView.setAdapter(adapt);

                        }

                }
                   catch (JSONException e)
                   {
                       e.printStackTrace();
                   }

                }

This is code for receiving the ArrayList where I am setting SwipeCards
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.temp_user_status_info, container, false);
        swipeCardsView=(SwipeCardsView)v.findViewById(R.id.swipeCard);
        infoAdapter=new CurrentInfoAdapter(info,getActivity());
        swipeCardsView.retainLastCard(false);
        swipeCardsView.enableSwipe(true);
        CurrentInfo currentInfo=new CurrentInfo();

        Bundle bundle=this.getArguments();
        if(bundle!=null){
            currentInfo=bundle.getParcelable("myList");
        }

        person_name=getArguments().getString("name");
        person_people=getArguments().getString("people");
        person_estimate=getArguments().getString("estimate");

        currentInfo.setName(person_name);
        currentInfo.setPeople(person_people);
        currentInfo.setEstimate(person_estimate);
        Log.i("name",person_name);
        Log.i("people",person_people);
        Log.i("estimate",person_estimate);
        info.add(currentInfo);
        swipeCardsView.setAdapter(infoAdapter);
        return v;
    }

The error is
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
                                                                         at biz.fyra.QueueApp.TempUserStatusInfo.onCreateView(TempUserStatusInfo.java:52)
                                                                         at android.support.v4.app.Fragment.performCreateView(Fragment.java:2248)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1340)
                                                                     at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1569)

Comment: Please stop using the [tag] markdown for class names. Instead, use the proper name - e.g., ArrayList - and surround it with backticks, ` - `ArrayList`.
Answer: Problem is your are not set string values but your trying to receive that value. that why your getting null pointer exception .Pass string value also.
TempUserStatusInfo info=new TempUserStatusInfo();
                       Bundle bundle=new Bundle();
                       bundle.putParcelable("myList",c)
    bundle.putString("name",value);
    bundle.putString("people",value);
    bundle.putString("estimate",value);

Answer: Use correct arraylist to send parceable arraylist not the class object
putParcelableArrayListExtra("list", infoArrayList);

where custom object arraylist is
ArrayList<CurrentInfo> infoArrayList;

in Recieving Fragment class use this
ArrayList<CurrentInfo> infoArrayList = bundle.getParcelableArrayListExtra("list");

Comment: It is giving me error as Imcompatible Types
Comment: did u use this class CurrentEntry ?
Comment: Yes it s my Custom object for ArrayList
Comment: okay make it parceable and use it
Answer: You can use Serializable for this
//for putting in bundle
bundle.putSerializable("key", class_value)

//for receieving
object = arguments.getSerializable("key") as className

Do not forget to extend the class with serializable.
Answer: Another idea is to use Gson to make json object and then make string of it send this string and on other side again make object from that json string using Gson.
Convert Java object to JSON
Gson gson = new Gson();
Staff obj = new Staff();
String jsonInString = gson.toJson(obj);

Revert from json to object:
Gson gson = new Gson();
Staff staff = gson.fromJson(jsonInString, Staff.class);

Add following dependency to your gradle file:
<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.6.2</version>
</dependency>

By doing this you dont have to serialize/deserialize and you can send it as string.
Answer: Try like this to pass arraylist one fragment to another
your first Fragment
ArrayList<ParcelableRow> parceArrayList = new ArrayList<ParcelableRow>();
Bundle bundle=new Bundle(); bundle.putParcelableArrayListExtra("yourArraylist",parceArrayList);

get Arraylist in other Fragment
ArrayList<ParcelableRow> result = data.getParcelableArrayList("yourArraylist");

Comment: I am getting error when i receive ArrayList Incompatible types.
Required:
ArrayList

Found:
ArrayList
Comment: how you receiving arraylist can you please  show the code?
Comment: ArrayList current=getArguments().getParcelableArrayList("MyList");
Comment: did u implement Parcelable in your CurrentInfo class ?
Comment: No.Is there a case I need to implement Parcelable in both CurrentEntry and CurrentInfo ?
Comment: you need to implement Parcelable to get the arraylist in another fragement.try and let me know does it make any difference or not
Comment: Now  I am done with this.That error resolved. Now how to get and set the data in current fragment  ?
Comment: you got the list  now  read understand do it by your own.thank you
Comment: I got this error    Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getParcelableArrayList(java.lang.String)' on a null object reference
Comment: we can only show you the path how do things rest of things you need to do it by your own try to debug the code and see where things going wrong.thank you


JMS Bridge existing queue messages

Question: Is it possible to setup a JMS Bridge to bridges existing JMS messages from one queue to another. I have the bridging working for new messages, but if the messages already exist in the source queue then they don't get bridged tot he destination queue.
Is there any way to make this happen?
Cheers.
Answer: Bridge only can take effect on the messages that are flowing into the source, not those that are already in the source.

JMS Bridge existing queue messages


R: multiple linear regression model and prediction model

Question: Starting from a linear model1 = lm(temp~alt+sdist) i need to develop a prediction model, where new data will come in hand  and predictions about temp will be made.
I have tried doing something like this:
model2 = predict.lm(model1, newdata=newdataset)
However, i am not sure this is the right way. What i would like to know here is, if this is the right way to go in order to make prediction about temp. Also i am a bit confused when it comes to the newdataset. Which values should be filled in etc.?
Answer: newdata should contain a column for each of your predictive variables, alt and sdist. (Any variables except the one you're predicting.) For example:
newdata = data.frame(alt = newAltVector, sdist = newSdistVector)
predictions = predict.lm(model, newdata)

predictions will then contain a fitted y value for each new x. In the below, black dots represent training data, and the blue dots represent predicted values.
Whether that's the right way to predict temp depends on how well a linear model approximates the relationship between variables. Try this intro to evaluating a linear model in R.
Comment: Well your answer helped a lot. Thanks for the link too. By the way how did you plotted the using `predictor` and `predicted` variables?
Comment: plot(x, y, xlab = "Predictor variable", ylab = "Predicted variable"); points(predictions, newdata$x, col = "blue")