Markov Chain problem with first passage time

Question: Let $X$ a Markov Chain with space state $S$, and transition matrix $P$. Let $A \subset S$ and $\tau_A = \inf\{n \ge 0: X_n \in A\}$ . Suppose that exists $n \ge 1$ and $\alpha > 0$ that for all $x \in A^c$ (the complement of $A$), $p^n_{x,A} \ge \alpha$. i) Show that for all $k \in \mathbb{N}$ and $x \in S$, $\mathbb{P}_x(\tau_A > kn) \le (1 - \alpha)^k$. ii) Show that $\mathbb{E}_x[\tau_A] \le \frac{n}{\alpha}$, and in particular, $\mathbb{P}_x(\tau_A < \infty) = 1$.
This is how I tried to solve it:
If $x \in A$, we have
$$\mathbb P _x(\tau_A = 0) = 1 \implies \mathbb P _x(\tau_A > kn) = 0 \le (1-\alpha)^k.$$
Let $x \in A^c$. If $\lambda = (\lambda_i : i \in S)$ is a probability distribution of $X$, so $\lambda_x = \mathbb P_x(X_0 = x)$. Moreover, it's known that

By definition of $\lambda$, we have $\lambda_x \le 1$;
Since $X$ is Markov Chain, we have (from Chapman-Kolmogorov)
$$p^n_{x,A^c} = \sum_{i_1, \dots, i_{n-1} \in S}{p_{x,i_1} \cdots p_{i_{n-1},A^c} }$$
Since $A^c \subset S$,
$$p_{x,A^c}\underbrace{p_{A^c,A^c} \cdots p_{A^c,A^c} }_{n-1 \text{ times}} \le \sum_{i_1, \dots, i_{n-1} \in S}{p_{x,i_1} \cdots p_{i_{n-1},A^c} } = p^n_{x,A^c}$$
Similarly,
$$\underbrace{p_{A^c,A^c} \cdots p_{A^c,A^c} }_{n \text{ times}} \le \sum_{i_1, \dots, i_{n-1} \in S}{p_{A^c,i_1} \cdots p_{i_{n-1},A^c} } = p^n_{A^c,A^c} $$
It's easy to see, that
$$p^n_{A^c,A^c} = 1 - p^n_{A^c,A^c}$$
For $x \in A^c$,
$$p^n_{A^c,A} \ge p^n_{x,A}$$
And finally,
$$p^n_{x,A^c} = 1 - p^n_{x,A} \le 1 - \alpha$$

Using some properties about Markov Chains and all these information, it follows that
$$\begin{aligned}\mathbb P_x(\tau_A > kn) &= \mathbb P (X_0 \not \in A,X_1 \not \in A, \dots, X_n \not \in A, X_{n+1} \not \in A, \dots, X_{2n} \not \in A,\dots, X_{kn - 1} \not \in A,X_{kn} \not \in A\mid X_0 = x)\\
&=\mathbb P(X_0 = x, X_1 \not \in A, \dots, X_n \not \in A, \dots, X_{2n} \not \in A,\dots, X_{kn} \not \in A )\\
&= \lambda_x p_{x,A^c}\underbrace{p_{A^c,A^c}\cdots p_{A^c,A^c}}_{n-1 \text{ times}}\underbrace{\underbrace{p_{A^c,A^c}\cdots p_{A^c,A^c}}_{n \text{ times}}\cdots \underbrace{p_{A^c,A^c}\cdots p_{A^c,A^c}}_{n \text{ times}}}_{k - 1 \text{ times}}\\
&\le p_{x,A^c}\underbrace{p_{A^c,A^c}\cdots p_{A^c,A^c}}_{n-1 \text{ times}}\underbrace{\underbrace{p_{A^c,A^c}\cdots p_{A^c,A^c}}_{n \text{ times}}\cdots \underbrace{p_{A^c,A^c}\cdots p_{A^c,A^c}}_{n \text{ times}}}_{k - 1 \text{ times}} \text{ (from 1)}\\
&\le \left(\sum_{i_1,\dots, i_{n-1} \in S}{p_{x,i_1}p_{i_1,i_2}\cdots p_{i_{n-1},A^c}}\right) \cdot \left(\sum_{i_1,\dots, i_{n-1} \in S}{p_{A^c,i_1}p_{i_1,i_2}\cdots p_{i_{n-1},A^c}}\right)^{k-1} \text{ (from 3 and 4)}\\
&= \left(p^n_{x,A^c}\right)\left(p^n_{A^c,A^c}\right)^{k-1} \text{ (from 2 and 4)}\\
&\le \left(p^n_{x,A^c}\right)\left(1 - p^n_{x,A}\right)^{k-1} \text{ (from 5 and 6)}\\
&\le (1-\alpha)^k \text{ ( from 7)}\end{aligned}$$
This is how I tried to solve item i). Note that,for $i \ge 1$
$$\{\tau_A > i + 1\} \subseteq \{\tau_A > i\}$$
It means that
$$\mathbb P_x(\tau_A = \infty) = \mathbb P_x(\lim_{k \to \infty}{\tau_A > kn}) = \lim_{k \to \infty} {\mathbb P_x({\tau_A > kn})} \le \lim_{k \to \infty}{(1-\alpha)^k} = 0$$
It implies that,
$$\mathbb P_x(\tau_A < \infty) = 1 - \mathbb P_x(\tau_A = \infty) = 1$$
Finally,
$$
\begin{aligned}
\mathbb{E}_x[\tau_A] &= \frac{n}{n}\mathbb E_x[\tau_A]\\
&= n\mathbb E_x\left[\frac{\tau_A}{n}\right]\\
&= n\left(\sum_{i \ge 1}{\mathbb P_x\left(\frac{\tau_A}{n} > i\right)}\right)\\
&= n\left(\sum_{i \ge 1}{\mathbb P_x(\tau_A > ni)}\right)\\
&\le n\left(\sum_{i \ge 1}{\mathbb (1-\alpha)^i}\right)\\
&=n \cdot \frac{1}{1 - (1-\alpha)} = \frac{n}{\alpha}
\end{aligned}
$$
Please, help me to find any mistakes. Thanks for the help!
Comment: It is not clear what $i$ is in the inequality $p_{ii}^n \geq \alpha$, and how $i$ relates to $x$.  I also observe that $\tau_A \leq \infty$ is an inequality that is always true, so its probability is trivially 1.
Comment: I'm sure you mean $E[\tau_A]\leq n/\alpha$ since you cannot infer equality from the given information. To prove (i) you group the $kn$ slots into groups of $n$ consecutive slots. You get (ii) from (i) using a sum formula for expectation of nonnegative integer random variables.
Comment: You group the $kn$ slots into groups of $n$ consecutive.  Every $n$ consecutive slots you independently enter $A$.
Comment: I'm sorry. I made a mistake when I wrote $p^n_{ii}$. The correct is $p^n_{x,A}$.
Comment: But, do you know how to get this $(1 - \alpha)^k$ formula? I tried to show by induction, but I think I'm missing some property about the $\tau_A > kn$ probability. Is there some trick or theorem to help me?
Comment: Ok! I gonna try, and after that, I will come back here to see if I'm in the right direction.
Comment: I tried to use the sum formula for expectation of nonnegative integer random variables
$$\mathbb{E}[T] = \sum_{i \ge 0}{\mathbb{P}(T > i)}$$
but, I can't get a '$\le$' innequalty.
Answer: Note that if $x\in A$ then $\tau_A=0$ and so $$0=\mathbb{P}_x(\tau_A>kn)\leq (1-\alpha)^k$$ On the other hand, if $x\notin A$ we can say that $$\mathbb{P}_x(\tau_A>kn)=\mathbb{P}(X_1\notin A,X_2 \notin A,\ldots,X_{kn}\notin A|X_0=x)$$ The right hand side is bounded above by $$\mathbb{P}(X_n\notin A,X_{2n}\notin A,\ldots,X_{kn}\notin A|X_0=x)$$ Using the chain rule for conditional probability along with Markov this equals $$\mathbb{P}(X_n\notin A|X_0=x)\times \mathbb{P}(X_{2n}\notin A|X_n\notin A)\times \dots \times\mathbb{P}(X_{kn}\notin A|X_{(k-1)n}\notin A)$$ which is bounded above by $(1-\alpha)^k$. Clearly if $x\in A$ then $\mathbb{E}_x(\tau_A)=0$ so for $x \notin A$ we have that $$\mathbb{E}_x(\tau_A)=\sum_{j=0}^{\infty}\mathbb{P}_x(\tau_A > j)=1+\sum_{j=1}^{n-1}\mathbb{P}_x(\tau_A>j)+\sum_{k=1}^{\infty}\sum_{j=kn}^{kn+n-1}\mathbb{P}_x(\tau_A>j)$$ Because $$\sum_{j=1}^{n-1}\mathbb{P}_x(\tau_A>j)\leq(n-1)\mathbb{P}_x(\tau_A>1)\leq(n-1)(1-\alpha)$$ $$\sum_{j=kn}^{kn+n-1}\mathbb{P_x}(\tau_A>j)\leq n\mathbb{P}_x(\tau_A>kn)\leq n(1-\alpha)^k$$ it follows that $$\mathbb{E}_x(\tau_A)\leq1+(n-1)(1-\alpha)+n\sum_{k=1}^{\infty}(1-\alpha)^k=\alpha(1-n)+\frac{n}{\alpha}\leq \frac{n}{\alpha}$$ as desired. Now we'll prove $\mathbb{P}_x(\tau_A<\infty)=1$ for $x\notin A$. For $j\geq n$ we have $$\mathbb{P}(X_j\notin A,\ldots ,X_1 \notin A|X_0=x)\leq \mathbb{P}(X_{n\left \lfloor{j/n}\right \rfloor }\notin A,\ldots,X_n \notin A|X_0=x)$$ The right hand side is bounded above by $(1-\alpha)^{\left \lfloor{j/n}\right \rfloor }$ and finally $$\mathbb{P}_x(\tau_A=\infty)\leq \lim_{j\rightarrow \infty}(1-\alpha)^{\left \lfloor{j/n}\right \rfloor}=0 $$
Comment: Hi, Matthew! Can you see if my answer is right?
Comment: Let me take a look. Please fact check my answer too. Note when I say "using the Markov property" I'm first using the chain rule of conditional probability $$P(A_1\cap A_2 \cap A_3|A_0)=P(A_3| A_0\cap A_1 \cap A_2)P(A_2|A_0\cap A_1)P(A_1|A_0)$$ and then applying the Markov property.
Comment: I think you can simplify you first argument by noting that $$\{X_1\notin A\}\cap \ldots \cap \{X_{kn}\notin A\}\subseteq\{X_n\notin A\}\cap \ldots \cap \{X_{kn}\notin A\}$$ Also, it may not be necessry to define an initial distribution $\lambda_x$ on $X_0$.
Comment: Lastly, you argument that $\mathbb{P}_x(\tau_A=\infty)=0$ looks better than mine :)


Probability that the eventually a six on a dice will appear.

Question:
Dave rolls a fair six-sided die until a six appears for the first time. Independently, Linda rolls a fair six-sided die until a six appears for the first time. Let $ m$ and $ n$ be relatively prime positive integers such that $ \frac{m}{n}$ is the probability that the number of times Dave rolls his die is equal to or within one of the number of times Linda rolls her die. Find $ m+n$.

If you roll a die $r$ times, the probability of getting a six on the $r$th try is:
$\frac{1}{6} \cdot \frac{5^{r-1}}{6^{r-1}}$
Now I believe casework for Dave so:
1 roll: $ \frac{1}{6} $, 2 rolls: $\frac{1}{6} \frac{5}{6}$, 3 rolls: $\frac{1}{6} \frac{5^2}{6^2}$, .... , $r$ rolls, $\frac{1}{6} \frac{5^{r-1}}{6^{r-1}}$
I would add this up, but still, we never found $r$?
HINTS ONLY
EDIT
As pointed by 5xum, $L=1$ isn't possible with $D = L - 1$. So I got:
$P = 1 \cdot (1/6)\sum_{r=2}^{\infty} (5/6)^{r-2} + 1  + ...$
But $P > 1$ already, which is impossible?
Comment: I can't figure out how you constructed your series sum.  You might consider looking at my response and writing out the first few terms...?
Answer: Let $D$ denote the random variable telling how many rolls Dave took to roll a $6$, and let $L$ denote the variable telling how many rolls Linda took.
Then what you calculated were $P(D=k)$ for certain values of $k$. For example, the probability that Dave took $5$ rolls to roll a $6$ is
$$\frac56\cdot\frac56\cdot\frac56\cdot\frac56\cdot\frac16$$
What you need to calculate is the probability that $D=L\pm1$ or $D=L$, which is the probability
$$P(D=1\wedge (L=1\vee L=2)) + P(D=2\wedge (L=1\vee L=2\vee L=3)) + \dots$$
and the sum is actually infinite. I think writing it down may simplify it a bit, and you will be summing power series, which is not that hard...
Comment: Shouldn't be $D= L $ or $D = L \pm 1$?
Comment: What is: $/vee$ and $/wedge$?
Comment: @Amad27 Symbols for **or** and **and**.
Comment: $P_1 = \frac{1}{6}( \frac{1}{6} (1 + \frac{5}{6})$. and then, $P_2 = \frac{5}{6}\frac{1}{6}...$. But then $ L = 1$ isnt possible in that case!
Comment: @Amad27 What is $P_1$? What is $P_2$? In what case is $L=1$ not possible?
Comment: Sorry, I forgot to (+1), just did it. $D= L-1$ isnt possible with $L=1$ but I still got an impossible answer, can you check my edit?
Comment: @5xum, please??
Comment: @Amad27 Well, you can simply set $P(D=0)=0$ in your sum, that's not really a problem. But in your sum, how did you get the one into the sum? You have $P = 1 \cdot (1/6)\sum_{r=2}^{\infty} (5/6)^{r-2} + 1  + ...$, but why the plus one?
Answer: Let $D, L$ be the obvious random variables.  Then the desired probability is
\begin{align}
P & = P(D = 1, L = 1) + P(D = 1, L = 2) + P(D = 2, L = 1) \\
  & + P(D = 2, L = 2) + P(D = 2, L = 3) + P(D = 3, L = 2) \\
  & + P(D = 3, L = 3) + P(D = 3, L = 4) + P(D = 4, L = 3) \\
  & + \cdots
\end{align}
Each row constitutes an element in a geometric series.  Find the first row sum and the ratio, and the rest is trivial.
Answer: If $D$ and $L$ denote the number of rolls needed by Dave and Linda and $E$ denotes the event then:$$P(E)=P(D=L)+P(D=L-1)+P(D=L+1)$$
This with $P(D=L-1)=P(D=L+1)$ on base of symmetry, and with:
$$P(D=L)=\sum_{k=1}^{\infty}P(D=k\wedge L=k)=\sum_{k=1}^{\infty}P(D=k)P(L=k)$$For $P(D=L-1)$ you can also find such an expression.

edit:
$$P\left(D=L\right)=\sum_{k=1}^{\infty}P\left(D=k\right)P\left(L=k\right)=\sum_{k=1}^{\infty}\left[\left(\frac{5}{6}\right)^{k-1}\frac{1}{6}\right]^{2}=$$$$\frac{1}{36}\sum_{k=1}^{\infty}\left(\frac{25}{36}\right)^{k-1}=\frac{1}{36}\frac{1}{1-\frac{25}{36}}=\frac{1}{11}$$
As said: likewise you can find $P(D=L-1)$.
Comment: @Amad27 it's an infinite series because $D$ and $L$ are bother Geometric Random Variables. $D$ is the count of tries until a six, which can realise values of $\{1, 2, 3, 4, ..., \to \infty\}$.  They asked to find the probability that $L$ is within $1$ step of $D$, so they're after $\mathsf P(L-1\leq D\leq L+1)$
Comment: $L + 1$ isnt allowed? Also, what about $L -2, L - 3, etc...$? +1
Comment: If you have found $P(D=L-1)$ then you have also found $P(D=L+1)$ because (as said) the probabilities are equal by symmetry. So you are ready then. I don't really understand your second question. Expressions like $L-2$ etc. are irrelevant in this context.
Comment: The problem says it can be any number less than Linda's. so $L - 2$ can be a case as well
Comment: "equal to or within one of the number of times Linda rolls" sounds very much like $D=L$ or $[D$ is one more than, or one less than $L]$. Do you think that $P(D\leq L)$ must be calculated?
Comment: mmm... I think I screwed with the wording. What does "within" mean? I thought it meant if Linda did: $\{1, 2, 3, 4, 5, ..., 6\}$ then withing or equal is: $1, 2, 3, 4, 5,$ and $=$ is $6$.
Comment: If you wanted to find $P(D\leq L)$ then seek your hail in the equation $P(D\leq L)+P(L\leq D)=1+P(D=L)$. Combine this with $P(D\leq L)=P(L\leq D)$ (symmetry) and find $P(D=L)$ as written in my answer.
Comment: Just having some trouble; Why is it an INFINITE series? Also but what is their MEANING, do they want: $P(D \le L)$ or just around one?
Comment: Is $P(D = L) = \frac{1}{6} \left( \frac{5}{6} \right)^{r-1}$
Comment: @GrahamKemp, Thanks. So  but is $P(D = L) = 1/6(5/6)^{r-1}$?
Comment: I got an impossible answer, adding edit.
Comment: @drhab, please, one last help!
Comment: See my edit as the last help.


Can you call a variable in a method in another class?

Question: Hi I'm new to prgramming, and currently doing a project in java.
I'm doing a simulation of a zoo, where animals eat specific foods and after consumption, they will gain a specific amount of health, as well as produce a specific amount of waste.
In order to do this, food has to be stored in a FoodStore class in a HashMap. In order to do this, I had created a a separate class called food, and created methods with their health and waste properties:
public class Food {

public int healthAdd;
public int wasteProd;

public Food hay(){
    healthAdd = +1;
    wasteProd =4;
    return null;
}

However, when I feed the animals I have to show that they have now gained new health points and have produced waste.
So i was wondering if it was possible to access the variables that I have initialized in, for example, the healthAdd & wasteProd in the "hay" method of the FoodClass in another class?
Sorry if this seems long winded :)
Comment: You can't call variables. You can only call methods. Those methods can access the variables in the object on which you called the method... Does that give you any ideas?
Comment: Can you please note that you have been already told twice that you don't call variables.
Comment: What does *"calling a variable"* mean?  Do you mean "can you access a variable used in another method?"
Comment: you can access them with the help instance of the Food class instance as you have declared them `public`.
Comment: @scottb yes thats what I meant, sorry for not being clear
Comment: @Laurenth can you elaborate how we can call method variables from another class
Answer: Variables in Java can be of two broad types.  You can have "instance variables" and you can have "local variables" (there are also static variables which I won't discuss).
Local variables are defined inside methods or inside curly braces and live only as long as the defined scope is active.  In other words, if a local variable is defined inside braces, it ceases to exist as soon as execution exits those braces.
Instance variables are defined inside a class definition but outside of any methods or other curly braces.  Those variables live for as long as the corresponding instance of that class lives.
For example:
public class MyClass {
    public int myInstanceVar1 = 0; // lives for as long as this MyClass
                                   // instance exists

    public MyClass() {   // Constructor for MyClass instances

        int myLocalVar1 = 0; // lives only during the constructor invocation
        :
        :
    }
    :
    :
}

In the snippet above, you would be able to access the myInstanceVar1 field on any MyClass object that wasn't null.  The instance field exists for as long as the object does.
You would not, however, be able to access myLocalVar1 because it only exists during the time at which the constructor is executing.  After the constructor has finished, the local variable falls out of scope and is no longer available anywhere in your program.


Using Windows AMI rather then Linux on Amazon Cloud to deploy PHP Application

Question: Currently i have deployed my application on Linux AMI instance on Amazon cloud.
But i am facing lot of problems there like some php files dont work on Linux beacause Linux is case sensitive, imagecreatefromstring function also don't works on Linux because GD package is not installed there by default in PHP. Moreover i can't succeded in installing phpmyadmin there.
Everytime i have to perform database operations by command prompt there using Putty.
Moreover my scripts responsible to send frequent emails to various users also don't work on Linux
while working fine on Windows.
Overall I am using XAMPP on windows  and everything works fine here.
But in case og Linux server i need to manually install PHP packages,mysql packages,PHP graphic packages,PHP mailing PEAR packages. etc.
Please tell me if i run my application on Windows Server 2008 AMI there then will i face any security or performacne related issues there?
Thanks in advance guys.
Answer: Security and performance depends on a lot of factors. You're basically asking "is Linux better than Windows" as a catch-all question.
For what it's worth, I run several Windows EC2 images, and have absolutely no security or performance concerns with the underlying platform.


Why Doesn't This PHP Download Script Work?

Question: Here is a simple script I have written to limit downloads for users to one at a time (IE if they are downloading a file then they cannot download another one until they cancel the current download or it finishes).
ignore_user_abort(true);

$local_file = $_GET['filename'];
$download_file = explode("/", $local_file);
$download_file = $download_file[count($download_file) -1];

// set the download rate limit (value is in kilobytes per second
$download_rate = 100;
if(file_exists($local_file) && is_file($local_file)) {
    $ip = visitor_ip();
    if(!are_downloading($ip)) {
        header('Cache-control: private');
        header('Content-Type: application/octet-stream');
        header('Content-Length: '.filesize($local_file));
        header('Content-Disposition: filename='.$download_file);

        flush();

        $file = fopen($local_file, "r");
        log_downloader($ip);

        while(!feof($file)) {
            if (!connection_aborted()) {
            // send the current file part to the browser
            print fread($file, round($download_rate * 1024));
            // flush the content to the browser
            flush();
            // sleep one second
            sleep(1);
        } else {
            break;
            }
        }

        clear_downloader($ip);
        fclose($file);
    } else {
        die('Due to server limitations you may only download one file at a time. Please cancel or wait for your current download to finish before trying again. Click here to return.');
    }
} else {
    die('Error: The file '.$local_file.' does not exist!');
}

function visitor_ip() {
    if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $TheIp=$_SERVER['HTTP_X_FORWARDED_FOR'];
    else $TheIp=$_SERVER['REMOTE_ADDR'];

    return trim($TheIp);
}

function are_downloading($ip) {
    $query = "select * from downloaders where ip_addr='$ip'";
    $result = mysql_query($query);

    $num_rows = mysql_num_rows($result);

    return $num_rows > 0;
}

function log_downloader($ip) {
    $query = "insert into downloaders (ip_addr) values ('$ip')";
    $result = mysql_query($query);
}

function clear_downloader($ip) {
    $query = "delete from downloaders where ip_addr='$ip'";
    $result = mysql_query($query);
}

When I test it out, it works fine, but for a lot of people, their IP never gets cleared out of the database - even when they have finished downloading/cancelled a file. Why don't the IPs get deleted?
Comment: This is a bad idea because of NAT. I'd use their PHP session ID instead of their IP to identify them, which is guaranteed to be unique.
Comment: This script is extremely insecure.  You are letting users download whatever they want off your hard drive, including the source code to your applications, possibly passwords, etc.  You're also wide open to SQL injection attacks, since you are trusting the request headers for the `HTTP_X_FORWARDED_FOR` values and what not, and not escaping anything before using it in a database.  Use prepared/parameterized queries with PDO or similar to avoid SQL injection problems, and validate the files you're allowing users to download to make sure they are in the directory you expect.
Comment: There's more stuff going on to deal with the issues you mentioned - this is just the part of the script causing problems.
Comment: @ChunkyBaconPlz could you please elaborate on how you would do this?
Comment: @CameronBall Instead of using the unreliable (and as Brad pointed out, sometimes insecure) $_SERVER variable array, use the session ID that PHP generates for each user: `$sess_id = session_id();`. Then insert `$sess_id` in your database as the unique identifier instead of their IP. An IP address is a terrible thing to use if you want to uniquely identify someone.
Comment: @ChunkyBaconPlz session_id() is empty when I call it.
Comment: @CameronBall Make sure you use session_start(); at the start of your PHP pages.
Comment: @ChunkyBaconPlz that seems to be working, however now the script just hangs when a user tries to download two files at once, instead of dieing and displaying the message. Any idea why that would happen?
Comment: @CameronBall Add some `echo` or `syslog()` calls for debugging so you can tell exactly where it hangs.
Comment: It was because PHP puts a lock on session data. So when they try download another file the script must wait for the previous file to finish before it can read session data. Calling session_write_close() straight after reading the session id solved it. I'll just have to wait now and see if session ids get stuck in the DB.
Comment: OK nope, it still doesn't work. IDs are getting stuck in there - so the issue was obviously not the IP address stuff.
Answer: The problem was that with big downloads the MySQL connection went away, I simply had to reconnect in the clear_downloader function and now it works fine.


Associative table is erroring

Question: I have a school project where I need to create a database in SQL Server. I am currently having issues entering in my tables.
I have successfully entered in the first two tables, but the associative table is erroring, as are other tables following.
create table Home
(
    HomeID INT Identity (1,1) Primary key,
    Address1 varchar(250) not null,
    City varchar(25) not null,
    State1 varchar(25) not null,
    Zipcode CHAR(5) not null,
    SmokeDetectors INT,
    Co2Detectors INT,
    SecuritySystem CHAR(1),
    TotalSqFt int,
    Rooms INT,
    AdditionalBuilding CHAR(1),
    AssessedValue DEC(10,2),
    YearAssessed char(4),
    CompanyID int not null,
)

create table MortgageCompany
(
    CompanyID INT Identity (1,1) Primary key,
    CompanyName varchar(100) not null,
    Address1 varchar(250),
    City varchar(25),
    State1 varchar(25),
    Zipcode char(5),
    HomeID int not null
)
create table HomeMortgageCompany
(
    HomeID INT,
    CompanyID INT,
    foreign key CompanyID references MortgageCompany(CompanyID),
    foreign key HomeID references Home(HomeID),
    Primary key (HomeID,CustomerID)
)

create table Loan
(
    LoanID INT Identity (1,1) Primary key,
    LoanNumber int not null,
    MortgageAmount dec(10,2),
    CompanyID int
foreign key CompanyID references MortgageCompany(CompanyID)
)

create table PersonalProperty
(
    PropertyID INT Identity (1,1) Primary key,
    ItemName int,
    Type1 varchar(150) not null,
    Value1 Dec(10,2) not null,
    HomeID int

foreign key HomeID references Home(HomeID)
)

create table Policy
(
    PolicyID INT Identity (1,1) Primary key not null,
    PolicyYear char(4),
    PremiumCharged dec(10,2),
    EffectiveDate date not null,
    ExpirationDate date not null,
    ReviewDateTime datetim,
    Decision char(8),
    HomeID int
foreign key HomeID references Home(HomeID)
)

create table Bank
(
    AccountID int Identity (1,1) Primary Key,
    BankName varchar(150) not null,
    AccountNumber int not null,
    RoutingNumber int not null,
    Amount Dec(10,2),
    PolicyID int not null
)

create table PolicyBank
(
    PolicyID int,
    AccountID INT,
    foreign key PolicyID references Policy(PolicyID),
    foreign key AccountID references Bank(AccountID),
    Primary Key (PolicyID, AccountID)
)

Create table PolicyHolder
(
    SSN char(9) Primary key not null,
    FirstName varchar(50) not null,
    LastName varchar(50) not null,
)
create table PolicyPolicyHolder
(
    SSN char(9),
    PolicyID INT,
    foreign key PolicyID references Policy(PolicyID),
    foreign key SSN references PolicyHolder(SSN),
    Primary key (SSN, PolicyID)
)
create table HomePolicyHolder
(
    SSN char(9),
    HomeID Int,
    foreign key HomeID references Home(HomeID),
    foreign key SSN references PolicyHolder(SSN),
    Primary key (SSN, HomeID)
)

create table Employment
(
    SSN char(9) Primary Key,
    EmployerFirstName varchar(50)not null,
    EmployerLastName varchar(50) not null,
    Address1 varchar(250),
    City varchar(25),
    State1 varchar(25),
    Zipcode char(5),
    StartDate date,
    CurrentSalary dec(10,2) not null,
    JobTitle varchar (75),
    RecordExtractionDate date not null,
    foreign key SSN references PolicyHolder(SSN)
)

Create table Document
(
    DocumentID INT Identity (1,1) Primary key,
    DocumentType varchar(50),
    DateTimeSent datetime not null,
    SSN char(9) not null,
    PolicyID int,
foreign key PolicyID references Policy(PolicyID)
)
create table PolicyHolderDocument
(
    DocumentID int,
    SSN char(9),
    foreign key DocumentID references Document(DocumentID),
    foreign key SSN references PolicyHolder(SSN)
);

Comment: Please post the errors.
Comment: When I tried to enter in my third table (associative table for the first two tables) it said there was a syntax error near 'CompanyID' in the line where I identified my foreign key
Comment: Copy and paste the exact error directly into your question [edit]
Comment: If it is erroring it has an error that it tells you. Why do you not tell us?
Comment: Please post the exact error so that people can provide a useful answer.
Answer: For the third table definition:
create table HomeMortgageCompany (
    HomeID INT,
    CompanyID INT,
    foreign key CompanyID references MortgageCompany(CompanyID),
    foreign key HomeID references Home(HomeID),
    Primary key (HomeID,CustomerID)
)

Problems with this code:

the column name in the defina of the foreign key needs to be surrounded with parentheses
the primary key refers to column CustomerID, but there is no column in the table

Presumably, you meant:
create table HomeMortgageCompany (
    HomeID INT,
    CompanyID INT,
    foreign key (CompanyID) references MortgageCompany(CompanyID),
    foreign key (HomeID) references Home(HomeID),
    Primary key (HomeID,CompanyID)
)

Comment: It worked!! Thank you again. You are my hero. I spent hours struggling to figure out what was wrong.
Comment: Thank you so much! I will try that. I really appreciate your help

Associative table is erroring


Canonical morphism is always monic and epic?

Question: I'm reading Manin & Gelfand's book Methods of Homological Algebra and I came to something I can't prove after several tries.
It's on page 113, II.5.11.(b) Commentary on the Axiom A4 (of Abelian Categories). There it's stated that in every category with axioms A1-A3 and such that kernels and cokernels exists, then the canonical morphism is always a monomorphism and an epimorphism.
I've been working on this but can't obtain anything. What I found is the following:
With the standard procedure, starting with a morphism $\varphi: a \to b \in \mathcal{C},$ we can obtain maps $h : I \to b$ such that $\varphi = h \circ {\tt coker}({\tt ker}\ \varphi),$ $h': a \to J$ such that $\varphi = {\tt ker}({\tt coker}\ \varphi) \circ h'$ and $\ell :I \to J$ such that $h = {\tt coker}({\tt ker}\ \varphi)\circ \ell.$ Here, $I$ is the target of ${\tt coker}({\tt ker}\ \varphi)$ and $J$ is the source of ${\tt ker}({\tt coker}\ \varphi).$
Clearly, $\ell$ is the canonical morphism associated to $\varphi.$ Further properties of the morphisms above are:

${\tt ker}\ h = {\tt ker}\ \ell,$
${\tt coker}\ h' = {\tt coker}\ \ell,$
${\tt ker}\ \varphi = {\tt ker}\ h',$
${\tt coker}\ \varphi = {\tt coker}\ h,$
${\tt ker}({\tt coker}({\tt ker}\ \varphi)) = {\tt ker}\ \varphi,$
${\tt coker}({\tt ker}({\tt coker}\ \varphi)) = {\tt coker}\ \varphi.$

Using all this properties I can't prove that ${\tt ker}\ \ell = 0,{\tt coker}\ \ell = 0.$ Could someone help me with this?
Thanks in advance!
Answer: If I understand the question properly, the answer is: It is not true that the induced morphism between the coimage and image is always a mono- and an epimorphism.
An example is the category $C$ of complete locally convex Hausdorff spaces and continuous linear maps. Kernels in $C$ are the usual null sets with the subspace topology and monomorphisms are just the injective continuous linear maps.The cokernel of $f:X\to Y$ is more subtle, it is the completion of $Y/\overline{f(X)}$, where you first need the closure of the range to obtain a Hausdorff space $Y/\overline{f(X)}$ (in the quotient topology of $Y$) which however need not be complete (it is complete if $Y$ is metrizable, but in general quotients of complete spaces needn't be complete, examples can be seen here https://mathoverflow.net/questions/57654) so that you have to take the completion.
The coimage of $f$ is thus the completion of $X/$ker$(f)$ and the image is the closure $\overline{f(X)}$ of the range.
If now $f:X\to Y$ is a morphism with closed range $f(X)$ such that $Z=X/$ker$(f)$ is not complete then the induced morphism is the unique continuous extension to the completion of the canonical map $Z\to f(X)$ which fails to be injective.
All this is discussed in an article of Kopylov and Wegner On the notion of a semi-abelian category in the sense of Palamodov (here is a link to an easily accissible version https://arxiv.org/abs/1406.6804).


Animação reversa ao tirar mouse

Question: Alguém saberia me dizer como faço a animação "ao contrario" quando tirar o mouse? Testem no link abaixo e acho que irão entender. Quando ponho o mouse, a descrição da imagem "desce", queria que quando retirasse o mouse ele "subisse"
https://jsfiddle.net/evy1oLys/
Answer: Você pode usar transition para alterar a altura do elemento no hover mais ou menos assim:

.our-works {
    z-index: 1;
}

.item-works {
    z-index: 99999;
    display: block;
    float: left;
    width: 24%;
    height: 8em;
    overflow: hidden;
    position: relative;
}

.item-works:hover .sub-works {
    display: inherit;
    overflow: hidden;
}

.item-works:hover .sub-works {

   max-height: 150px;
   transition: max-height 0.7s ease;
}

.sub-works {
  transition: max-height 0.7s ease;

    max-height: 0;
    position: absolute;
    background-color: #00aeff;
    top: 0;
    color: #fff;
    z-index: 1;
}

.link-foto {
    position: absolute;
    bottom: 0;
    left: 0;
    padding: .8em;
    text-decoration: none;
    color: #fff;
    background-color: #008bcc;
    font-weight: bolder;
}

.desc-works {
    margin-top: 1em;
    text-align: center;
}

.desc-works p {
    width: 70%;
    margin: 0 auto;
}

.img-works {
    max-width: 100%;
}

Our Works

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                        +

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                       +

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                        +

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                        +

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                        +

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                        +

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                        +

Work

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                        +

Comment: Mas aí ele fica sem aquele efeito de "bater e voltar", que era o propósito do uso de keyframes.

Animação reversa ao tirar mouse


Why does data get so tangled up in high dimension?

Question: When I look at textbooks on classification and machine learning, many of the examples focus on data that is often twisted up such as to avoid linear separation. I have an example picture below. The common description of the classification problem is that data can be twisted in this manner, and hence kernel methods or random forests are better at dealing with nonlinear decision boundaries. Of course, there is no a priori reason that datapoints should be nicely separated and linearly separable.

But I was trying to understand how the data usually gets so twisted up? First, the usual claim is that in high dimension, meaning perhaps dimensions greater than 10 or so, the distance between points becomes so big, that all points are essentially the same distance from each other. If that is the case, then I would imagine that data should not be twisted, because all the points are far from both similar points and dissimilar points.
At the same time, there is this common manifold assumption, where data generally lie on a lower dimensional manifold. But again, how would this manifold assumption reconcile with the distance issues in high dimension? As we add dimensions, points seem to become more equally distant from each other.
So I am just trying to understand how the geometry of high dimensional data evolves, given the contrast between the high dimensional distance issues versus the manifold assumption?
Comment: That is an unnaturally limited characterization.  Much of the data statisticians and analysts work with is quantitative but *not* numerical.  Regardless, the broadness of any general concept of "data" would seem to preclude the possibility of any meaningful answer to your question.
Comment: This question implicitly assumes "data" refers to some kind of general thing that can be characterized.  That's not so.  How, then, can we possibly offer any kind of universal characterization of how data behave?
Comment: @whuber , I suppose a better description is tabular data?
Comment: Almost all data traditionally analyzed in statistics ultimately is "tabular data."  Even networks are represented as (sparse) tables.
Comment: @whuber I would say that all data in statistics is numerical "array" data, since an array makes very clear restrictions on the datatypes--at least in numerical computing languages. "Tabular" does not really restrict datatypes, since a table can include strings columns and float columns, so tables cannot be manipulated mathematically in the same way that a float array can be manipulated.
Comment: Data gets *less* entangled in high dimensions. See for instance: https://en.m.wikipedia.org/wiki/Knot_theory#Higher_dimensions but also the image of the concentric circles, which you posted, would look less neat in on dimension less (unless one uses the radial distance as the dimension).
Comment: @SextusEmpiricus yes, very true. Technically the image I gave is linearly separable if I was to add a 3rd dimension. I could then just transform the red points to have a higher z coordinate, and then separate the two classes with a plane. So then is the point of showing these examples in a book that a neural network or random forest can deal with the nonlinearity while remaining in the original 2-d form. That is not explicitly stated. It is like the books show one image but mean something different.
Answer: Textbook examples are not meant to represent the likelihood of encountering particular situations. They are meant to cover a wide range, and give you the ability to recognize and solve certain special situations even if you rarely encounter it in practice.

When I look at textbooks on classification and machine learning, many of the examples focus on data that is often twisted up such as to avoid linear separation. I have an example picture below. The common description of the classification problem is that data can be twisted in this manner, and hence kernel methods or random forests are better at dealing with nonlinear decision boundaries. Of course, there is no a priori reason that datapoints should be nicely separated and linearly separable.

IMHO the keyword here is can.
I.e., "if your data looks like this, [linear won't work but] you can do as follows..."
In general, data can be whatever from easily linearly separable over complicated as in the illustration to truly inseparable.
However, we can make statements how typical data of certain types/domains/applications/tasks looks.
"My" data are mostly vibrational spectra.

For them, the physics and chemistry behind the data-generation processes mean for particular questions like medical differential diagnosis that chances are quite good that a linear separation (or at least not too complex non-linear) can be found.
In practical terms it behaves like you reason: since we typically cannot get exponentially more cases (sample size) with increasing dimensionality, the sampling density will be lower and chances are that data are less tangled. Of course, estimating class boundaries is also more uncertain because of the lower sampling density.
So it may be linearly separable in the original (≈ 1000d) space, but compressed into low dimensionality (say, 10d), class boundaries may become nonlinear.
BTW, it is typically not clear beforehand whether modeling in original or low-d projection will work better.

For other tasks such as quality control where "good" means being not too far away from the target, a (one) linear separation cannot tackle too low and too high at the same time. The data would be expected to behave more like the donut, but without a low-density region between good and bad and maybe with additional red clusters far away.
And this is expected to be true both in high dimensional original space as well as in low-d projections of it.
Comment: thanks for the response. Yes, I get what you mean. So there is this connection between the ambient dimension of the data--say 1000d--versus the intrinsic dimension (a term taken from algebraic topology) which may be say a 5 or 10d manifold. So objects can be far in ambient dimension, but closer in intrinsic dimension.
Comment: The examples you give are also helpful. Say I have an image of a horse and a noisy image of the same horse. So each pixel in the original image has a bit of gaussian noise to make the image blurry. In this case, if I take the distance between images in the ambient dimension--say 784x784, then the pictures are far apart. But if I look the distance between images in the intrinsic dimension, though should be much closer because they are basically on the same lower dimensional manifold. So the "tangling" that I am talking about is in the intrinsic dimension. Am I getting that correctly?


index.html in aws s3 displaying raw text

Question: The same index.html on laptop shows the web page correctly. aws is showing the text as is, as shown below, without rendering. Following S3 static web site hosting steps. FYI.

<title>Testing, Inc.</title>

Welcome!

Welcome to my first webpage. I am writing this page using a text editor and plain old html.

By learning html, I'll be able to create web pages like a pro....

which I am of course.

Here's what I've learned:

How to use HTML tags

How to use HTML colors

How to create Lists

Appreciate your help.
Answer: If the file's extension is not html/htm or there is no extension on the file, it will set Meta Data / Content-Type to application/octet-stream, you can update it to text/html and it will work.
Comment: I have already Content-Type set to text/html. My account is still in trial / free period. Any limitation due to this?
Comment: No nothing related to trial account, it may be related to your browset. What are you using?
Comment: You are correct! I was using chrome. Now I tried IE and it worked! But the same html loads fine in chrome in my laptop :(
Answer: For Future if anyone is reading this, if your code is not being rendered and your using windows.
In the folder that you saved your text file go to "view" then "options" click "Change folder and search options".
Then click on the "View" tab and UNCHECK "Hide extensions for know file types".
Answer: Thank you seartun and Adrian Mole.
Both contritrubted to my issue the root issue is that AWS doesnt register the file as an HTML document. I use a mac, i was using word to save my file with an HTML extension, even though it was an HTML document and AWS metadata stated it was html/text, it was still not rendering properly.
Solution for me was to use a text editor application to save my file rather than word, I used submlime text exit, and re-upload forcing the metadata to Text/HTML


Microservice cross-db referencial integrity

Question: We have a database that manages codes, such as a list of valid currencies, a list of country codes, etc (hereinafter known as CodesDB).
We also have multiple microservices that in a monolithic app + database would have foreign key constraints to rows in tables in the CodesDB.
When a microservice receives a request to modify data, what are my options for ensuring the codes passed in the request are valid?
I am currently leaning towards having the CodesDB microservice post an event onto a service bus announcing when a code is added or modified - and then each other microservice interested in that type of code (country / currency / etc) can then issue an API request to the CodeDB microservice to grab the state it needs and reflect the changes in its own local DB. That way we get referential integrity within each microservice DB.
Is this the correct approach? Are there any other recommended approaches?
Answer: Asynchronous event based notification is a pattern commonly used in micro services world for ensuring eventual consistency. Depending on how strict your consistency requirement are you may have to ensure additional checks.
Another possible approach could be to use
Read only data stores using materialized view. This is a form of CQRS pattern where data from multiple services is stored in a de-normalized form in read only data store. The data gets updated asynchronously using the approach mentioned above. The consumers gets fast access to data without having to query multiple services
Caching - You could also possibly use distributed or replicated depending on your performance or consistency requirements.


Insert data from a modal form to DB

Question: I'm trying to add some data to the DB from a modal form in django. After filling all the fields and click on submit it doesn't save on the DB. Here are the models, views and forms and the template. I think the problem it's on the views.py
models.py
class Buyer(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    phone_numbers = ArrayField(PhoneNumberField())
    industry = models.IntegerField(null=True)
    credit_limit = MoneyField(max_digits=20, decimal_places=2,
    default_currency='MMK', null=True)
    is_active = models.BooleanField(default=True)
    datetime_created = models.DateTimeField(auto_now_add=True)
    datetime_updated = models.DateTimeField(auto_now=True)

views.py
class BuyerCreateView(AtomicMixin, View):
template_name = 'add_buyer_modal.html'

def get(self, request):
    form = BuyerForm()
    return render(request, self.template_name, {'form': form})

def post(self, request):
    form = BuyerForm(request.POST)
    if form.is_valid():
        form.save()
        messages.success(request, 'Buyer created!', extra_tags='alert alert-success')
        return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
    messages.error(request, 'Unable create buyer. {}'.format(form.errors), extra_tags='alert alert-danger')
    return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))

forms.py
class BuyerForm(forms.ModelForm):
    class Meta:
        model = Buyer
        fields = ['name', 'phone_numbers', 'industry', 'credit_limit']

template

New Buyer

            <button type="button" data-dismiss="modal" aria-label="Close" class="close">
                ×
            </button>

            <form id="buyer-form" method="post" class="submit-form" action="{% url 'buyers:add_buyer' %}">
                {% csrf_token %}

                        Name
                        <input autocomplete="false" type="text" name="name" class="form-control" required>

                        Industry

                            <input autocomplete="false" type="number" name="industry" class="form-control" required>

                <input id="payment-submit" type="submit" class="btn btn-primary pull-right submit-button" />
            </form>

urls.py
urlpatterns = [
url(r'^$', buyers_views.BuyerListView.as_view(), name='buyers_list'),
url(r'^(?P<id>[0-9a-f-]+)/$',
    buyers_views.BuyerDetailView.as_view(), name='buyers_detail'),
url(r'^/buyer/add/', buyers_views.BuyerCreateView.as_view(), name='add_buyer'),

]
Comment: can you post your *template* `add_buyer_modal.html` as well?
Comment: Sure, I edited the question
Comment: I see that  the form is pointing to `buyers:add_buyer`, are you sure that that url is actually linked to the view?
Comment: Yes.. You can see it on the urls.py that I published now
Comment: I don't think you're rendering a  bound `BuyerForm` on the template. What are the contents of `POST`?
Answer: Check to see if your form is invalid. You only fill out 2 of the 3 fields in the HTML form and send it back to the server. Therefore, when you check to see if the form.is_valid(), it's probably returning False and therefore, not actually saving the form.
To check, you can put a print statement inside the if statement printing out 'success' and one after the if statement printing out 'failure'. If you don't see the 'success' print out, it means your form is invalid.
If this truly is the issue, add form fields in the HTML for all fields in your form. Any field you include in the fields attribute of a form by default is required. This means that if the field isn't filled out when calling is_valid on the form, a validation error for that field will be thrown.

Insert data from a modal form to DB


How to update DataGridView cell in c#

Question: I have a DataGridView in c# WinForms
In this form I fill a big DataGridView with data, the process behind takes long time.
anyway, my issue is that I want to update one cell in that DataGridView based on criteria
DataGridView has 4 columns, StNo, StName, StAge, StMark.
I want to search for StNo = 123 and update their StMark to be 68
I tried the following but does not work
grd1.Rows.Cast<DataGridViewRow>().Where(x => x.Cells["StNo"].Value.ToString() == "123")["StMark"] = 68;

How to do that?
Comment: First, use a `DataTable` and set it as your DataSource, don't directly access the `DataGridView`. Then, see here: [How to Edit a row in the datatable](https://stackoverflow.com/q/19629644)
Comment: Is there a way to update the datagridview?
Comment: If you set a DataTable as your DataSource and update it, your DataGridView will automatically update.
Comment: You should follow @Fabio 's answer. You will need to break the current (invalid) one line of code into two (2) steps. You need to make sure that when the query returns the results from `Where(x => x.Cells["StNo"].Value.ToString() == "123"` … that "something" is actually returned. Using your approach assumes that "something" is always returned. The code MUST check for the case when nothing is returned. Otherwise, a null exception is guaranteed. You can apply this same idea to the grid or the grids data source.
Answer: DataGridView is a winforms control which responsible for displaying given records in UI and provide user's input to the underlying records via different events.
So instead of updating values via DataGridView - update underlying records.
public class Student
{
    public int Number { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public int Mark { get; set; }
}

public class MyForm
{
    public readonly BindingList<Student> _sutdents;

    public MyForm()
    {
        _students = new BindingList<Student>();
        myDataGridView.DataSource = _students;
    }

    private void AddStudentButton_Click(object sender, EventArgs args)
    {
        var student = new Student
        {
            Number = int.Parse(textboxNumber.Text),
            Name = textboxName.Text,
            Name = int.Parse(textboxAge.Text),
            Name = int.Parse(textboxMark.Text),
        };

        _students.Add(student);
    }
    // After button click you should see that new student appears in the DataGridView

    // Now you can update existing students from code without "touching" DataGridView
    private void UpdateMarkButton_Click(object sender, EventArgs args)
    {
        var studentNumber = int.Parse(textboxNewMarkStudentNumber.Text);
        var newMark = int.Parse(textboxNewMark.Text);

        var student = _students.FirstOrDefault(s => s.Number = studentNumber);
        if (student != null)
        {
            student.Mark = newMark;
        }
    }
}

Answer: Your life, made easy:

add a new DataSet file to your project, open it, name it StudentDataSet in the property grid
right click, add a new DataTable to the surface, name it Students
add columns of StNo (make it an int in the property grid), StName, StAge (int), StMark (int)
right click StNo and make it a primary key
save
switch to the form designer, open the Data Sources panel (view menu.. other windows)
drag the node representing the table, onto the form. A datagridview appears

Now the code you need for updating a Mark is:
var s = studentDataSet.Students.FindByStNo(123);
if(s!=null)
  s.StMark = 99;

Yes, that's all you need (plus you need to load the table with student data)

If these students come out of a database, you can make your life easier in the second step by not adding a DataTable but instead adding a TableAdapter and setting up the db connection/query that pulls them out of the db..

How to update DataGridView cell in c#


Busca sem retornar dados PDO

Question: A minha variável esta  sendo passada porem no processo de filtro sempre não esta retornando nada.
try
{
   $keyword = trim($_GET["keyword"]);
   if (!empty($keyword))
   {

       $sql = "SELECT * FROM noticias WHERE
         titulo LIKE :keyword OR conteudo LIKE :keyword ORDER BY Nid";

       $stmt = $DB->prepare($sql);

       $likekeyword = "%".$keyword."%";
       $stmt->bindParam(':keyword', $likekeyword, PDO::PARAM_STR);

   }
   else
   {
       $sql = "SELECT * FROM noticias WHERE 1 ORDER BY Nid ";
       $stmt = $DB->prepare($sql);
   }

   $stmt->execute();

tentei (titulo LIKE :termo) OR ...
Atualizado o estranho e que o resultado do if empty em branco ta funcionando o que me leva a crer que e na parte de consulta mesmo
Comment: O problema está na consulta e não no php. A ideia é buscar por `%:key%` ? faz um sqlfiddle e coloca o link na pergunta e as consultas que não funcionaram.
Answer: Creio que o seu problema se resolva dessa maneira:
try {
     $termo = trim($_GET["termo"]);
      if (!empty($termo)) {
$sql = "SELECT * FROM noticias WHERE titulo LIKE :termo OR conteudo LIKE :termo ORDER BY Nid";
$stmt = $DB->prepare($sql);

$likeTermo = "%".$termo."%";
$stmt->bindParam(':termo', $likeTermo, PDO::PARAM_STR);
...

Considere estas diferenças:

PDOStatement::bindValue() -> A variável está vinculada à referência e só será avaliada no momento em que o PDOStatement::execute() for chamado. E neste caso, só é aceito valores como argumento.

Se você usar $stmt->bindValue(":termo", $termo);.
O valor deverá existir obrigatoriamente, senão ocorrerá um erro.

PDOStatement::bindParam() -> Já neste caso, o argumento esperado é uma referência (variável ou constante) e não pode ser um tipo primitivo como uma string ou número solto, retorno de função ou método.

Exemplos inválidos:
$stmt->bindParam(':termo', 10); // Inválido
$stmt->bindParam(':termo', getValue()); // Inválido

Comment: Quando você usa like, o símbolo % representa qualquer ocorrência, se estiver á esquerda (%abc) qualquer ocorrência que comece com  "abc", na direita usando abc%, significa qualquer ocorrência que termine com "abc". também pode usar _  como curinga de caráter único. Use os curingas para fazer a consulta. a propósito, essa consulta que você fez tratando `...LIKE audio ...` a palavra audio, sem aspas não é um termo de pesquisa, ele entra como um valor "null".
Comment: infelizmente nao continua retornando nada, ja havia tentado algo assim antes, testei denovo pra ter certeza porem o resultado e o mesmo
Comment: quanto a diferenca do param e value entendi , obrigado pela dica porem ainda continua sem os resultados, atualizei o codigo
Comment: talvez o problema não esteja neste trecho. E sim na saída, o que acontece quando você dá um `var_dump($stmt->execute())` ?
Comment: E o que acontece quando vc executa essa query com o termo direto no workbench ou phpmyadmin?
Comment: bool(true)  retorna verdadeiro , exibe a mensagem que programei ( nenhuma busca foi encontrada)  e tenho so nos titulos 3 resultados das palavras que busquei
Comment: quando você executa: `SELECT * FROM noticias WHERE titulo LIKE '%a%' OR conteudo LIKE '%a%' ORDER BY Nid` no workbench, o que retorna?
Comment: rapaz executei o seguinte: SELECT *
FROM `noticias`
WHERE titulo LIKE audio
OR conteudo LIKE audio
ORDER BY Nid
LIMIT 0 , 30

e o resultado foi incrivel

http://prntscr.com/8ow940

 Pode isso arnaldo?...
Comment: qualquer coisa veja, se os parâmetros estão sendo processados: `$stmt->debugDumpParams();` ao final do `...->execute()`
Comment: SQL: [88] SELECT * FROM noticias WHERE titulo LIKE :keyword OR conteudo LIKE :keyword ORDER BY Nid Params: 1 Key: Name: [8] :keyword paramno=-1 name=[8] ":keyword" is_param=1 param_type=2  resultado .. mais como to começando em pdo nem sei do que ta falando, esses param são as variaveis? ou campos?
Comment: Olha aqui do que se trata, é para você verificar sua query: http://php.net/manual/en/pdostatement.debugdumpparams.php
Comment: rapaz descobri uma coisa se eu pesquiso por "a" ele me retorna o resultado cujo a primeira letra do conteudo é "a" . me parece estar so verificando a primeira palavra
Answer: Caro amigo, não sei se existem aí mais erros, mas, deste bocado de código que aí tens, vejo apenas uma irregularidade capaz de causar este problema, que é o número de parâmetros vinculados através do bindParam. Na tua consulta SQL foste bem específico fornecendo dois placeholders, com os nomes :titulo e :conteúdo, porém durante a parte em que vinculavas os valores desses respectivos placeholders, passaste apenas um.
Veja algumas correções que apliquei ao teu script:
Exemplo:
<?php

// Valores Extrnos
$key = isset($_GET["keyword"]) ? trim( (string) $_GET["keyword"]) : NULL;

// Conectar PDO
try{

    $opc = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
    $pdo = new PDO("mysql:hostname=localhost;dbname=banco_de_dados;", "root", "", $opc);

    //$sql = "SELECT * FROM noticias WHERE titulo LIKE :titulo OR conteudo LIKE :conteudo ORDER BY id ASC";
    $sql = "SELECT * FROM noticias WHERE titulo LIKE :titulo OR conteudo LIKE :conteudo ORDER BY Nid";
    $stmt = $pdo->prepare($sql);

    $key = "%" . $key . "%";

    $stmt->bindParam(":titulo", $key, PDO::PARAM_STR);
    $stmt->bindParam(":conteudo", $key, PDO::PARAM_STR);
    $stmt->execute();

    // Capturar exceção, se haver uma
    } catch(PDOException $e){
    echo "Erro: " . $e->getMessage();
}

// Resultados
if(isset($stmt)){
    while($linhas = $stmt->fetch(PDO::FETCH_OBJ)){
        echo  $linhas->titulo . "
";
        echo  $linhas->conteudo. "
";
    }
}

?>

NOTA: Trabalhar com o PDO, requer alguns cuidados, e reparei também que nesta parte do teu script, tens o try, mas não vi a parte catch onde deve-se capturar a exceção, caso haja alguma.

Referências:
PDO::bindParam - PHP.net
Exceptions - PHP.net
Catch - PHP.net

Busca sem retornar dados PDO


Practical example of a non-measurable maximum likelihood estimator

Question: This post gives an example of a situation where the MLE is not measurable. However, this doesn't seem to be a situation that you would ever encounter in practice.
Is there a more practical example of a situation where the MLE is not measurable? To be more specific, is there an example that does not rely on the axiom of choice? If such an example exists, and we happen to be put in a situation where we want to estimate a parameter, but the MLE is not measurable, what should we do?
Answer: So I think whether or not an example is practical is a little ambiguous. However, with regard to the axiom of choice (AC), I think the answer is no. That is, if we want to construct an example in which $\hat\theta$ is non-measurable this will require AC. The reason for this is simply that in order to construct a non-measurable set of real numbers we need to employ AC. And, of course, we will need a non-measurable set inside our measure space to construct a non-measurable function.
Interestingly, my understanding is that while we cannot construct an example without AC it is still possible that a non-measurable $\hat\theta$ could exist! The reason for this is that the existence of a non-Lebesgue measurable is consistent with Zermelo-Fraenkel (ZF) axioms. That is, a non-measurable set does not imply AC. I don't think this really answers your question about practicality but it is an interesting point (assuming my reading is correct).
So what do we do about this? Well, I am going to give a bit of a dodging :) answer here. One of the more classical assumptions in MLE is that $\Theta$ is compact and the criterion is continuous in $\theta$. This will be enough for the measurability of $\hat\theta$. Another possibility is to work with outer probability measures when generalizing to the case of extremeum estimators (there is an example of this generalization in Chapter 5 of Van der Vaart (1998)). Specifically, we will relax uniform convergence to,
$$P^*[\sup_{\theta\in\Theta} |\hat Q(\theta)-Q(\theta)|>\epsilon]\to 0$$
a.s. in outer probability. where each of these events $\{\sup_{\theta\in\Theta} |\hat Q(\theta)-Q(\theta)|>\epsilon\}$ need not be measurable. But this only lets us bypass measurability issues as we approach the limit. It seems that as long as $(\Theta, \mathcal{A})$ is a separable measurable space then that is enough to guarantee measurability.
Comment: First, thank you for your thoughtful response. About your first point, what if we consider a situation where the sample space is not the real numbers? One practical scenario is if our statistical experiment involves, say, tossing a coin and throwing a die. Suppose that we know the probability of the coin landing on heads, but we do not know any of the probabilities regarding the die (and our sigma field reflects this). Then the indicator function of whether a "1" was rolled will not be measurable. Perhaps in a situation such as this, we could come up with a non-measurable MLE?
Comment: I fail to see how this random variable would be [non-measurable](https://en.wikipedia.org/wiki/Non-measurable_set). This is simply an event whose probability we do not know.
Comment: That wikipedia article seems to be referring to Lebesgue measurability. I'm talking about measurability in general; see for example, section 13 and section 20 of Probability and Measure by Billingsley. Given an arbitrary probability space $(\Omega, \mathcal{F}, P)$, a random variable is a function $X: \Omega \rightarrow \mathbb{R}$ that is measurable $\mathcal{F}$.
Comment: In my example above, I can simply define $\Omega = \{(H, 1), (T, 1), (H, 2), (T, 2), \dots ,\}$ and $\mathcal{F}$ so that it contains $\{(H,1),(H,2), \dots, (H,6)\}$ (the event that heads is flipped) but not $\{(H,1), (T, 1)\}$ (the event that "1" is rolled), for example. I'm wondering if we can come up with a probability model such that the MLE is not $\mathcal{F}$ measurable.
Comment: You can obviously define a $\sigma$-algebra that will not include some set. However, notice that this is not the procedure that we use in MLE or when we define random variables. Rather we use the $\sigma$-algebra **generated** by the random variable. In your example, this would of course be included as the union of $(H,1)$ and $(T,1)$.


How can I get the complete query?

Question: I am displaying a Drupal 8 view. I see that all of the fields that are displayed in the view are not in the query.
How does this work?
Answer: For query tracing you can use devel module. Devel module include the Web Profiler module which shows many options. Even you can see the all queries executed for page.
Following are the sample details of web profiler.

UPDATE: So how you can see your view query in web profiler?
Well, follow this steps.

For tracing purpose disable view cache. "Select 'No Cache' from advance section".
Then Clear all drupal cache.
Open views output page.
Click on database link from web profiler.
Now search in page(Ctr+F) your field name.
E.g: Here I added one field in my view, that is field_image. So I search that and I get view query..
Once you found out your query, you will see there is no parameter in query, Well to see which paraters query is taking click on "Info" tab of query. And you will see all parameters of placeholder.
Comment: hi how exactly can i use this webprofiler in connection with the view to see the query ?
Comment: Please check updated answer, I added how to check view query in web profiler.

How can I get the complete query?


Url amigável em ASP.NET Web Forms

Question: Gostaria de saber como fazer URL amigável em C# ASP.NET.
Tentei usar no arquivo: global.asax mas não funcionou.
Comment: É para uma aplicação nova ou ja existe? É baseado em Web Forms ou MVC?
Comment: @Intruso obrigado por responder, a aplicação já existe e é baseada em Web Forms
Answer: De fato, não é pelo Global.asax apenas que se faz isso. É preciso instalar este pacote primeiro.
Instalado isso, você precisa colocar a linha abaixo no seu Application_Start:
RouteConfig.RegisterRoutes(RouteTable.Routes);

Deve ser criado um arquivo chamado App_Start/RouteConfig.cs. Dentro dele, deve haver um método em que a seguinte linha deve existir:
routes.EnableFriendlyUrls();

Assim sendo, se você tem um arquivo chamado Teste.aspx na raiz, com esta configuração, Teste.aspx será chamado como /Teste.
Mais informações? Veja aqui.
Comment: @Furlan, se precisar, dentro do `RegisterRoutes(RouteCollection routes)` você pode registrar outras rotas usando o `routes.MapPageRoute`, a MSDN tem vários exemplos a respeito: [How to: Define Routes for Web Forms Applications](https://msdn.microsoft.com/en-us/library/cc668177.aspx)

Url amigável em ASP.NET Web Forms


PDE problem: how to show that it can have a unique solution

Question: I have a problem with this exercise:
Consider the following system of coupled first-order nonlinear partial differential equations for the scalar-valued function $u=u(x,y)$:
$a\frac{\partial u}{\partial x}+b\frac{\partial u}{\partial y}=f(x,y,u)$
$c\frac{\partial u}{\partial x}+d\frac{\partial u}{\partial y}=g(x,y,u) $
$(*)$
Here $a$, $b$, $c$ and $d$ are given smooth functions of $x$ and $y$ and we assume that  $ab-dc$ $\neq$ $0$ for all $(x,y)$ in $\mathbb{R}^2$.
Show that the system has a unique solution for all initial data $u(x_0,y_0)=u_0$ if and only if
$[\mathbb{V},\mathbb{W}]=r\mathbb{V}+s\mathbb{W}$, $(**)$
where $\mathbb{V}$ and $\mathbb{W}$ are the vector fields on $\mathbb{R}^3$ given by
$\mathbb{V}(x,y,z)=(a(x,y),b(x,y),f(x,y,z))$ and $\mathbb{W}(x,y,z)=(c(x,y),d(x,y),g(x,y,z))$
for some functions $r(x,y,z)$ and $s(x,y,z)$
Now my problem is that I don't know where to start, I tried to use the Froebinus theorem but without suceed. I don't manipulate well PDE and it doesn't help me. Please can you explain me how to really understand this exercise ?
Regards,
Herosix
Answer: Well, it seems to be true. The scheme of the proof is the following.
Let us suppose that $a \equiv 1, b \equiv 0, c \equiv 0, d \equiv 1$. We can always achieve it by solve the equation explicitly (I believe that you made a type and the determinant of the system is not null). Thus, let us consider the system
$\frac{\partial u}{\partial x}=f(x,y,u)$
$\frac{\partial u}{\partial y}=g(x,y,u) $
The formal condition of solvability of the equation above is
$\frac{d f}{d y} = \frac{d g}{d x}$, or
$\frac{\partial f}{\partial y} + g\frac{\partial f}{\partial z} = \frac{\partial g}{\partial x} + f\frac{\partial g}{\partial z}$
$(1)$
On the other hand, if we compute Lie bracket of the fields $\mathbb{V} = (1, 0, f)$ and $\mathbb{W} = (0, 1, g)$ (see https://en.wikipedia.org/wiki/Lie_bracket_of_vector_fields for example) we will come to
$[\mathbb{V},\mathbb{W}]=(0, 0, \frac{\partial g}{\partial x}-\frac{\partial f}{\partial y}+f\frac{\partial g}{\partial z}-g\frac{\partial f}{\partial z})$
It is easy to see that it is equal to $r\mathbb{V}+s\mathbb{W}$ IFF $r\equiv0,s\equiv0$ and (1) is satisfied (please see also http://www.math.tamu.edu/~jml/EDSpublic.pdf  Example 1.2.3)
P.S. I believe it is possible to do similar direct calculation for arbitrary $a, b, c, d$ functions. It might be pretty cumbersome but finally will lead you to correct result. I also believe that there exists more nice "modern" way to prove it :)


R command multcompBoxplot with two plots side by side

Question: I ran into a little problem when using the multcompBoxplotfunction in the multocompView package. What I am trying to do is to put two box plots side by side from multcompBoxplot command. I use par(mfrow=c(1,2) and it did not work. Could anyone give me some advice how to deal with this? Here is an example from the multocompView website.
library(multcomp)
par(mfrow = c(1,2))
data(cholesterol)
cholesterol$trt3 <- with(cholesterol, factor(
  as.character(trt), levels=levels(trt)[c(5:4,1:3)]))
multcompBoxplot(response ~ trt3, cholesterol,
                sortFn=NULL)
multcompBoxplot(response ~ trt3, cholesterol,
                sortFn=NA)

Answer: Is this what you are looking for?
Then use boxplot instead of multcomBoxplot
library(multcomp)
data(cholesterol)
cholesterol$trt3 <- with(cholesterol, factor(
  as.character(trt), levels=levels(trt)[c(5:4,1:3)]))

par(mfrow = c(1,2))
boxplot(response ~ trt3, cholesterol,
                sortFn=NULL)
boxplot(response ~ trt3, cholesterol,
                sortFn=NA)

Comment: I try to put two box plots in a same figure. Like the one you show above, I want put another boxplot next (or under) the same figure. Like what the par(mfrow=c(1,2)) does.
Comment: Thank you for your response. I know how to do with the normal box plot with the par(mfrow). I really want to know is if there is a way to apply this kind of technique with the multcompBoxplot function.


GameplayKit: Stop Pathfinding When Path Is Blocked By Certain Obstacles

Question: I have a SceneKit project into which I'm trying to integrate GameplayKit's 2D pathfinding capabilities.
What I have are 2 different kinds of obstacles (let's call them "good obstacles" and "bad obstacles"). The main character can touch the good ones, but not the bad ones (or it's level failed).
What I need GameplayKit to do if there's a "bad obstacle" in the way of the path is to stop pathfinding and notify me that the process failed.
How might I accomplish this?
Here's some code to illustrate that I do have pathfinding working -- minus the desired behavior, of course:
var obstacles = [GKPolygonObstacle]()

//Manually plot a set of points around the circumference of a circle...
//...for use in creating the obstacle (because I was unable to get `GKCircleObstacle` working)
let pegRadius: Float = 0.15
let numOfPoints = 12
let totalRadians: Float = 360.0 * .pi / 180.0
let radiansPerPoint: Float = totalRadians / Float(numOfPoints)
var polyPoints = [SIMD2<Float>]()
for i in 0..<numOfPoints {
   let angle = radiansPerPoint * Float(i)
   let x = pegPosition.x + (pegRadius * cos(angle))
   let y = pegPosition.y + (pegRadius * sin(angle))

   polyPoints.append(SIMD2(x: x, y: y))
}

//Create the obstacle:
let obstacle = GKPolygonObstacle(points: polyPoints)

obstacles.append(obstacle)

let graph = GKObstacleGraph(obstacles: obstacles, bufferRadius: 0.05)

//Grab the nodes that will act as "to" and "from":
let receptors = scnView.scene?.rootNode.childNodes(passingTest: { theNode, stop in
     return theNode.name == "receptors"
}) as? [SCNNodeIdentifiable]
var receptorIndex: Int = 0
guard let receptors = receptors else {
     return
}

var startPointVector = vector_float2(x: Float(receptors[receptorIndex].presentation.worldPosition.x), y: Float(receptors[receptorIndex].presentation.worldPosition.y))
let endPointVector = vector_float2(x: Float(receptors[receptorIndex+1].presentation.worldPosition.x), y: Float(receptors[receptorIndex+1].presentation.worldPosition.y))
var startingPoint = GKGraphNode2D(point: startPointVector)
let endPoint = GKGraphNode2D(point: endPointVector)

graph.connectUsingObstacles(node: startingPoint)
graph.connectUsingObstacles(node: endPoint)
var path = (graph as GKGraph).findPath(from: startingPoint, to: endPoint)

if path.count >= 2 {
   //Path found! Do something.
} else {
   //I'd like to end up here if there's a "bad obstacle" in the way of the pathfinding
}

I suspect that the answer has to do with GKRule and GKRuleSystem, but I could use some input.
Thanks for your help!
Answer: So, according to the documentation, the correct way to handle this is to subclass GKGraphNode2D and override the cost(to:) method, which the findPath methods use in constructing a path through the graph.
On cost(to:), the docs say the following:

"Subclasses can implement this method to add other information to the
cost. For example, a game might use higher costs to represent travel
through regions of a map that are difficult for a character to
traverse."

Unfortunately, it appears that this is totally broken and does not work.
Consider the following attempt at making "bad" obstacles have a higher cost than "good" ones:
class MyGraphNode2Dsubclass: GKGraphNode2D {
    var isBadObstacle: Bool = false

    override func cost(to node: GKGraphNode) -> Float {
       isBadObstacle ? 10.0 : super.cost(to: node)
    }

}

When it gets to super.cost(to: node), I get an EXC_BAD_ACCESS crash 100% of the time.
Now, what I can do is this:
class MyGraphNode2Dsubclass: GKGraphNode2D {
    var isBadObstacle: Bool = false

    override func cost(to node: GKGraphNode) -> Float {
       isBadObstacle ? 10.0 : 0.1
    }

}

But that results in all "good" obstacles having the same cost of 0.1 instead of having their true costs, so it's not a good solution.
Obviously, if the cost system of GameplayKit doesn't really work, then GameplayKit itself doesn't really work.
There are some other questions from years past that might involve this same problem -- but I'm not sure. They might be describing something a bit different, but on the same topic.
Of course, it's also possible that I've misunderstood this problem -- so please let me know if that's the case.


Is the path_alias table queried for all URLs?

Question: I'm trying to generate SEO-friendly URLs for a set of exposed filters. For e.g.:
/analyst-relations/firm?related_firm=5072 would look like
/analyst-relations/firm/forrester
one way I imagined doing it was by adding/updating/deleting this path programmatically to the path_alias table upon creation/modification/deletion of the relevant term or entity. However I seem to have misunderstood how path_alias works. I was able to successfully add the path /analyst-relations/firm?related_firm=5072 and the alias /analyst-relations/firm/forrester, but the exposed filter links still load like the former. Is the path_alias table not queried for all URLs? If not, is it possible to somehow 'attach' this path and alias to an entity?
EDIT:
I'm using Better Exposed Filters to exposed the filters as  links, so afaik there is no form submission
Comment: Wasting your time, the Google spider/crawler isn't going to fill out your exposed filter form and then index that.
Comment: Enjoy the pointless implementation, [Changing url of exposed filter](https://drupal.stackexchange.com/questions/22989/changing-url-of-exposed-filter)
Comment: Not to pile on or anything, but this is almost definitely a waste of time. The most up to date SEO advice, which hasn't changed for years in this case, is to add `rel=nofollow` to links that filter lists of content, and even meta canonical and noindex tags to the filtered pages themselves. This helps to avoid duplicate content penalties, and allows search engines to be more confident that they've chosen the "correct" (read: unfiltered) version of a page to show people. All of this makes the URL completely moot.
Comment: Even if its misplaced, this is a project requirement so I don't have much of a choice
Comment: I found this awhile back, was hoping something might have changed over the past 8 years
Answer: While @Clive's comment is in most cases correct, from a SEO perspective it can make sense to expose certain filters as links and make them searchable through Google. Path aliases are implemented in AliasPathProcessor. Since the core alias lookup system can't handle query parameters and you can alias without a lookup table by querying the entity data directly, you could add your own path processor. Inbound you have to change the path to the internal path and add the query parameter to the request, outbound vice versa (but use $options to remove the query parameters because this is for all outgoing links, don't use the request).
Comment: Thanks @4k4 I'm exploring this now. Would this be an additional AliasPathProcessor that only runs on the URLs in question, or would this be a new AliasPathProcessor that extends and replaces the existing one? In the former case I imagine constructing and calling it in an EventSubscriber after matching on the request URI. Thoughts?
Comment: No, you don't need to replace the core AliasPathProcessor, just add your own and catch paths you are interested in. It's not an event subscriber but a tagged service `path_processor_inbound`/`path_processor_outbound`. Check `core.services.yml` and you get the idea how to put the service in `mymodule.services.yml`.
Comment: It appears I `implements InboundPathProcessorInterface, OutboundPathProcessorInterface` and add this in services.yml: `    tags:
      - { name: path_processor_inbound, priority: 100 }
      - { name: path_processor_outbound, priority: 300 }` Does that make sense 4k4? It appears to be firing on any page load now without explicitly executing it somewhere
Comment: Yes, this is OK. Now you can check the path for `/analyst-relations/firm/*`, process the path and set the query parameter. Similar to [PathProcessorFiles::processInbound](https://api.drupal.org/api/drupal/core%21modules%21system%21src%21PathProcessor%21PathProcessorFiles.php/function/PathProcessorFiles%3A%3AprocessInbound/8.8.x)
Comment: So just to test i did this `$request->query->set('related_firm',5366);` but the page still 404's. My reasoning for this is because while the query is set, the pathInfo/request URI likely still needs to change (the correct Request would have a path of analyst-relations?related_firm=5366, not analyst-relations/firm/*?related_firm=5366) However `$request = Request:Create(...)` wont work because its not passed by reference. Any ideas on setting a new pathInfo/requestURI ?
Comment: No, the processed path is different from the original path. The relation between both and the processed request object are cached by the way and re-used for all future requests of the same URL.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/107738/discussion-between-plambre-and-4k4).


Passar matriz de structs como argumento

Question: Tendo o struct
struct bloco {
    bloco () : real(), marcado('.'){}

    char real;
    char marcado;
};

Quando eu tento
void tabuleiro (int lado, int mina){
    ...
    bloco tab[lado][lado];

    ...

    for (i=0, j=0; lado>i; i++){
        for (j=0; lado>j; j++){
             tab[i][j].real = '.';
        }
    }

    ...

    jogar(tab[lado][lado]);

    return;
}

E na função jogar eu tenho
void jogar(bloco tab){
    tab[x][y].marcado = 'M';
}

Eu recebo a mensagem

no match for 'operator[]' (operand types are 'bloco' and 'int')
     tab[x][y].marcado = 'M';

Até onde entendi, isso quer dizer que eu nao passei "tab" como sendo uma matriz, então eu tentei resolver com:
void jogar(int lado, bloco tab[lado][lado]){
    tab[x][y].marcado = 'M';
}

Que me deu a seguinte mensagem

error: use of parameter 'lado' outside function body
   void jogar(int lado, bloco tab[lado][lado]){

Eu só queria passar a matriz de structs criada em uma função pra alterá-la na outra, mas não sei como :(
Answer: O segundo erro que você recebeu é porque você precisa passar um tamanho constante dentro dos colchetes na declaração do parâmetro. "lado" não serve, pois também é um parâmetro. Mesmo que fosse, lado não é uma constante ou expressão constante, então não pode ser usado como dimensão da matriz.
Ou seja, você vai ter que fixar o tamanho da sua matriz e, uma vez fixado, fazer algo assim:
void jogar(bloco tab[][ALTURA]) { ... }

Aparentemente, isso não se encaixa nos seus requisitos, então você pode usar std:vectors, que são de tamanho dinâmico. std::vector de std::vector, no seu caso.
Comment: Muito obrigado! Eu usei `vector  > tab(lado, vector(lado));` e resolveu meus problemas de compilação. Agora surgiram outros de lógica, mas esses eu posso resolver com um pouco de estudo!

Passar matriz de structs como argumento


Networkmanager nmtui static IP/ external IP / public IP address

Question: For long time try to setup my external IP address on centos7,rocky on with "Networkmanager" but its working only with systemd-networkd.
Found some solution and use systemd-networkd but now after update to rocky 9.2 i cant use systemd-networkd anymore.
[Match]
#this is just works
Name=eth1

[Network]
Gateway=XXX.XXX.XXX.XXX
Address=XXX.XXX.XXX.XXX/29
DNS=22.214.171.124

is now 2023 and i am not able still make static external IP to work
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:03:6f:26 brd ff:ff:ff:ff:ff:ff
    inet XXX.XXX.XXX.XXX/32 scope global noprefixroute eth1
       valid_lft forever preferred_lft forever

if use /32 is not add brodcast but in diffrent distro like debian is show brd with no issue and its work

when use /29 its show correct br but still is not working

use command ip addr add XX.XX.XX.222/29 br XX.XX.XX.223 dev eth1 or ip addr add XXX.XXX.XXX.222/32 br XXX.XXX.XXX.222 dev eth1
still fail

on windows its working, debian,centors with systemd-networking is working so its just a redhat crap networkmanager
Comment: What is not working? Why do you expect it to work?
Comment: @vidarlo necause  systemd-networkd was working with no issue
Answer: Your XXX.XXX.XXX.223 is the broadcast address, you cannot use this as IP-address for your machine. (as shown in your screenshot from nmtui).
Use XXX.XXX.XXX.222/29 as address and it should work fine.
If for some reasons not.. try editing the network-script file manually:
/etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
DNS1=22.214.171.124
DNS2=184.108.40.206
NETMASK=255.255.255.248
IPADDR=XXX.XXX.XXX.222
GATEWAY=XXX.XXX.XXX.217

restart the netwerk services systemctl restart network (or reboot the whole machine systemctl reboot).
Hope this helps.
Comment: that correct: Gateway: XX.201.XX.217 Netmask: 255.255.255.248 Broadcast: XX.201.XXX.223 but (Redhat) rockylinux 9.2  remove systemd-network and that suck because now can't use it and have to use networkmanage that never works for me on any Os like debian,centos,ubuntu,rocky
Comment: allright, I've never used the systemd-network, as explained earlier, you can set the config in the `/etc/sysconfig/network-scripts/` folder which works fine.
in any other case, I suggest to read the [rocky9 manual](https://docs.rockylinux.org/guides/network/basic_network_configuration/).
Comment: `dnf install systemd-networkd` might do the trick for you.

FYI
Network-Manager exists since RHEL6, it will follow-up the older ifcfg in the next RHEL releases, as Network-Manager is more flexible.

It might be the default in the next Ubuntu too, combined with netplan.
Comment: my bad i was try do yum install systemd-networkd  and dnf install systemd-networkd just work for me thx -- also instrall dnf install systemd-resolved do like on this urtoial and its working https://www.addictivetips.com/ubuntu-linux-tips/set-up-systemd-networkd/


Comments field displays only plain text

Question: I have a Drupal 7 site where people might want to put code snippets in a comment.  I have the geshi module set up for syntax highlighting.
I have an article node set to the Full HTML text format, and some code snippets.  The article is displayed properly, the code is highlighted.
I have created a comment on the article with the text format also set to Full HTML, and some code snippets.  The comment displays the literal html code, as if the text format is plain text or something.  I have BUEditor and Ajax markup installed, and the preview they give me shows it highlighted.  But Drupal's preview is consistent with the real output.
I've tried googling for this problem, but between most people wanting the opposite and the term comment being on pretty much every webpage these days, I couldn't find anything.
Answer: I was doing the following:
    <csharp>line1
    line2
    line3</csharp>

Those extra 4 spaces in the beginning made Markdown put that in a
, and then geshi still processed the csharp block.  Taking out the spaces in the beginning made it work correctly.

Comments field displays only plain text


Will it be correct to intregrate when answer comes in via square roots since they can be positive or negative?

Question: I tried to find the integral of the function
$$\int_0^2x(x+2)^\frac{1}{2}dx$$
I substituted $$x+2=t^2$$ but while converting limits I found $t=2,-2$ as upper limit. When integrating with these different limits I get different answers while the correct is with only positive one? Why can't the one with negative one be correct?
If I do the same for the lower limit, the same situation arises.
Comment: The substitution is either $x+2=t^2$ where $t\ge 0$, or where $t\le 0$. We are really setting $t=\sqrt{x+2}$ or $t=-\sqrt{x+2}$. Of course I prefer plus, but whichever you want to use is OK as long as you are consistent.
Comment: That you get the same answer either way is what I showed in my answer posted below. ${}\qquad{}$
Answer: $$
\int_0^2x(x+2)^{1/2}dx
$$
If $t^2 = x+2$ then $2t\,dt = dx$ and $t^2 - 2 = x$.
As $x$ goes from $0$ to $2$, then $t^2$ goes from $2$ to $4$, so $t$ goes from${}\,\ldots\,{}$ what, to what?
We could let $t$ go from $\sqrt 2$ to $2$.  Then we have
$$
\int_{\sqrt 2}^2 (t^2-2) t\,(2t\,dt) = 2 \int_{\sqrt 2}^2 (t^4 - 2t^2)\,dt = 2\left[ \frac{t^5} 5 - \frac{2t^3} 3 \right]_{\sqrt 2}^2 = \frac {112 + 16\sqrt 2} {15}.
$$
Or we could let $t$ go from $-\sqrt 2$ to $-2$.  Then we have
$$
\int_{-\sqrt 2}^{-2} (t^2-2)(-t)(2t\,dt) = -2\int_{-\sqrt 2}^{-2} (t^4-2t^2)\,dt = - 2 \left[ \frac{t^5} 5 - \frac{2t^3} 3 \right]_{-\sqrt 2}^{-2} = \frac{112 + 16\sqrt 2}{15}.
$$
The answer is the same either way.
Comment: Why did you take **-t**.What it mean to me is that **t** is negative here and you tried to change sign and made the situation same as was with the positive limits.
Comment: @Raul : If $t^2=x+2$ then $t=\pm\sqrt{x+2}$.  If that goes from $-\sqrt2$ to $-2$, then $t=-\sqrt{x+2}$, so $\sqrt{x+2}$ is $-t$. ${}\qquad{}$
Comment: Dont you think underroot of x+2 can itself take a negative number.It is looking as you are taking underroot of x+2 as modulus
Comment: @Raul : $x+2$ would be positive but $t$ would be negative. ${}\qquad{}$
Answer: Let $\simeq$ mean "to be equal to up to a constant".
Then we have
$$
\int x(x+2)^{1/2} dx = \int \bigg[ (x+2)^{3/2} - 2(x+2)^{1/2} \bigg] d(x+2)
\simeq \frac{2}{5}(x+2)^{5/2} - \frac{4}{3}(x+2)^{3/2}.
$$
Can you complete?


remove unwanted path

Question: I have tried a lot to remove path that you can see in below picture:

I am new to drupal and learning it.So right now I am converting HTML template in to Drupal theme.
So for that I have copied bartik folder and I am changing in that.
For the content, I have used an article and from configuration I have set that article on front and removed title using function in template.php.
But I am not able to find, from where that path is coming from.
Inspect element of that specific part :

My page--front.tpl.php and template.php.
Ask me if more code is needed.
I have also tried by clearing cache but it did not help me out.
Comment: That path is showing under `node-1` ID.So does it mean that it should be in the editor of that node ? Cz I have checked in editor as well but there is no content like this.
Comment: since it's not in either of those two file you linked, try node.tpl.php
Comment: failing that, see if you have a block defined to show in the content area, or content-top, etc.
Comment: Yupp.. nice call ..Solved finally :) Thanks a lot!
Answer: since it's not in either of those two file you linked, try node.tpl.php
failing that, see if you have a block defined to show in the content area, or content-top, etc.

remove unwanted path


how can I make ARIMA more robust to outliers?

Question: I have a very noisy time series like this and I forcast future values with auto.arima from the forecast package in R:
set.seed(123)
y <- diffinv(rnorm(100))

plot(forecast(auto.arima(ts(y))))

I am quite happy with this forecast. However, in my data, sometimes extreme outliers can happen, for example:
y[100] <- -10

plot(forecast(auto.arima(ts(y))))

These completely destroy my forecast. How can I make it so that ARIMA is robust to those outliers or would I have to detect and remove these outliers separetly?
Comment: You may be interested in [this answer](https://stats.stackexchange.com/questions/169468/how-to-do-forecasting-with-detection-of-outliers-in-r-time-series-analysis-pr/173684?s=2|28.2897#173684) and the [tsoutliers](https://cran.r-project.org/package=tsoutliers) package of R.
Answer: ARIMA on its own can't really handle outliers. You need to use tsclean or some other similar preprocessing method.


Memory vs Performance, which would be best?

Question: I need to take an image, scale it, mask it, add a background in case some of it is transparent and then add an overlay image.  To do this I've written the following:
<code>Canvas canvas = new Canvas();
Bitmap mainImage = Bitmap.createScaledBitmap(((BitmapDrawable)d).getBitmap(), iconSize, iconSize, false);
Bitmap result = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);

canvas.setBitmap(result);
Paint paint = new Paint();
paint.setFilterBitmap(false);

Bitmap mask = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.res, context.mask_bg)
                    , iconSize, iconSize, false);
                        canvas.drawBitmap(mask, 0, 0, paint);
canvas.drawBitmap(mainImage, 0, 0, paint);

mask = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.res, context.mask)
                    , iconSize, iconSize, false);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(mask, 0, 0, paint);

mask = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.res, context.mask_frame)
                    , iconSize, iconSize, false);
paint.setXfermode(null);
canvas.drawBitmap(mask, 0, 0, paint);
</code>
Now this operation is going to happen alot in my application.  And my application always has a service running (which is the context in this case).  I don't know too much about performance when it comes to images and I know they use up to 4 times their actual size in space but this seems like a waste to me recreating the same objects over and over.  Plus the main need for my app is performance over size.
So I'm wondering is it better to keep the bitmaps being generated each time in the service so they're only created once (only the mainImage bitmap will change each time) or even as a drawable create the bitmap from that?
Answer: Never conserve a drawable outside of the activity/fragment where it is displayed.
It can very easily create memory leaks : the drawable keep a reference to its activity, so the garbage collector can not destroy it, even if it has been destroyed and recreated since.
Use bitmaps instead.
Comment: If you will reuse the same bitmap multiple times it is highly recommended to do not recreate it each time. It is especially important to avoid creating a Bitmap (or any costly object) in methods such as getView() that are critical for performances.
Comment: Ah ok so is a bitmap conserved safe to use rather then recreating it over and over?
Comment: That's the answer I was looking for.  Much appreaciated :-)
Comment: You are welcome. Don't hesitate to run Android Lint on your project from times to times, it gives very useful advices on good coding practices and possible optimizations. I think it also includes a check for bitmaps.


Can violins change notes in the middle of a double stop?

Question: I am arranging Mozart's Piano Sonata for a string trio, because, when I listen to it, I hear 3 voices, with the bass voice in the Alberti bass being the first note and the lower melodic voice as being the other 3 notes of the Alberti bass. I reached a conundrum, it seems to require that the upper note of the violin move while sustaining the lower note in a double stop. Here is what is in that bar, as dictated by the melodic voice:
<code>X:
T: Piano Sonata no. 14 in C minor
T: K 457
T: Arranged for String Trio
C: Composed by Wolfgang Amadeus Mozart
C: Arranged by Cheyanna Marie Ward
M: 4/4
L: 1/4
Q: 1/4=190
K: C minor
%
%
%%score (Vio2 Vio) Via Cel
V:Vio2 subname="upper voice" clef=treble
V:Vio name="Violin" subname="Violin" clef=treble
V:Via name="Viola" clef=alto
V:Cel name="Cello" clef=bass
%
%
[V:Vio2] z3 g1/2f1/2 |
[V:Vio] e3 d |
[V:Via] z1 G A2 |
[V:Cel] z1 D,,2 D,, |
</code>
Now, I have never heard a violinist sustain one of the notes of a double stop while moving the other note. Usually, they break the double stop there.
I am wondering though, is such a thing possible? Or should I give the D to the viola, where the violist would just have to stop the sustain of the D? Or should I just have the D rearticulated by the violin, even though Mozart wrote it as a single quarter note with 2 eighths above it?
Comment: Yes, this is possible, depending on the notes. Look at baroque violin music, it happens all the time.
Comment: As long as each or both notes are physically within a handspan, there's no reason why not. Even cases where both notes change are feasible - two notes can move together, or one be static and the other change - on the same bow if needed, as long as they can be reached.
Comment: You should put a slur on the 2 eighth notes since they are coupled with the quarter note underneath.  Also, you don't really need the dotted half note rest as it's obvious where the eighth notes happen.
Comment: This happens in plenty of pieces for any bowed instrument - not just baroque periods.   I've played a cello  piece (Villa-Lobos) in which not only do the double-stop notes change but I have to reach out for a left-hand pizz on a third string at the same time.
Comment: @Carl I only mentioned baroque because that's the period I've mainly seen it.
Comment: You need to check up with the original score. The note in the cello should be a B flat followed by a B natural. The left hand in the piano score might be written with a G cleff at that point. In the vioiln the pause should be below the E flat as the melodic line is E flat followed by G and F.
Answer: It's even possible to detach notes in one voice of a double stop while continuing a note in the other voice, using a rocking movement of the bow.  Cf the Andante in Bach's solo violin sonata 2 with repeated detached notes in the lower voice while a sustained note is sometimes held explicitly in the upper voice.  However, that kind of technique tends to be reserved to solo violin performances as it takes a lot of practice.  However, the passage you quote is trivial in first position with regard to double stops.  You should not expect the tricky detached technique Bach calls for in something intended for a trio, so you should place a slur over the eighths regardless of whether the piano version has them.
Answer: As long as the strings to be played are next to each other, there's no reason for notes to not change smoothly during a double stop.
In your example, you would have the 3rd finger on the A string and your 1st and 2nd fingers on the E, and would lift the 2nd finger to change to F.
Here's an example of double stops changing in Bach:

Bach Sonata No. 1 for Solo Violin, Adagio, BWV 1001


AttributeError: 'UnaryOp' object has no attribute 'evaluate' when using eval function in Python

Question: <code>for test_ind, case_data in test_df.iterrows():
      case_data = case_data.to_frame().T
      rule = "Ask_before>-0.4843681 & 0.5255821<=BidVol_before<=0.07581073 & Volume>0.1107559"
      print(case_data, "case_data")
      if case_data.eval(rule).all() == True:
          print("TRUE")
</code>
Here, when the rule contains negative values, this error will appear. Could you please help me to fix this. I need to check whether this rule applies to the instances in the data-frame. Ask_before, BidVol_before are the columns of the dataframe test_df. Could you please help me to fix this issue.
Comment: Could you share test_df or a sample of it?
Comment: test_sf is a data frame with columns such as Ask_before, BidVol_before and Volume. Assume values of those columns can be any floating number.
Comment: `data = [[-0.5, -3.5, 3.8],[-0.7, -0.5, -0.38]]

# Create the pandas DataFrame
test_df = pd.DataFrame(data, columns = ['Ask_before', 'BidVol_before',Volume])`
Comment: I can't reproduce your error with `pandas '1.0.5'`. It is working for me with the data you provided. Check your pandas version just in case.
Comment: recently, face the same problem. try to cast to float as https://stackoverflow.com/questions/50400843/using-negative-numbers-in-pandas-dataframe-query-expression
it solve my problem
Answer: It isn't a problem in your code, it's a bug in pandas https://github.com/pandas-dev/pandas/issues/16363
It is fixed by now.
Answer: Seems like it's still open as of 2022 January
https://github.com/pandas-dev/pandas/issues/16363
in my experience resolving negative index values solved iit
Answer: Change the "unary" to an simple expression works for me, e.g. -5 -> (0 - 5)


join three tables sql

Question: I have 3 tables
sales
-----------
date
order_id

product_details
-----------
product_id
cost
price

order_detail
-----------
product_id
order_id

I have to minus the sum of cost and price where date is between __ and __ to show the profit or loss
I have tried this but dont what is the result is showing
SELECT ( SUM(p.price) - SUM(p.cost) )
FROM   product_details AS p
       LEFT JOIN order_detail AS o
         ON o.product_id = p.product_id
       JOIN sales AS s
         ON s.order_id = o.order_id
WHERE  s.[date] = ' 15.08.2013'

Comment: Please show some sample data and sample output.  It's very difficult to know what the problem is.
Comment: The left join implies you want all product details but the where clause excludes the benefit of the left join.  So do you want all product details regardless if it had a sale or do you want only product details which have had a sale and an order...
Comment: I just want to show the profit which can calculate as price - cost = profit
and from date to date e.g from 20.07.2013 to 20.08.2013
Answer: Assuming product_id and order_id are unique:
SELECT SUM(p.price) - SUM(p.cost) AS Profit
FROM sales s
INNER JOIN order_detail AS o ON s.order_id = o.order_id
INNER JOIN product_details AS p ON o.product_id = p.product_id
WHERE s.Date BETWEEN '15.08.2013' AND '16.08.2013'

Comment: the answer should be 14000 but I am getting 3201
Comment: Is there a quantity field that we're missing?
Comment: yes I have added and its working thnx
but I am getting 24005 instead of 24000
Comment: I'd have a close look at the data, how are you arriving at that number?  Maybe filter it to a smaller range and try and see how consistent the inconsistency is.
Comment: Its adding +1 to every day
e.g
15.08.2013 = 10000
17.08.2013 = 10000
19.08.2013 = 10000
the result should be 30000 but its 30003
Comment: I cannot possibly fathom why that would occur.  Once again I recommend further sifting through the data.  Unless something is fundamentally different from your code to mine.  Sorry bud. Also please consider upvoting and accepting my answer if it has helped you.
Answer: Sounds like you need a GROUP BY in your clause, as you're looking for the total profit of each product id?
SELECT SUM(pd.price) - SUM(pd.cost)
FROM product_details pd
    LEFT JOIN order_details od ON pd.product_id = od.product_id
    INNER JOIN sales s ON od.order_id = s.order_id
-- This is where you'd change your date filter
WHERE s.Date BETWEEN '20.07.2013' AND '20.08.2013'
GROUP BY pd.product_id

Answer: Your query is correct. Just confirm the date range your are using. Or try getting the Dates in a query and then use it accordingly in the where clause.
SELECT s.[date],( SUM(p.price) - SUM(p.cost) )
FROM   product_details AS p
LEFT JOIN order_detail AS o
ON o.product_id = p.product_id
JOIN sales AS s
ON s.order_id = o.order_id
group by s.[date]

As the Order Id is not unique then please try this:
with order_cte(product_id,order_id)as
(select distinct Product_id, Order_Id from order_detail)

SELECT s.[date],( SUM(p.price) - SUM(p.cost) )
FROM   product_details AS p
LEFT JOIN order_cte AS o
ON o.product_id = p.product_id
JOIN sales AS s
ON s.order_id = o.order_id
group by s.[date]

Comment: I am getting result 24005 instead of 24000

join three tables sql