Interpreting exim log files after parsing

Question: I'm parsing exim log files and, due to my processing method, lose the original order of all entries in this file.  I rebuild the transactions by their transaction ID (i.e. 1OfiYX-0000Ev-7k) but still don't have a way to determine the original order.
The <= , => , == , ** characters' original order matter, right?  Is there a way to rebuild the order without any additional information?
Αντίο
Answer: I think the answer, limited solely to the symbols you ask about, is that <= is always going to come before each of the other symbols you list, and a message's Completed line will come after all of those symbols.  However, each of the other symbols ==, =>, **, can appear in any order between <= and Completed.
One thing to keep in mind is that a message can have multiple recipients, and each of those recipients can be deferred (==), so the order of those symbols matters for each recipient of the message
So, every message should have exactly one <= when the message is accepted by the local server
Every message should have exactly one Completed line indicating that the local server is done with the message
Between those:
Each message:recipient will have exactly one of ** (failure) or => (delivered).  It will be the last entry for that specific message:recipient.
Each message:recipient may have one or more == (deferred) lines.  If a message:recipient has a == log line, it will occur before that message:recipient's => or ** line.
The order of different recipients in a given message only matters if you think it matters, most likely.
Comment: +1. Exactly what I was looking for.
Answer: Exim is shipped with tools to help with logfile analysis.  In particular, exigrep may be of interest, as it can search for a pattern in a line and then show all the log-lines for that message, including those which came before the match-line.
Exim is shipped with documentation, "The Exim Specification"; at the very least, you should have a file called "spec.txt", if not .pdf or other variant; this is also online at http://www.exim.org/; you might find "49. Log files", documenting the precise format of the log-files, and "50. Exim utilities" to be useful.
Each log-line has a timestamp; group by exim message-id and then sort by timestamp and you have the original order back.
Answer: Yes the matter as they indicate the direction of the message flow. You need to improve your processing method not to reorder your entries.
Comment: So here is my next finding.  1) I sent a message FROM the server. 2) I sent a message TO the server.  Both had the same structure. The first log entry *always* contained the `<=` while the second entry contained the others `=>`, `==`, etc.  Based on the ID, why can't I just rebuild the message so the `<=` always is the first line?  Am I misunderstanding something?  Based on this experiment, I want to say order *doesn't* matter.
Comment: *Is there a way to rebuild the order without any additional information?*
Comment: Yes there could be it depends on how hadoop has split the lines. because each line has the ID you should be able to reassemble the message.
Answer: Have you tried using one of the available log file parsers, e.g. awstats or sawmill.


Full height using flex-direction: column

Question: I want my c1 to be fully stretched, but I wonder why when I apply flex:1 it doesn't fill up the space.

.wrap {
  display:flex;
  flex-direction: column;
}

.c1 {
  background: red;
  flex: 1;
}

.c2 {
  background: blue;
}

child 1

more content

child 2

Comment: You need to set a height on the parent
Answer: In your wrap class you have to add the height.

.wrap {
  display:flex;
  flex-direction: column;
  height: 100vh;
}

.c1 {
  background: red;
  flex: 1;
}

.c2 {
  background: blue;
}

child 1

more content

child 2

Comment: I got it, just have to use box-sizing to not have a scroll bar
Comment: height 100vh is not what I want, it create scroll bar
Comment: "I want my c1 to be fully stretched" -- you have to define what that is. Is it 100vh? Is it 100 px?  The above answer is correct, just maybe a different number than 100vh.
Comment: @alice_morgan you feel free to change the hight or can you perhaps explain in more detail what exactly you expect?


Maximize $x\cos \left( {{\theta _a}} \right) + y\cos \left( {{\theta _b}} \right)$ subject to $x\le 3$, $y\le5$?

Question: I like to maximize the following equation:
$x\cos \left( {{\theta _a}} \right) + y\cos \left( {{\theta _b}} \right)$ subject to $x\le 3$, $y\le5$
Where, $cos(\theta_a)$ and $cos(\theta_b)$ are just two angels range $0\le \theta_a \le 2\pi $ and $0\le \theta_b \le 2\pi $
By doing numerically I found that $x=3$ and $y=5$ maximize the equation. But how should I determine the condition on the angle $\theta_a$ and $\theta_b$?
Any suggestions will be helpful. Thanks.
Comment: Are $x$ and $y$ restricted to be non-negative? If not, then you can set $\theta_a = \theta_b = \pi$ and make $x$ and $y$ arbitrarily negative.
Comment: What are $\theta_x$ and $\theta_y$?
Comment: @saulspatz I edited that part. Thank you.
Answer: Since $x$ and $y$ are positive numbers, you want $\cos \theta_a$ and $\cos \theta_b$ to be as large as possible, so take $\theta_a=\theta_b=0$


Backbone Validation with Backbone stickit - All attributes being validated when one is changed

Question: I am attempting to use Backbone Validation with Backbone Stickit, I wish to validate one attribute at a time as the user enters them. However, when a user enters a value all attributes on the model get validated instead of just the one the user has changed. What am I doing wrong?
My View:
bindings:{
        '#username' : {
           observe:'username',
           setOptions: {
                validate:true
           }
        },

        '#email' : {
           observe:'email',
           setOptions: {
                validate:true
           }
        },

        '#firstname' : {
           observe:'firstName',
           setOptions: {
                validate:true
           }
        },

.......

onShow: function(){
        Backbone.Validation.bind(this, {
              valid: function(view, attr) {
                alert('VALID - ' + attr);
              },
              invalid: function(view, attr, error) {
                alert('INVALID - ' + attr);
              }
            });

        this.stickit();

    },

Comment: Solved this by any chance? Stuck with the same problem
Comment: Sorry, I never did solve this problem. From what I remember, and from reading yousefcisco's response, it is due to the behaviour of a backbone model
Answer: Everything you pass through setOptions is used when setting the value in the model (1). When you pass validate: true to the set function of a Backbone model it will validate the values in the model as well as the values passed to the set function (2) meaning it will validate the whole model every time you set a new value causing the problem you're seeing now. You're not doing anything wrong.
You could probably solve this by splitting up your validation into multiple separate functions and calling only the required ones on attribute change and then changing the validate function to call all those separate functions to validate the entire model.
Comment: The main issue here is that Backbone will validate the entire model when ```validate: true``` is passed. One solution to this would be to create separate validation functions (eg. validateCountry, validatePhone) and then set event listeners for change on country and phone to trigger the validation function. However, this solution isn't great and adds a whole load of complexity to your application. Here's an incomplete gist of what this solution could look like (it got too complex to finish) https://gist.github.com/yousefcisco/5ba5d571eff103650c87
Comment: Can you please elaborate?
Answer: This happened to me as well. In my case, I was setting default values in the model as '' (blank). Removed them and it worked
Answer: For this to work you should remove defaults (at least for the attributes your validating) values from your model
Comment: could you explain more? please read How to improve your answer
http://meta.stackoverflow.com/q/253804/3664960 if this actually was your answer
Answer: Try using the backbone.validation forceUpdate parameter on your backbone.stickit setOptions object in yout view bindings. That worked for me and I had a kind of similar problem.
Just like yousefcisco mentioned, backbone will validate all the attributes in the model on set or save, depending of your options passed, but in my case is not that I needed to validate each attribute separately, but the attributes didn't get set even if only one attribute was invalid, then I tried the forceUpdate: true, and it did its magic.
check it here: http://thedersen.com/projects/backbone-validation/#configuration/force-update


Fatal error: Class 'RulesI18nStringController' not found in entity.i18n.inc on line 31

Question: My client drupal site stopped working suddenly and gave me this error Fatal error: Class 'RulesI18nStringController' not found in entity.i18n.inc on line 31 i checked the rules module and entity module and nothing seems to be messing.
I searched for a solution on the internet with no luck.
I have rules 7.x-2.2 and entity 7.x-1.0-rc3 but i can't login to the site so i can't access update.php to update the rules and entity modules to the latest versions "as it may fix this problem".
So can anybody help me find solve this problem?
PS: If you need any additional information about the problem just ask about it in the comments.
Thanks in advance for you all.
Comment: You can use drush to update your site without logging in.
Comment: @ЕлинЙ. i will try it and i hope updating will fix the problem
Answer: You have $update_free_access variable in your settings.php file. Set it to:
$update_free_access = TRUE;

You will be able to run update.php without login. Don't forget to turn it back to FALSE when done - if left TRUE, it can open your site to DoS attacks.
Comment: Tried it and updated my modules and the error message is gone thank you for your help
Comment: Glad it worked :)


Compute the double integral $\iint_{(x,y):0<\tfrac{x}{2}\leq{y}\leq\tfrac{3x}{2}<1}dydx$

Question: Attempt: I sketched the region, and decided it would be easiest to break up the area into two integrals $A_1,A_2$ and sum. Is it correct that $A_1,A_2$ are Type-I integration regions? Is there a more straightforward way to compute the overall area? My multivar integration is weak.
$$A_1 = \int_0^{\tfrac23}\int_{\tfrac{x}{2}}^{\tfrac{3x}{2}}dydx=\tfrac29$$
$$A_2 = \int_{\tfrac23}^{1}\int_{\tfrac{x}{2}}^{x}dydx=\tfrac{5}{36}$$
Thus the desired integral is $\tfrac{13}{36}$, is this the correct value?
Comment: Why is there an $A_2$ integral at all?  Along that region, $\frac{3x}2 > 1$, so it shouldn't be included.
Answer: The region defined by $$(x,y) : 0 < \frac{x}2 \leq y \leq \frac{3x}2 < 1$$
is the triangle enclosed by $y=\frac{x}2$, $y=\frac{3x}2$ and $\frac{3x}2 = 1$ (i.e. $x = \frac23$).
Using the side along $x=\frac23$ as the base, this triangle has height $h = \frac23-0=\frac23$ (the other two lines intersect at $x=0$) and base length $b = \frac{3(2/3)}2 - \frac{(2/3)}2 = \frac23$ (the distance between the points the line $x=\frac23$ intersects the other lines).  It follows that the area enclosed is $$\frac12bh = \frac29.$$


Rounded corners in layout with custom color on Android

Question: I've got an xml for the shape and color of my drawable :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/light_red"/>
    <corners android:radius="10dp"/>
</shape>

But I would like to use this drawable as a global one, like having the corners rounded when I'm using it, but being able to change the backgroundColor.
But when I'm trying to change the backgroundColor programatically, it overrides the color like I want but it also override the rounded corners which becomes flat.
For the moment, if I want to have rounded corners with different colors, I need to create multiple XML files with only the android:color changing.
Answer: To programmatically change a color globally defined in a shape, use this:
findViewById(R.id.your_xml_element).getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);

Answer: Just for other people coming here after, I did some research with what you gave me, this setColorFilter is deprecated since API 29.
I found the solution for non deprecated method (a little bit longer but working):
findViewById(R.id.your_xml_element).getBackground().setColorFilter(BlendModeColorFilterCompat.createBlendModeColorFilterCompat(Color.BLUE, BlendModeCompat.SRC_ATOP));


Searching for a bit-string $x$ such that for $f: \{0,1\}^n \rightarrow \{0,1\}$ we have $f(x) = 1$

Question: Suppose I have a function $f: \{0,1\}^n \rightarrow \{0,1\}$, where for one particular value of $x \in \{0,1\}^n$ we have $f(x) = 1$ and for all other values $y \neq x$, $f(y) = 0$. Now suppose that I choose $k$ values for $ 1 \leq k \leq n$, say $x_k \in \{0,1\}^n$ and test if $f(x_k) = 1$.
If the values $k$ were not distinct, then I would imagine that the probability of not choosing $x$ is $ (\frac {2^n - 1} {2^n})^k$, whereas if the $k$ values are distinct, then the probability of not choosing $x$ is $\frac {2^n -1 }{2^n} \frac {2^n - 2 }{2^n - 1} \cdots \frac {2^n - (k-1)} {2^n - k}$.
The author of the textbook I am reading writes that "if choosing $k$ values will find $x$ with probability $1 - \epsilon$ for $0 \leq \epsilon  \leq 1$, then we must have $1 - \frac {k} {2^n} < \epsilon$". I am not sure how this was arrived at, insights appreciated.
Answer: The author is being a bit lenient in terms of accuracy. What the author is really trying to say is this:

When choosing randomly $k$ elements among $\{0,1\}^n$, you cannot guarantee a probability to find your $x$ that is higher than $\frac{k}{2^n}$.

What the author writes, somewhat inaccurately, is this:

If the probability that a subset of $\{0,1\}^n$ whose cardinality is $k$ contains $x$ is larger than $1-\epsilon$ then $1-\frac{k}{2^n}<\epsilon$.

The point is that the probability that a subset of $\{0,1\}^n$ whose cardinality is $k$ contains $x$ is equal to
$$1-\frac{{2^n-1\choose k}}{{2^n\choose k}}=\frac{k}{2^n}$$
(because in order not to contain $x$ you must choose $k$ elements among the remaining $2^n-1$). Now, if you know that this probability is exactly $1-\epsilon$, then you obviously get $\epsilon=1-\frac{k}{2^n}$; however, if you want to guarantee a probability larger than $1-\epsilon$, then you get $\frac{k}{2^n}>1-\epsilon$, whence $1-\frac{k}{2^n}<\epsilon$.


What different between 2 json with PHP

Question: I have theses two code to make json from array in PHP:
Code 1
$array_1 = array("A","B","C");
$array_2 = array("D","E","F");
echo json_encode(array('array_0'=> array('array_1'=>$array_1,'array_2'=>$array_2)));

Output :
{
    "array_0":
    {
        "array_1": ["A", "B", "C"],
        "array_2": ["D", "E", "F"]
    }
}

Code 2
$A = array('A','B','C');
$B = array('array_1' => $A);
$C = array('D','F','E');
$D = array('array_2' => $C);
$E = array($B, $D);
$F = array('array_0' => $E);
echo json_encode($F);

Output :
{
    "array_0": [
        {
            "array_1": ["A", "B", "C"]
        },
        {
            "array_2": ["D", "F", "E"]
        }
    ]
}

Why is there a difference between the 2 output? Which one is correct?
Thanks you !
Comment: What do you mean by "correct"?  Both are correct.  They are 2 different structures.  Why would would be "correct" and one "incorrect"?
Comment: Why it different structures ? I think 2 code is the same ?
Comment: "Code 2" is not the same.  In "code 2", you are doing `array($B, $D)`.  You are making an array of 2 arrays.  That's different than "code 1".  What you should be doing is: `$B['array_2'] = $C; $F = array('array_0' => $B);`.  Get rid of `$D` and `$E`.  You want to add `array_1` *and* `array_2` to the *same* array not add them to their own arrays.
Comment: this would be a good situation for `var_dump()` or `print_r()`. If you use those functions instead of `json_encode()`, you will see that the structures are not exactly the same
Answer: In code_2 you create array_0 as:
array(array('array_1' => $A), array('array_2' => $C));
// ^$E   ^$B                   ^$D

Whereas the similar step in your code_1 is:
array('array_1' => $A, 'array_2' => $C)

You can make them similar by defining $E in code_2 as following:
$E = array_merge($B, $D)

Answer: In the first case, array_0 is an associative array that is translated to js object.
In the second case, array_0 is a numeric array that is translated to js array.
There is no correct/wrong. They are both correct.

What different between 2 json with PHP


Join tables having the same primary key

Question: How do I join three tables having the same primary key and make one view ? Any leads would be appreciated.
I have 3 tables sttm_customer, sttm_customer_c and sttm_customer_custom,
 that have customer_no in common with all.
I need to make one view STVW_CUSTOMER_TEMP merging all of them.
Comment: Also, there are some more columns in common of all the three tables.
Comment: Why do you have 3 almost similar tables? Seems like poor db design.
Answer: If I understand what you're trying to do, you can use UNION:
SELECT customer_no (and any other matching columns)
FROM sttm_customer
UNION
SELECT customer_no (and any other matching columns)
FROM sttm_customer_c
UNION customer_no (and any other matching columns)
FROM sttm_customer_custom

Join tables having the same primary key


Entropy of Sum vs Difference of Random Variable

Question: I am looking for a proof of the following fact
Let $X$ and$ X'$ be i.i.d on $\{0,1,2\}$ (not necessarily uniform). Prove that
$$H((X + X') \mod3) \leq H((X - X') \mod3)$$
where $H()$ is the standard Shannon entropy.
A short (or long) proof or any pointers would be very helpful.
Comment: As Tom Lin points out (+1), this is not true.  What is true is that the inequality universally holds for the *conditional* random variables $X\pm X^\prime \mod 3 | X\pm X^\prime \ne 0$.
Comment: I had actually made a mistake in writing the inequality unfortunately. Does this direction hold?
Comment: Yes, the inequality is now correct. (+1)
Comment: Can you give me a proof of it?
Answer: I found this suprisingly hard to prove, because the expressions for the entropies are messy.  One successful idea is to modify the distribution in a way that (a) fixes the entropy of $X-X^\prime$ while (b) increasing the entropy of $X+X^\prime$ (where the sum and difference will always be taken modulo $3$).   In this fashion the distribution of $X+X^\prime$ can be made the same as that of $X-X^\prime$, implying the original entropy of $X+X^\prime$ was no greater than that of $X-X^\prime$.

Let us designate the distribution of any random variable $X$ attaining the values $0,1,2$ by the vector of its probabilities $(\Pr(X=0), \Pr(X=1), \Pr(X=2))$. Letting the common distribution of $X$ and $X^\prime$ be $(p,q,r)$, which I will write $X\sim (p,q,r)$, we may directly compute that
$$X+X^\prime \sim (p^2 + 2qr, r^2 + 2pq, q^2 + 2pr)$$
and
$$X-X^\prime \sim (p^2+q^2+r^2, pr + qp + rq, pq + qr + rp).$$
Note that the last two coefficients are equal and observe that the value of the first (different) coefficient $t = p^2 + q^2 + r^2$ must lie between $1/3$ and $1$.  Thus we may alternatively parameterize the distribution of the difference in terms of $t$ as
$$X-X^\prime \sim \left(t, \frac{1-t}{2}, \frac{1-t}{2}\right)$$
for $t\in [1/3,1]$.
Now fix $t$ and adjust $(p,q,r)$ to make the entropy of $X+X^\prime$ as large as possible (so that the entropy of $X-X^\prime$ remains the same).  That is, modify $p, q, r$ without changing the equalities
$$t = p^2 + q^2 + r^2;\quad p+q+r=1.$$
If we temporarily fix one of the coefficients of $X+X^\prime$ then the entropy (which is proportional to the entropy of the random variable $X+X^\prime$ conditioned on not being equal to the corresponding value) increases as the remaining two coefficients move closer together; therefore, we may as well assume this has been done as much as possible and that two of the coefficients are actually equal.  This can be accomplished within the foregoing restrctictions by setting
$$p=\frac{1}{3}\left(1 \pm \sqrt{6t-2}\right);\quad q=r=\frac{1}{3}\left(1\mp \frac{1}{2}\sqrt{6t-2}\right).$$
In so doing we will have increased the entropy of $X+X^\prime$ while fixing the entropy of $X-X^\prime$.  However, as a result the distributions of $X+X^\prime$ and $X-X^\prime$ have become the same (that's an easy calculation based on these formulas for $p,q,$ and $r$) and so the resulting entropy is the same as that of $X-X^\prime$, QED.


Deploying a classic ASP site with Octopus

Question: We are currently trying to integrate deploying our new ASP.NET projects with Octopus and I was wondering if anyone has tried to use Octopus to deploy a classic ASP site?
I know it is possible and I know how to do it in theory, but our problem arises from the fact that the ASP site is HUGE.  After the total size of all the videos, images, and pdf's are summed up the site weighs in at just under 3 gigs.  So when a change is checked into TeamCity and a NuGet package is created, Octopus will be pushing a 3 gig nuget package to 2 individual load balanced servers.
We can't create a shared directory or cdn for the media files (at least not yet) so can anyone tell me a good way to attack this?  Or is Octopus just not a good solution for a large ASP site and Web Deploy would be better?  If that is the case, how can a backup solution be implemented for Web Deploy so that any errors can be rolled back?
Thanks for the help on this in advance.  We are converting these ASP sites to MVC but that is going to take a while and until that is done we have to find a way to work with them.
Answer: You should package the ASP site and the Media Files as 2 separate NuGet packages. This will allow you to update the ASP code and deploy it without having to deploy all the media files (assuming the code changes more often than the media).
Implementation Details

Setup TeamCity to package the ASP site and the Media files as separately published NuGet packages.
In Octopus Deploy add each of the 2 NuGet Packages as deployment steps for a single project
When you create a new Release in Octopus select the newest package version for the ASP code and the previously released package version for the media files.
When you deploy the release you can check a box to skip the deployment of the media files

Tips

Use the Octopus variable "OctopusWebSiteName" to specify that your media files package should be deployed in a sub-directory of your ASP site. (Like "Default Web Site/Media") The variable can be scoped to a specific package so that it only applies when deploying that package.
Answer: Do you really need to push all the content every time - cant you just push the changes?
Comment: My limited knowledge of the deployment process with TeamCity and Octopus is that Octopus is going to pull a NuGet package from the TeamCity repository.  The NuGet package is going to contain the complete source of the ASP site (4GBs).  Am I wrong in this?


Characterize a positive harmonic functions with multi-singularities

Question: Recently, I learn a theorem of Bocher from Axler-Bourdon-Ramey's book (Theorem 3.9 and 3.14) on harmonic functions which states that
Theorem

A positive harmonic functions on $\mathbb{R}^n\setminus\{ 0\}$ must be the form $a_0 + a_1 |x|^{2-n}$, where $a_i$ are constants.

My question is that : Can the above theorem be generalized to the multi-singularities case?
Conjecture

A positive harmonic functions on $\mathbb{R}^n\setminus\{ 0,1\}$ must be the form $a_0 + a_1 |x|^{2-n} + a_2 |x-1|^{2-n}$, where $a_i$ are constants.

My apptempt is to prove that such harmonic function can be decomposed to two functions, one is harmonic on $\mathbb{R}^n\setminus\{ 0\}$, the other one is $\mathbb{R}^n\setminus\{ 1\}$. But I have no idea to prove this.
I also see the authors provide the following exercise
Exercise 3.17

Let $P=\{ p_1,p_2,\cdots\}$ denote a discrete set of $\mathbb{R}^n$. Characterize the positive harmonic functions on $\mathbb{R}^n \setminus P$.

I guess its answer is a moditication of my conjecture. But I have no idea to prove it too.
Many thanks for any discussion.
Answer: This theorem should answer the question above.
Theorem: Suppose $n > 2$ and $p_1, \dots, p_m$ are distinct points in $\mathbf{R}^n$. Suppose $u \colon \mathbf{R}^n \setminus \{p_1, \dots, p_m\}\to \mathbf{R}$ is harmonic. Then $u$ is bounded below if and only if there exist $a_0, a_1, \dots, a_m  \in \mathbf{R}$ such that $a_j \ge 0$ for $j = 1, \dots, m$ and
$$
u(x) = a_0 + a_1 |x-p_1|^{2-n} + \cdots + a_m |x - p_m|^{2-n}
$$
for all $x \in \mathbf{R}^n \setminus \{p_1, \dots, p_m\}$.
Proof: Use induction on $m$. For $m = 1$, the desired result follows from the theorem quoted in the question.
Now suppose $m > 1$ and the desired result holds for $m-1$. By Theorem 3.9 in Harmonic Function Theory (second edition), there is a constant $a_m \ge 0$ and a harmonic function $v$ defined on some neighborhood of $p_m$ such that
$$
u(x) = v(x) + a_m |x - p_m|^{2-n}
$$
for all $x \ne p_m$ in a neighborhood of $p_m$.
Extend $v$ to be defined on $\mathbf{R}^n \setminus \{p_1, \dots, p_{m-1}\}$ by defining
$$
v(x) = u(x) - a_m |x - p_m|^{2-n}.
$$
Then $v$ is harmonic on $\mathbf{R}^n \setminus \{p_1, \dots, p_{m-1}\}$ (because $|x-p_m|^{2-n}$ is harmonic).
By our induction hypothesis, $v$ has the desired form, which can then be plugged into the equation above, showing that $u$ has the desired form. QED
Comment: Nice, +1. Looks like a good book!
Comment: Thank you so much! I forgot the mathematical induction.
Comment: Are these coffecients $a_i$ unique?


Why are we allowed to make trig substitutions when solving integrals?

Question: I was taught that integrals involving
$$\sqrt {a^2-x^2} \qquad \sqrt {a^2+x^2} \qquad \sqrt {x^2-a^2}$$
where $a$ is a constant can be solved by substituting various trig functions for $x$, allowing us to eventually get rid of the radical. What I was wondering is, why are we allowed to do this? On a second note, doesn't the fact that $\sin \theta$ has a range of $[-1, 1]$ mean that letting $x = a \sin \theta$ restricts $x$ to $[-a, a]$, whereas that may not necessarily be the case for the original function we're integrating?
Comment: What happens to $\sqrt{a^2-x^2}$ if $x$ is outside the range $[-a,a]$?
Comment: Ah, good point! It becomes the square root of a negative and is no longer real, so $x$ being outside $[-a, a]$ does not matter. Thanks
Answer: In a hand wavy sense, it works because of the pythagorean rules for trig functions. So in the words of David Mermin "Shut up and calculate".
More to what you asked, any x outside the $\pm a$ range is complex, so having a trig substitution function that is "bounded" is totally appropriate. If you're doing complex integration, have bounds greater than $\pm a$, then you can extend the values for inverse trig functions, obviously they will involve complex numbers. Much how we extend square roots to negative inputs.
Answer: OK, after reading Theophile's enlightening comment (and some more experience with integration), I get it. For every $\theta$, there is a corresponding $x$, and for all $x$ there is at least one corresponding $\theta$. So there's one mind-blowingly simple point that has to be understood in order to make the trig substitution method possible/plausible:
(1) $x$ is a function of $\theta$.
(2) In other words: $x$ is $f(\theta)$.
If you define $f(\theta)$ in such a way that this is true, then you are free to substitute $f(\theta)$ for $x$.


Criar vários DataFrames através de iteração

Question: É possível que seja criado vários DataFrames dentro de uma iteração?
estou necessitando fazer esse feito, segue o exemplo:
na iteração NUM, possuí números de 0 a 9, total 10 números.
no for nn in NUM: ele irá iterar renomeando o df_nn ficando df_0 df_1... até df_9, assim gerando 10 DataFrames diferentes, onde posso consulta cada um.
existe alguma forma de fazer isso? obrigado
import pandas as pd
import random

NUM = [n for n in range(10)]

for nn in NUM:
    df_nn = pd.DataFrame({
        "A":[random.random(),random.random()]
    })

Answer: Me parece que você está buscando um dicionário, por exemplo:
d = {
    n: pd.DataFrame({
        "A": [random.random(), random.random()]
    })
    for n in range(10)
}

Agora é possível acessar cada DataFrame através de sua chave correspondente (nesse exemplo, números de 0 a 9):
>>> d[0]
          A
0  0.592403
1  0.328729

>>> d[5]
          A
0  0.273226
1  0.188603

Comment: perfeito, obrigado pela sua disponibilidade, abraço


How can I change the color of an icon and text at the same time when hovering over with mouse

Question: I've created 3 icons with text under, you can see the code here http://cssdeck.com/labs/qrpf4z9g
The problem is that if you hover your mouse over an icon, only the icon gets red and the text stays grey, but if you hover over the text first then both icon and text gets red.
my goal is to make the text and the icon red at the same time no matter where you hover first and i can't figure out how.
I'm new to HTML/CSS
Comment: Try using the selector `a:hover span`
Answer: Change this:
.righticons a span:hover

To this:
.righticons a:hover span

Also, I noticed that upon first hovering each that there is a slight "flash" before showing the red icon. This happens because the icon needs to load its new image - you might consider creating a sprite (at least for each icon) and adjusting only the background-position property upon hovering. This will eliminate the flash.
Comment: No problem - note the edit I made as well regarding the flash of the hover images, should help you make things look a little cleaner.
Comment: yes, i was thinking about the flash too, thanks for letting me know, altough i'm not sure how to create a sprite. Would appreciate if you could tell me or i'll have to find it out myself
Comment: Probably too much for me to answer in a comment, but the basic idea is that you are combining your regular and hover images into equally sized blocks in a single image file. Then you use the `background-position` property to define which portion of the image you show. The image changes its position, but doesn't need to load since it was already included in page load with the original image. [This link](http://css-tricks.com/snippets/css/basic-link-rollover-as-css-sprite/) should help with setting up your classes, and there are a lot of tutorials available online to check out.
Comment: w3schools also has a decent example here: http://www.w3schools.com/css/css_image_sprites.asp
Comment: Thanks, i figured it out by watching a youtube video :)


Json from url - array in array

Question: I want take data from API from polish http by json format. But, I have problem take data from array in array.
From "normal" json I can took data, but this json have struture as 'krs_podmioty.id' => 'blabla' <= I have problem with . (dot) and array in array.
I try get data from https://api-v3.mojepanstwo.pl/dane/krs_podmioty/10186.json?layers[]=dzialalnosci&layers[]=reprezentacja.
You can decode on: http://freeonlinetools24.com/json-decode (and past text from http).
It's public website and data.
If you will look it, I want data from segment:
'krs_podmioty'.person_id' =>  array ( 0 => '14439' .... 11 => '1233301' )
import urllib.request
import json

res = urllib.request.urlopen('https://api-v3.mojepanstwo.pl/dane/krs_podmioty/10186.json?layers[]=dzialalnosci&layers[]=reprezentacja')
res_body = res.read()

j = json.loads(res_body.decode("utf-8"))

for item in j['data']:
    ucmdbId = (item['krs_podmioty'])
    print('Id podmioty: '.format(ucmdbId))

exit(0)

In perfect situation I need print list of all "krs_podmioty.person_id"
Thank you very much!
Answer: Try this:
   for item in j['data']['krs_podmioty.person_id']:
        ucmdbId = item
        print('Id podmioty: {0} '.format(ucmdbId))

j['data'] contained all of the objects in the 'data' array in which you could call for the krs_podmioty.person_id key to get its corresponding value array.
Answer: import requests
import json

result = requests.get('https://api-v3.mojepanstwo.pl/dane/krs_podmioty/10186.json?layers[]=dzialalnosci&layers[]=reprezentacja').json()
ids = result['data']['krs_podmioty.person_id']
for id in ids:
    print('Id podmioty: ' + id)

Json from url - array in array


How to model binomial data when the dependent variable is LITERALLY dependent on the independent variable

Question: I am designing an experiment where a subject makes a choice between two options ("low value" (LV) and "high value" (HV)).
The subject will experience both options during a trial that takes place before their choice is measured.
I want to test whether subjects choose the HV option.
To avoid any potential effect of which side the option is presented, I intend to switch the HV option from left to right (and vice versa) between first exposure and the choice test trial.
I need to account for subject ID (random effect), so cannot use a simple Chi-square test. I was hoping to use a binomial logistic regression to test whether subjects are more likely to choose the HV option, but obviously this doesn't make sense as the dependent variable is the same as the independent variable.
I thought about using the right-left data instead (i.e. choose L/R ~ HV on L/R) but I think this would just tell me whether HV being on the right or left makes a difference to the choice, rather than whether the subjects choose the HV option.
Could anyone tell me how I can overcome this issue? Is there an appropriate test out there that can do this with additional variables, or is there a different way I could prepare the data to make it work?
Comment: Do you just want to know if subjects choose HV more often than a 50/50 chance (or whatever your ratio of HV is to LV)?
Comment: Yes. Ideally, I'd just use a chi-square test, but the subjects will be tested multiple times.
Answer: You have two IV's (Low Value and High Value) and 1 DV which is binary.
Thus, a binary GLM would be appropriate.
Assuming "Low Value" is your baseline, then the coefficient on "High Value" would be the effect of "High Value" vs "Low Value". If the p-value is not significant, then there is no  difference between the "Low Value" and "High Value". You interpret the constant as the baseline for the "Low Value".
The reason this works is because ANOVA and Regression are the same thing. (Try running an ANOVA and a post-hoc test like Tukey's HSD and you will get the same results as would via linear regression).
Thus, you can perform an ANOVA type analysis using GLM's in a similar manner by interpreting the coefficients and p-values. Your treatment groups will be measured against a baseline, etc.
An additional way to interpret this is that since you have a controlled experiment then your IV's are truly independent.
Comment: Thank you for answering my question. I'm afraid I'm still unsure how I would construct the model. Is there not an issue with the HV and LV options being presented at the same time?
Answer: Through playing with some dummy data in R and thinking more about the answers/comments here, I think I've figured out the answer to my question. I just need to look at the value of the intercept.
I should use a logistic regression with only the intercept. So, when coding it in R, and with choice as the binary dependent variable:
    my.model = glmm(choice ~ 1 + (1|subjectID), data = data, family = binomial(link = "logit"))

The coefficient for the intercept informs me whether the number of "correct choices" is significantly above 50%.
If I want to include fixed effects and test whether covariates affect choice, I would have to compare a model with these with this intercept-only model with anova() or similar.


What does it mean that the decomposition is based on the linear systematic component? And how can I interpret my result?

Question: I'm using the oaxaca package to implement a Blinder-Oaxaca decomposition on a logistic model with binary outcome.
The vignette says that:

Note that, if a non-linear function such as glm() is chosen, the
decomposition will be based on the linear systematic component – usually associated with
the estimation of the corresponding latent variable – of the regression method.

What does it mean that the decomposition is based on the linear systematic component?
I'm decomposing with:
results <- oaxaca(f,
                  data = df,
                  R = R,
                  reg.fun = glm,
                  family = binomial(link="logit"))

The results is as follows:
> results$n
$n.A
[1] 188751

$n.B
[1] 87856

$n.pooled
[1] 276607

> results$y
$y.A
[1] 0.005260899

$y.B
[1] 0.002663449

$y.diff
[1] 0.00259745

So results$y looks like it contains probabilities. The difference in probability between the two group is 0.25%.
But I don't understand the three-fold decomposition, which is as follows:
> results$threefold$overall
  coef(endowments)     se(endowments) coef(coefficients)   se(coefficients)
        0.59955787         0.12425443         0.23692063         0.13821627
 coef(interaction)    se(interaction)
       -0.04663127         0.13934151

If I sum the 3 components of the decomposition, I obtain:
> te <- results$threefold$overall[["coef(endowments)"]] +
+       results$threefold$overall[["coef(coefficients)"]] +
+       results$threefold$overall[["coef(interaction)"]]
> print(te)
[1] 0.7898472

which should equal results$y$y.diff, but obviously isn't.
Answer: To your first question - What does it mean that the decomposition is based on the linear systematic component?
This means that the decomposition implemented here is on the log-odds (logit) scale. For a logistic regression, the $\beta$ coefficients are interpreted in terms of log-odds, which are linear and additive. The endowments, coefficients, and interaction outputs for your Blinder-Oaxaca decomposition are therefore all in log-odds terms.
Addressing your second question about summing the decomposition estimates - this calculation is impacted by use of the log-odds scale, and the raw sum of these components will not be equal the simple difference in probabilities given by the results$y output.
To better understand what's happening, let's simulate a decomposition
# For reproducibility
set.seed(6000)

# Data generating process
n <- 10000
mu_group_A <- c(1, 2.5, 4)
mu_group_B <- c(0.5, 2.5, 3.5)
sigma <- rWishart(1,3,diag(3))[,,1]

# Simulate RHS observed data
x1 <- MASS::mvrnorm(n, mu_group_A,sigma)
x2 <- MASS::mvrnorm(n, mu_group_B,sigma)

# Regression formulas for two groups
intercept <- 1
betas_A <- c(0.25, 0.1, 0)
betas_B <- c(0.5, 0.75, 0.15)

# Calculate log-odds outcome for each
z1 <- intercept + x1 %*% betas_A
z2 <- intercept + x2 %*% betas_B

# Convert from log-odds to observed binary outcome
pr <- plogis(c(z1, z2))
y <- rbinom(n*2, 1, pr)

# Join into a data.frame
group_B <- rep(0:1, each = n)
df <- data.frame(y, rbind(x1, x2), group_B)

Now before we fit any models to our simulated data, we already know what the true decomposition components should be, based on the means of each variable by group ($\bar{X}_A$ and $\bar{X}_B$) and the log-odds scale $\beta$ coefficients we used to generate the outcome $y$.
$$\begin{align*}
\text{Endowments} && (\bar{X}_A - \bar{X}_B)'\beta_B = 0.325 \\
\text{Coefficients} && \bar{X}_B' (\beta_A - \beta_B) = -2.275 \\
\text{Interaction} && (\bar{X}_A - \bar{X}_B)' (\beta_A - \beta_B) = -0.2 \\
\end{align*}$$
Which we can calculate in R by:
# True decomposition estimates
endowments <- t(mu_group_A - mu_group_B) %*% betas_B
coeffs <- t(mu_group_B) %*% (betas_A - betas_B)
interact <- t(mu_group_A - mu_group_B) %*% (betas_A - betas_B)

> (true_BO_par <- c(endowments, coeffs, interact))
[1]  0.325 -2.275 -0.200

Now let's run the Blinder-Oaxaca on our simulated data
library(oaxaca)
fit <- oaxaca(y ~ X1 + X2 + X3 | group_B,
              data = df,
              reg.fun = glm,
              R = 100,
              family = binomial(link="logit"))

This takes a little while to run with the bootstrap procedure (used to estimate uncertainty on the decomposition components), but we eventually find
> fit$threefold$overall
  coef(endowments)     se(endowments) coef(coefficients)
        0.37101832         0.03174424        -2.48317386
  se(coefficients)  coef(interaction)    se(interaction)
        0.08839086        -0.23463968         0.02981978

Which agrees fairly well with our known decomposition parameters.
If we now take the sum of both the true and estimated decomposition components, you'll notice something interesting.
> sum(true_BO_par)
[1] -2.15
> sum(fit$threefold$overall[c(1, 3, 5)])
[1] -2.346795

Although they agree somewhat well with each other, they are definitely not on the probability scale (i.e. they don't equal fit$y$diff). But more importantly, transforming the summed decomposition components back to the probability scale doesn't actually give us the raw difference in probabilities.
This is because transforming back to the probability scale makes the previously independent linear effects of each term on the model (i.e., on the log-odds scale) dependent on the values of the other variables in the model. We need instead to use marginal effects.
To verify our results, let's estimate the separate marginal effects for each group, and find the difference
library(marginaleffects)

# Marginal effects needs a factor variable
df$group_B <- as.factor(df$group_B)

# Refit the models separately
m1 <- glm(y ~ X1 + X2 + X3,
          data = df,
          subset = group_B == 0,
          family = binomial(link="logit"))
m2 <- glm(y ~ X1 + X2 + X3,
          data = df,
          subset = group_B == 1,
          family = binomial(link="logit"))

> (mm1 <- marginalmeans(m1, type = "link"))
     term value marginalmean  std.error conf.low conf.high p.value statistic
1 group_B     0     1.522338 0.02714284 1.469139  1.575537       0  56.08618
> (mm2 <- marginalmeans(m2, type = "link"))
     term value marginalmean  std.error conf.low conf.high p.value statistic
1 group_B     1     3.869133 0.08093886 3.710496  4.027771       0  47.80316

And taking the difference in estimated marginal means for the separate models, we can see it matches our summed decomposition components (again, on the log-odds scale) perfectly:
> mm1$marginalmean - mm2$marginalmean
[1] -2.346795

To sum up, the decomposition components you're estimating by running a Blinder-Oaxaca model with a logistic regression have a marginal interpretation on the log-odds scale.


How to create a custom design of an existing view block?

Question: I have a block I created via views ui. It is in a table format. It has 3 columns with 3 fields. Every field shows in a separate column.
Now I want to change the design of this block in an easy way to my likings.
For example here is the screenshot of one of the blocks to explain what I mean.

This shot is showing user-pic, username and follow-flag resp. As indicated in the snapshot, I want to show follow-flag below the username.
How to easily change the design of my view or block? The best would be a drag & drop. I guess this is an easiest way.
Answer: By modifying the view templates the views can be altered.
You can add custom html design and styles to modify design.
From Page: Theming information select the template. For eg:  views-view--sample--page.tpl.php, template for the view named Sample.
Answer: By pressing "settings" next to the table format, you can alter which column the fields are shown in.
Then using the "Separator" on the parent column (in your case the username field) you can inject what separats them.
Alternative you can adjust the styling of the "Follow" field to be a block element (div).


A martingale and mesurability problem

Question: Let $X$ be an integrable random variable and $\mathcal F_t$ a filtration.
$E[X|\mathcal F_t]$ is an $\mathcal F$-martingale by the tower property.
Let $f$ be a bounded mesurable function. Set $Y_t=f(E[X|\mathcal F_t])$. Let $0<s<t \in \mathbb R$.
The question: is $E[Y_t|\mathcal F_s]$ mesurable with regard to $\sigma(E[X |\mathcal F_s])$ ?
When $f$ is the identity, this is immediate by the martingale property.
If it helps, we can suppose that $\mathcal F_t$ is generated by a stochastic process $Z_t$ and that $E[X|\mathcal F_t] = E[X|Z_t]$.
EDIT: If it helps even more, we can assume that $X=Z_1$, that $(Z_t)$ is Markov (with regard to its filtration $\mathcal F_t$), sample-continuous, and that $0<s<t \leq 1$.
Answer: That is false in general. The Markov assumption might help, although it is not obvious to me how. Anyways, here is a non-Markov counter-example.
Take $\mathcal{F}_n = \sigma (Z_1, \ldots, Z_n)$, where the $Z_i$ are i.i.d. with $\mathbb{P} (Z_i = 1) = \mathbb{P} (Z_i = -1) = 1/2$. Take $(X_0, X_1, X_2) = (0, 0, (1+Z_1) Z_2)$. Then:

$Y_2 = f((1+Z_1) Z_2)$.
$\mathbb{E} (Y_2 | \mathcal{F}_1) = \mathbb{E} (f((1+Z_1) Z_2) | Z_1) = f(0)$ if $Z_1 = -1$, and $\frac{f(-2)+f(2)}{2}$ if $Z_1 = 1$.
$\mathbb{E} (X_2 | \mathcal{F}_1) = 0$.
$\sigma (\mathbb{E} (X_2 | \mathcal{F}_1))$ is trivial.

Hence, as long as $\frac{f(-2)+f(2)}{2} \neq f(0)$, the equality you are looking for is false.
The problem is that compensations may happens so that $\sigma (\mathbb{E} (X_2 | \mathcal{F}_1))$ is strictly smaller than $\mathcal{F}_1$. If $f$ is the identity, or in general affine, the same compensations happens for $\mathbb{E} (Y_2 | \mathcal{F}_1)$, so that you still get what you want. However, non-linearity in $f$ may break these compensations, making $\sigma(\mathbb{E} (Y_2 | \mathcal{F}_1))$ finer than $\sigma (\mathbb{E} (X_2 | \mathcal{F}_1))$.

A martingale and mesurability problem


Identificar se o teclado do celular está aberto

Question: Sei que é possível identificar quando a pessoa clica num elemento determinado da tela pela primeira vez, mas se fosse melhorar isso.
Como poderia identificar se o teclado do celular está aberto quando alguém clicar num campo de texto através do navegador do celular, por exemplo?
Existe uma maneira de fazer isso através de javascript?

<form>
   <input onclick="seiQueAbriuOTeclado()">
</form>

Gostaria de saber se existe uma forma de acessar via webview algum plugin que faça essa relação com cordova, como o ionic framework faz.
Dúvidas similares
Aqui um exemplo básico
Comment: Pelo que entendo não é possível verificar se o teclado estar aberto sem ser por dedução. O que você pode fazer é um listener para o evento de focus em elementos que abre o teclado e um listener para o evento de blur em elementos que o teclado fecha para assim ter um controle.
Answer: Você poderia verificar se a pessoa está em um Dispositivo movel:
    function verificacao() { var check = false; //wrapper no check
        (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera)
        return check;
    }

E se o a pessoa estiver em um dispositivo mobile e o OnFocus for acionado você vai saber que o teclado apareceu.
Comment: Digamos que meu sistema já identifique que estou em um mobile, em vez de fazer a checagem de onclick eu checasse o foco no campo, `onFocus="abriuTeclado()"`,  como saber se o teclado foi fechado mesmo se perder o foco no campo?
Comment: Até porque é possível fechar o teclado se a pessoa apertar o botão voltar do celular.
Answer: Conforme o perguntando:

Gostaria de saber se existe uma forma de acessar via webview algum plugin que faça essa relação com cordova

Sim, Ionic é cordova, o núcleo dele pelo menos, por exemplo o plugin usado pelo Ionic é o https://github.com/ionic-team/cordova-plugin-ionic-keyboard, que é baseado no https://github.com/cjpearson/cordova-plugin-keyboard, para instalar basta usar o comando
cordova plugin add cordova-plugin-keyboard

Você pode checar se esta visivel com:
if (cordova.plugins.Keyboard.isVisible) {
    ...
}

Ou usar o evento:
window.addEventListener('keyboardDidShow', function () {
    // dispara quando o teclado se torna visivel
});

Via JavaScript puro não tem recurso para isso, o evento focus não vai checar se o teclado é visivel, vai checar se o campo esta focado, o teclado estando visivel em campo focado é mera "conveniência"


Fatal error with the tagadelic module

Question: I have this error after the installation of the tagadelic 7.x-2.x-dev module:

Fatal error: Call to undefined function tagadelic_get_weighted_tags() in /home/www/2374fcf941c82d5986ed6d27587b81e0/web/sites/all/modules/cumulus/cumulus.module on line 120

How can I recover my site?
Comment: Also note that in general installing a -dev module is a really bad idea. For reasons like here: an incompatibility between a rewritten module and one depending on it.
Answer: Log in to your database panel (for example PHPMyAdmin) and run following query:
UPDATE system SET status='0' WHERE name='tagadelic';

Additionally, if you are using Drupal 7, run:
DELETE FROM cache_bootstrap WHERE cid='system_list';

After then you can uninstall problematic module via administration panel.
Answer: had the same problem with tagadelic module, and cumulus module, and i use drupal 7.x. I copyed the code from http://www.startel.kz/sites/all/modules/tagadelic/tagadelic.module , for the tagadelic file, did wonders works great.

Fatal error with the tagadelic module


Run a program from python several times whitout initialize different shells

Question: I want to run a compiled Fortran numerical model from Python. It is too complex to compile it using F2PY without implement several changes in the Fortran routines. This is why I am just calling its executable using the subprocess module.
The problem is that I have to call it few thousands of times, and I have the feeling that generating soo many shells is slowing the whole thing.
My implememtation (It is difficult to provide a reproducible example, sorry) looks like:
import os
import subprocess

foo_path = '/path/to/compiled/program/'
program_dir = os.path.join(foo_path, "FOO")            #FOO is the Fortran executable
instruction = program_dir + " < nlst"                  #It is necesary to provide FOO a text file (nlst)
                                                       #with the configuration to the program

subprocess.call(instruction, shell=True, cwd=foo_path) #run the executable

Running it in this way (inside a loop), it works well and FOO generates a text file output that I can read from python. But I'd like to do the same keeping the shell active and just providing to it the "nlst" file path. Another nice option may be start an empty shell and keep it waiting for  the instruction string, that will look like "./FOO < nlst". But I am not sure about how to do it, any ideas?
Thanks!
[Edited] Something like this should work but .comunicate ends process and a second call does not work:
from subprocess import Popen, PIPE

foo_path = '/path/to/FOO/'
process = Popen(['bash'], stdin=PIPE, cwd=foo_path)
process.communicate(b'./FOO < nlst')

Comment: You could use a pipe (see popen()) that allows your python script to send strings. On the other side of the pipe you run a shell script that does a `read` and starts your Python script with the argument it just read from stdin.
Comment: Maybe threading works for you - [link](https://docs.python.org/3/library/concurrent.futures.html)
Comment: Thanks @Ronald . I think your approach is exactly what I want. But not sure about how to implement it. I'll edit the question with my attempt
Answer: I found this solution using the pexpect module,
import pexpect
import os.path

foo_path = '/path/to/FOO/'
out_path = '/path/to/FOO/foo_out_file'  #path to output file
child = pexpect.spawn('bash', cwd=foo_path)
child.sendline('./FOO < nlst')

while not os.path.exists(out_path): #wait until out_path is created
    continue

Answer: To extend my comment, here is an example for threading with your code:
import os
import subprocess
from concurrent.futures import ThreadPoolExecutor

foo_path = '/path/to/compiled/program/'
program_dir = os.path.join(foo_path, "FOO")            #FOO is the Fortran executable
instruction = program_dir + " < nlst"                  #It is necesary to provide FOO a text file (nlst)
                                                       #with the configuration to the program

def your_function():
    subprocess.call(instruction, shell=True, cwd=foo_path) #run the executable

# create executor object
executor = ThreadPoolExecutor(max_workers=4)  # uncertain of how many workers you might need/want

# specify how often you want to run the function
for i in range(10):
    # start your function as thread
    executor.submit(your_function)

Comment: Thanks, but this do not solve the problem as 'your_function' will create a new shell every time it is run in the pool.
Answer: What I meant in my comment was something like the following Python script:
from subprocess import Popen, PIPE

foo_path = '/home/ronald/tmp'
process = Popen(['/home/ronald/tmp/shexecutor'], stdin=PIPE, cwd=foo_path)

process.stdin.write("ls\n")
process.stdin.write("echo hello\n")
process.stdin.write("quit\n")

And the shell script that executes the commands:
#!/bin/bash

while read cmdline; do
    if [ "$cmdline" == "quit" ]; then
        exit 0
    fi
    eval "$cmdline" >> x.output
done

Instead of doing an "eval", you can do virtually anything.
Note that this is just an outline of a real implementation.
You'd need to do some error handling. And if you are going to use this in a production environment, be sure to harden the code to the limit.
Comment: This makes sense. I'll try to implement it without a shell script, but If I can't this is an option. Thanks!


How is inlining more efficeny than recursive definition?

Question: My Programming Paradigms textbook, Essential of Programming Languages (3rd ed), Chapter 1 has an exercise:

Exercise 1.12
Eliminate the one call to subst-in-s-exp in subst by
replacing it by its definition and simplifying the resulting
procedure. The result will be a version of subst that does not need
subst-in-s-exp. This technique is called inlining, and is used by
optimizing compilers.

The original code would have two functions: subst and subst-in-sexp which basically substitutes the all occurrences of old symbol with new symbol in the input list.
(define subst
  (lambda (new old slist)
    (if (null? slist) '()
        (cons
         (subst-in-s-exp new old (car slist))
         (subst new old (cdr slist))))))

(define subst-in-s-exp
  (lambda (new old sexp)
    (if (symbol? sexp)
        (if (eqv? sexp old) new sexp)
        (subst new old sexp))))

The answer to this question is to eliminate subst-in-sexp, which becomes this
(define subst
  (lambda (slist old new)
    (cond
      [ (null? slist) '()]
      [ (eqv? (car slist) old) (cons new (subst (cdr slist) old new))]
      [ else (cons (car slist) (subst (cdr slist) old new))])))

Why is in-lining better besides it may be a lot shorter (less space)? Does the size of the recursion changes? In other words, does this inlining creates fewer stack elements?
Moreover, how can I use this idea to make my C++, Python, and Java code faster? Can I extend this idea easily? Thanks.
I tagged this in Scheme (actually, Racket) because this is the choice of language in the book.
Comment: Yes it should reduce overhead by few stack frames, however this is not really an issue nowadays, code readability matters more and compiler will likely optimize it into something else entirely.
Answer: Inlining is a pretty standard compiler optimization, but as AoeAoe said, it's generally better to write your code so that it's readable and let the compiler do all the inlining for you.
The immediate benefit of inlining is that it eliminates branches in your code. It means your CPU can keep reading straight down your code rather than having to spend a couple of clock cycles finding the next section of code to execute.
However, inlining has some other benefits as well. You end up with bigger chunks of code, which means the compiler has more code and data to play with. It might be able to stick more things in registers, or do constant folding to eliminate more computations. The compiler can also do a better job of instruction scheduling, because it has more instructions to move around.
The drawback is that inlining increases your resulting code size. Especially with modern CPUs running so much faster than memory, it can often be better to inline less code in order to keep all of a hot section of code in L1 cache.
Answer: Adding just a bit to Eric's answer, inlining can be a big win in dynamically typed languages, where inlining a call may make it possible for a compiler to specialize the implementation to the kinds of data that appear.
For instance: suppose I have a function called f:
(define (f x) (+ (* x x) 3.0))

... and I call it inline:
(+ (f 3.2) (g 3.9))

In this case, the inlined code makes it clear that the multiplication and addition can't be called with non-numbers, so this error check can be elided.
Answer: In answer to: "How can I use this idea to make my C++, Python, and Java code faster?"
I don't think that the Python runtime does things like automatically inlining small methods. (If this is wrong, someone please correct me!) So in Python, if you have a piece of code which is very performance-sensitive, perhaps running tens of thousands or millions of times in an inner loop, you could try inlining manually. Only do this if the code is really a bottleneck, and it really needs to be as fast as possible, and always measure to see if such optimizations are actually helping anything. (If you try inlining something and it doesn't help, it's better to undo the optimization, because inlining will generally make your code harder to read.)
In Java and C++, any good compiler will inline small methods for you. The thing which you can (sometimes) do, is help the compiler see that a method can be inlined. If the exact method which is called depends on the run-time type of an object (as when using virtual methods in C++), the compiler will not be able to inline the call. static methods in Java can easily be inlined, and declaring methods as final (when it makes sense to do so) may also make it possible for the compiler to inline.
If you learn more in the future about compilers and how they work, you will better be able to see how to write performance-sensitive code in a way that the compiler is able to optimize for you.


ColdFusion loop through struct with key evaluation fails! What am i missing?

Question: I have this code in my cfm, which works
<cfif not StructIsEmpty(form)>
 <cfset larray = user.getArray() />
 <cfloop collection="#form#" item="key">
  <cfif left(key,4) eq "UPD_">
   <cfset x = listLast(key,"_") />
   <cfset y = evaluate(0,key) />
   <cfloop index="j" from="1" to="#arrayLen(larray)#">
    <cfif (larray[j][1] eq x) and (larray[j][3] neq y)>
     <cfset larray[j][3] = y />
     <cfif not LSIsNumeric(larray[j][3])>
      <cfset larray[j][3] = "0" />
     </cfif>
     <cfset larray[j][4] = "update" />
    </cfif>
   </cfloop>
  </cfif>
 </cfloop>

 <cfloop collection="#form#" item="key">
  <cfif left(key,4) eq "DEL_">
   <cfset x = listLast(key,"_") />
   <cfloop index="k" from="1" to="#arrayLen(larray)#">
    <cfif larray[k][1] eq x>
     <cfset larray[k][4] = "delete" />
    </cfif>
   </cfloop>
  </cfif>
 </cfloop>

 <cfset user = createObject("component", "cfc.User").init(
    identifier = FormatBaseN(form.id,10),
    array = larray
    ) />
</cfif>

<form name="usform" method="POST">
<cfset array = user.getArray() />
<cfoutput>
<cfloop index="i" from="1" to="#arrayLen(array)#">

  <input type="text" name="upd_#array[i][1]#" maxlength="6" size="6" value="#array[i][3]#" />
  <input type="checkbox" name="del_#array[i][1]#" />

<input type="hidden" name="id" value="#user.getIdentifier()#" />
</cfoutput>
</form>

I have put it into a cfc to seperate my logic and my view and i am trying to make it more generic
<cfcomponent name="ArrayManager" output="false">
 <cffunction name="init" hint="constructor" output="false" returntype="ArrayManager">
  <cfargument name="user" type="User" required="true" hint="User bean" />
  <cfargument name="form" type="Struct" required="true" />
  <cfset variables.instance.array = arguments.user.getArray() />
  <cfset variables.instance.form = arguments.form />
  <cfreturn this />
 </cffunction>

 <cffunction name="update" access="public" output="true" returntype="boolean">
  <cfargument name="structstring" type="String" required="true" />
  <cfargument name="seperator" type="String" required="true" />
  <cfset var x = "0" />
  <cfset var y = "0" />
  <cfloop collection="#variables.instance.form#" item="key">
   <cfif key eq "#arguments.structstring#">
    <cfset x = listLast(key,"#arguments.seperator#") />
    <cfset y = evaluate(0,key) />
    <cfloop index="j" from="1" to="#arrayLen(variables.instance.array)#">
     <cfif (variables.instance.array[j][1] eq x) and (variables.instance.array[j][3] neq y)>
      <cfset variables.instance.array[j][3] = y />
      <cfif not LSIsNumeric(variables.instance.array[j][3])>
       <cfset variables.instance.array[j][3] = "0" />
      </cfif>
  <cfset variables.instance.array[j][4] = "update" />
 </cfif>
</cfloop>
   </cfif>
  </cfloop>
  <cfset arguments.user.init(array = variables.instance.array) />
  <cfreturn true />
 </cffunction>

 <cffunction name="delete" access="public" output="false" returntype="boolean">
  <cfargument name="structstring" type="String" required="true" />
  <cfargument name="seperator" type="String" required="true" />
  <cfset var x = "0" />
   <cfloop collection="#variables.instance.form#" item="key">
    <cfif key eq "#arguments.structstring#">
     <cfset x = listLast(key,"#arguments.seperator#") />
     <cfloop index="k" from="1" to="#arrayLen(variables.instance.array)#">
      <cfif variables.instance.array[k][1] eq x>
       <cfset variables.instance.array[k][4] = "delete" />
      </cfif>
     </cfloop>
    </cfif>
   </cfloop>
  <cfset arguments.user.init(array = variables.instance.array) />
  <cfreturn true />
 </cffunction>
</cfcomponent>

And my new cfm
<cfif not StructIsEmpty(form)>
 <cfset arraymanager = createObject("component","cfc.ArrayManager").init(user,form) />
 <cfset seperator = "_" />
 <cfset structstring = "UPD" />
 <cfset arraymanager.update(structstring,seperator) />
</cfif>
...

It fails, i get this error message

The CFML compiler encountered an unexpected coldfusion.compiler.CompilerInternalException exception.
  The reason for this was: Unable to complete CFML to Java translation. Occurred at:
.
  .
  .
The error occurred in C:\path\to\document\root\cfc\ArrayManager.cfc: line 21
  Called from C:\path\to\document\root\cfc\update-emp.cfm: line 66
  Called from C:\C:\path\to\document\root\cfc\update-emp.cfm: line 66
19 :             <cfif key eq "#arguments.structstring#">
  20:
  21 :                 <cfset y = evaluate(0,key) />
  22:
  23 `:

What am i doing wrong or is there a better way to accomplish what i am trying to do (showing database content in a table and updating(Update and Delete) the database content through the same table)
Comment: I'm with Tomalak. What is it you're trying to do?

Specifically, what are you expecting to get from  ?
Comment: I've tried wrapping my head around your code for a while now. I have no idea how to extrapolate the missing bits. What data structure are you working with? How does the FORM post look like? Why do you put everything into nested arrays?
Comment: I think this is used as a way to say "" - But honestly, I think that is lame in more ways than one.
Answer: The error message you've posted indicates that you're misusing the Evaluate function. According to the docs, it works like this:

Evaluates one or more string expressions, dynamically, from left to right. (The results of an evaluation on the left can have meaning in an expression to the right.) Returns the result of evaluating the rightmost expression.

But you've got other problems, too. For starters, you're not duplicating the logic correctly when you move the code into the CFC.
In your working code, you use the conditional:
<cfif left(key,4) eq "UPD_">

But in your CFC you have:
<cfif key eq arguments.structString>

This should be:
<cfif left(key,4) eq arguments.structString>

Next, you aren't using the best syntax for evaluate, and you probably don't want to use it at all. The statement:
y = evaluate(0,key)

can be rewritten as:
y = evaluate(key)

Since the value of key is "UPD_something", this can be rewritten as:
y = [variables|arguments|etc].UPD_Something

(Since you're not explicitly specifying a variable scope, CF will attempt to find the variable in a set of scopes in a certain order; which is why I used the syntax [a|b|...])
You probably don't mean this, you probably want the value from the form. And since the key name is dynamic, you should access it this way (instead of using evaluate):
y = variables.instance.form[key]

I think that may fix it. So, to summarize:

Replace your statement <cfif key eq arguments.structString> with <cfif left(key,4) eq arguments.structString> (And make sure that the value you pass as "structString" includes the underscore!)
Replace your use of evaluate with: y = variables.instance.form[key]

I hope that fixes your problems...
After you get it working, start thinking about your variable names. "Array" is a terrible variable name because it is practically a reserved word in CFML. And using "x" and "y" is not descriptive at all. These types of problems are what made this question hard to answer.
Comment: +1 Very nice. I've had something similar ready, but after I became insecure if I fully understood the purpose of the original code, I was hesitant to post it. I guess I'll just post the advisory part.
Answer: I fully agree to Adam Tuttle's post. I've removed the "solution part" part of my answer in favor of his. So here's my two cents regarding the "general part":
Avoiding Evaluate() altogether is the best thing you can do. There is no reason to use it apart from actually evaluating pieces of code (which is another bag of hurt that should be avoided). If that's not what you are doing, then there is no situation that could not be resolved through something more appropriate than Evaluate(), e.g.:
<cfset foo = Evaluate("FORM.#foo#")>

is equal to:
<cfset foo = FORM[foo]>

All of the "conveniency" misuses of Evaluate() can be addressed like this.
A few more tips:

Avoid meaningless variable names like "x" or "y" (unless you refer to 2D-coordinates, of course).
Don't do "#variable#" - you can simply use variable instead.
Use Structs wherever you can when you need to access items with a key, e.g.
<cfif array[i][1] eq SomeValue> is a lot less elegant than
<cfif array[i]["FieldName"] eq SomeValue>
You don't really need "variables.instance" - every component instance has it's own VARIABLES scope. Whatever you stick in there is "instance-only" by default.
No need to pass in the FORM scope to a component. The scope is global, so CFCs can see it anyway.
Why do you store database stuff in an extra array instead of using the Query object you got when you retrieved them?
No need to self-close ("/>") CFML statements - you are not writing XML (though that's a matter of taste).
Comment: I disagree on the bit about passing in the form scope. I consider it part of decoupling the component from the page that uses it. Same goes for application scope, session scope, etc (99% of the time)... Generally, you shouldn't directly access them from a CFC.
Comment: I'm also a fan of XML/XHTML-formatted CFML tags, but as you said, it's a stylistic choice to be made by the developer. I find that they make it more obvious when a tag in a deeply nested situation does or does not have children; especially helpful when a peer's IDE messes with your indentation.
Comment: Hm, I would personally crucify anyone who messes with my indentation. But that's a matter of taste again. ;-) In any case, I don't really see a reason _not_ to use APPLICATION, SESSION, etc. in a CFC, if the CFC is part of the app (and not part of a general-purpose framework). I just don't like to repeat myself in the cffunction arguments all the time. What's the telling argument against that?
Comment: i store the database stuff in a object bean, where i save more than just the array information. the meaningless names where just an example. I agree with Adam, i think passing the form scope to the component makes it clearer that the component is supposed to use it. i see i have much to learn, programming for only 4 weeks now.


regex to match a string among white space (JavaScript)

Question: I try to match a string among white spaces.
I just thought it's as simple as \S*, but does not work
http://regex101.com/r/jC0uA5
What do I miss??
EDIT:
I also thought
It's as simple as.
http://regex101.com/r/zD4vN8
\S.*\S

but this does match only more than 2 characters.
Answer: You almost had it...
* matches zero or more characters.
Try \S+
Answer: Simply do: \S+
I am assuming that you do not require whitespace around the string, but that you want to ignore it if it is there.
Your previous regular expression of \S* was actually matching, but the first match returned was an empty string.
For clarification, do you wish to also match whitespace within the string, or is your meaning of "string" intended to include only non-whitespace?


Passing data using blocks in Objective-C

Question: I have two viewcontrollers, ViewControllerA and ViewControllerB respectively.
On ViewcontrollerB there are tableview cells. On click of tableview cells I want to send the data selected on ViewControllerB to label on ViewControllerA.
I know it can be achieved through many ways but how can this be achieved through blocks.Kindly suggest.
Thanks in advance!
ViewController B
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *viewArr = [self.array objectAtIndex:indexPath.row];

    NSLog(@"the value obtained on cell is %@",viewArr);
    ViewController *vc=[[ViewController alloc]init];
    vc.aSimpleBlock(viewArr);
}

Comment: in blocks also we can do int in multiple ways, can you show ur tried code
Comment: I have not implemented it through blocks,i have done it using delegates...but now i want to achieve the same through bocks...but not able to understand the correct way to implement.
Comment: ok I add some sample
Comment: You can use NSNotifications too.
Answer: In your ViewController A
1) Declare a typedef for block say typedef void (^simpleBlock)(NSString*);
2) Create a block variable like
@property(nonatomic,strong)simpleBlock  aSimpleBlock;

3) Define this block in viewDidAppear / viewDidLoad
aSimpleBlock = ^(NSString* str){
        NSLog(@"Str is the string passed on tableView Cell Click..!!");
    };

In your ViewController B Where you have tableView
1) In -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
just call your block as
your_VC_A_Object.aSimpleBlock("Your_Label_String_here");

Comment: It gives EXC_BAD_ACCESS exception when following line is executed  : your_VC_A_Object.aSimpleBlock("Your_Label_String_here");
Comment: @TestShroff You are creating new object there. No need to create new object, just pass the object reference from where you are navigating to VC B. When you create new instance , it will create new block variable so you will not be able to reference the same block.
Comment: @TestShroff Welcome .. and if this solves your problem, mark it as correct answer so that the other members can find it useful. Happy coding..!!
Comment: "just pass the object reference from where you are navigating to VC B."explain this a little more please.
Comment: Say you are navigating from VC1 to VC2. Then create VC1 variable in VC2 (but don't initialize it with alloc init). Now when you are going to push VC2, do like this: VC2_object.VC1_Variable_you_created = self.
Comment: You could also just define a regular method in A and call it from B. What advantage do you get from using a block instead?
Comment: @BrettDonald  Yes we can do this with simple method also. But I think I have answered 'I know it can be achieved through many ways but how can this be achieved through blocks.Kindly suggest.' this. Second thing, the advantage of blocks is blocks are faster than delegates also using blocks we can have the inline execution which makes code more readable.
Comment: Have a look at this :http://stackoverflow.com/questions/12176961/what-is-the-purpose-of-using-blocks
Comment: So, @TestShroff, did you try it? What do you think of the result? Do you prefer the delegate code or the block code? Why?
Comment: @Brett Donald  yes,i have implemeted it .I know it can be achieved through other ways also...but just to understand blocks i wanted to implement using blocks.
Answer: You can define a block in viewControllerB and set it ViewController A, when select a cell, you can call this block and pass the value to it, something like:
In viewControllerB
// ViewControllerB.h
@interface ViewControllerB : UITableViewController

@property (nonatomic, copy) void (^didSelectCellBlock)(id obj);
@end

// ViewControllerB.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        NSString *str = [self.dataArray objectAtIndex:indexPath.row];
        if (self.didSelectCellBlock) {
            self.didSelectCellBlock(str);
        }
        ...
    }
}

And In ViewController A
 ViewControllerB *controllerB = [[ViewControllerB alloc] init];
 __weak __typeof(self) weakSelf = self;
 controllerB.didSelectCellBlock = ^(id obj) {
     weakSelf.label.text = (NSString *)obj;
 };

Answer: step-1
initially add parent class of VC-B to VC-A
@interface ViewControllerA : ViewControllerB

Step-2
create the one common method in interface on ViewControllerB
@interface ViewControllerB : UIViewController

-(void)shareContent:(NSString*)currentText;

step-3
on that ViewControllerB implementation file
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
     __weak typeof(self) weakSelf = self;

      dispatch_async(dispatch_get_main_queue(), ^ {

         [weakSelf shareContent: [_items objectAtIndex:indexPath.row]];

    });

}

Step-4
on your ViewControllerA implementation file
 -(void)shareContent:(NSString*)currentText
 {

   NSLog(@"Local details:%@", currentText);
 }

Choice -2

for alternate Way , you can get the sample from here or example
Answer: I don't know if that's sensible or even possible.
To pass data directly between view controllers, I often use delegates. I would add a delegate property to B and have it define a delegate protocol. I would have A implement that protocol and have B invoke those protocol methods to pass the data. And, of course, set B's delegate to A.
Comment: Yes it's possible and even feasible as blocks are faster than delegates also using blocks we can have the inline execution which makes code more readable. But it is also true that you can't replace delegates everywhere with blocks, sometimes delegates are essential rather than blocks.
Answer: Well in that case you'd have to provide a block from ViewControllerA so the other one (ViewControllerB) can handle it (as a property), retain it and call when you select the table row.
But the benefit over the delegation? Not much in fact, delegation is way more a standard pattern to use in this case.
Comment: In fact delegation is better because (a) it's the standard pattern, and (b) it avoids A and B being dependent on each other. Using delegation keeps B independent.
Comment: @michi and Brett Donald I think you guys should have a look at this :http://stackoverflow.com/questions/12176961/what-is-the-purpose-of-using-blocks
Comment: Blocks are certainly valuable in many situations. I just don't think they're the right choice in THIS situation.


Handling some keys while textbox is focused

Question: So, apparently I had some problem when handling keys such as F10 or F11.
I want to move the focus from current textbox into another textbox, but not in one particular textbox. So, I wrote some code to handle key:
private void checkKeys(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F10)
            {
                buyerName.Focus();
            }
            else if (e.KeyCode == Keys.F11)
            {
                discount.Focus();
            }
        }

But, if I put this into individual textbox, which kinda hassle to me. Is there any method to listen key whether in global userControl or textbox?
Edit :  here's my structure that I want to ask :
Form-
    |-User Control
     |-TextBox

Edit 2 :  here's some image might help img
Comment: I agree that this would accomplish the same result, and I have updated my answer. But I do not agree that this is the "Correct Way" it is more 'Another Way".
Comment: The correct way of handling shortcut keys is to override `ProcessCmdKey` method of the `Form`.
Answer: To use a global keyboard listener in Winforms, you just need to add a handler to KeyUp action for the main form itself:
private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.F10)
        {
            textBox1.Focus();
            e.Handled = true; //To use F10, you need to set the handled state to true
        } else if (e.KeyCode == Keys.F11)
        {
            textBox2.Focus();
        }
    }

Then make sure that the KeyPreview property on the main form is set to True.

The issue with the application freezing when pressing F10 is because it is waiting for another consecutive action. To bypass this simply set the Handled property on the keyevent to TRUE. This releases the unresolved event.
This is my entire form class, refactored to use a helper method as you are refering to. This works fine. But you have to make sure that the KeyPreview property on your form is True, unless your keypresses will not be matched to your event handlers.
namespace KeyTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            CheckKeys(e);
        }

        private void CheckKeys(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F10)
            {
                textBox1.Focus();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.F11)
            {
                textBox2.Focus();
                e.Handled = true;
            }
        }
    }
}

Now in your comment you are mentioning a UserControl, if you want that, then you need to create an instance method on your UserControl class, and pass the event to that from your global keyboard event handler on your main form.
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public void HandleKeys(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.F10)
        {
            textBox1.Focus();
            e.Handled = true;
        }
        else if (e.KeyCode == Keys.F11)
        {
            textBox2.Focus();
            e.Handled = true;
        }
    }
}

Then on your main form:
public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            CheckKeys(e);
        }

        private void CheckKeys(KeyEventArgs e)
        {
            uc1.HandleKeys(e); //Instance method on your user control.
        }
    }

This then works as intended.
As pointed out in one of the comments, a better way would be to override the ProcessCmdKey method on the Form base class. This would be done like so:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        userControl11.HandleKeys(keyData); // method on the userControl to handle the key code.
        base.ProcessCmdKey(ref msg, keyData);
        return true;
    }

}

The handler on the UserControl stays more or less the same:
public void HandleKeys(Keys keys)
    {
        if (keys == Keys.F10)
        {
            nameTB.Focus();
        } else if (keys == Keys.F11)
        {
            emailTB.Focus();
        }
    }

Whether this is a more correct way of doing it, I am unsure of. They certainly both accomplish the same result. The documentation shows the first method in for handling keyboard events at the form level here:
How to handle keyboard input
But states here that the ProcessCmdKey method is to provide additional handling of shortcuts and MDI accellerators.
ProcessCmdKey
I will leave that up to you to decide what is the best for your scenario. But keep it in to show how you would use it should you choose to.
Comment: Sorry, fixed that :)
Comment: well, somehow i pressed f10 after tried your code inside textbox. it's kinda freeze for a while, and didn't move it's focus
Comment: That sound strange, do you have multiple KeyUp handlers going on at once perhaps?
Comment: nope, just couple keypressEvent inside textbox to detect ```Enter``` key to move it focus.
Comment: Just checked that out, when you use F10 it freezes until one additional input. I believe that is because F10 is used as a System Call short cut. I was able to reproduce this, but changing the listener to use F9 instead of F10 fixed the issue.
Comment: It just work as well. But, the focus won't move. I make a method inside the ```userControl``` to handle focus via ```MainForm``` class. But still, there's no luck :( . You might see the picture I added in my questions.
Answer: Thanks to @Espen and @reza-aghaei for handling keys into main form. Unfortunately, I still didn't managed find a way to focus to designated textbox inside a UserControl. However, I make some dirty method which kinda crappy and un-efficient by searching child control from it's parent
//MainForm.cs
if(yourUserControl.Name)//Do some check for targeted userControl, if null can cause NullReferenceException
{
   if (e.KeyCode == Keys.F10)
   {
     this.Controls.Find("textboxName", true).First().Focus();
     e.Handled = true;
   }
}

Answer: You can hook up to the KeyUp event of your form.
That way, any key pressed while your form is focused will be send to you (if the control didn't handle the key).


How do I fix a ReflectionException error (class doesn't exist)?

Question: I'm new to drupal 8. I would like to extend the user login form by deleting the username field and adding the email field. So I created a custom module, I implemented an Event Subscriber and declared it as a service :
services:
    mdmuser.route_subscriber:
        class: Drupal\mdm_user\Routing\RouteSubscriber
        tags:
             - {name: event_subscriber }

And here's my class RouteSubscriber
 <?php

 /**
 * @file
 * Contains \Drupal\mdm_user\Routing\RouteSubscriber.
 */

 namespace Drupal\mdm_user\Routing;

 use Drupal\Core\Routing\RouteSubscriberBase;
 use Symfony\Component\Routing\RouteCollection;

 /**
 * Listens to the dynamic route events.
 */
 class RouteSubscriber extends RouteSubscriberBase {

 protected function alterRoutes(RouteCollection $collection) {

     if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\mdm_user\Form\UserLoginForm');
      $collection->add('user.login', $route);
    }
  }
}

I have this error when I want to install my new module :
ReflectionException: Class Drupal\mdm_user\Routing\RouteSubscriber does not exist in ReflectionClass->__construct() (line 31 of core/lib/Drupal/Core/DependencyInjection/Compiler/RegisterEventSubscribersPass.php).

Any idea is appreciated !
Thanks
Comment: What's the path to the file? It should be: /modules/mdm_user/src/Routing/RouteSubscriber.php
Comment: Yes, it looks good : modules/custom/mdm_user/src/Routing/RouteSubscriber.php
Comment: Have you done a cache rebuild since adding the code?
Comment: I cleared cache again, the module is installed. But it seems my EventSubscriber is not caught. Thank you for your help !
Comment: There already exists a module that introduces changing the username to an email field in the login flow. so I don't recommend reinventing the wheel here. The module is called [Email Registration](https://www.drupal.org/project/email_registration).
Comment: You need to check your route define in routing.yml file .. or check that your controller file is place inside src/Controller folder. Cheer !!!!!!!!!!!
Answer: It has to be the file structure.  Check again that it's at /modules/custom/mdm_user/src/Routing/RouteSubscriber.php
Also, in your class, you don't need to add the route again, it's passed by reference.
You can remove
$collection->add('user.login', $route);

Answer: If you are getting above error message then I suggests following things to check for,

Check if there are any spelling mistakes in the routing file, that
is may be the name  you have written is something and the file name
is something else.
Check the class name defined in the controller file matches the file name
Folder structure is something like '\Drupal\module_name\src\Controller\exampleConfig.php' but the routing file will have something like this "\Drupal\module_name\Controller\exampleConfig" don't worry about the "src" folder
Check your namespace if it exists or not and if properly written or not
Check for unnecessary extra lines in *.routing.yml of your module.
Add 'Controller' to end of file with your Controller Class and to end of Class Name of Controller.

I have the approach of issue with below:
Try command in bash near web/ dir of drupal  'drupal gcon', see also
Hope this helps.
Happy Coding....
Answer: Ran into the same issue. It ended up being stupid mistake in my namespace in my RouteSubscriper.php file. I had:
namespace Drupal\my_module\Routing\RouteSubscriber;

When it should have been:
namespace Drupal\my_module\Routing;


insert an element into a sorted linked list

Question: we had to implement the insert function that can insert a cell into a sorted linked list. My implementation idea was to have two rlists, called previous and current, that will be used to iterate through the list.  At the beginning of the function call, the previous rlist will contain a random integer, and its next field is pointing to the current cell which is the head of the linked_list. I think this is problematic. I finished implementing my idea. I think the method will add the correct integer at the right place in the linked list. However, if the inserted element is at the beginning of the list, then the list is still the old list when using displaying on to the screen, but the old list does indeed have a cell pointing to it, and that cell has the inserted integer.  So I'm not sure how to deal with that.
 I tested my method, and it doesn't work as I described.
Here is what I did: I inserted -9 to the end of c3. c3 does indeed get -9 at the end of the list.  And then I added 4 inside c5. But then c5 now becomes [5;4;-9]. So it is wrong, it should have [5;4;3;2;1;-9] instead.  So I don't know what is wrong.
I looked up online on how to implement the method so that they can give me some inspirations or hint, but the solutions they provided are usually in Java or other programming languages.
type cell = { data : int; next : rlist}
and rlist = cell option ref

let c1 = {data = 1; next = ref None}
let c2 = {data = 2; next = ref (Some c1)}
let c3 = {data = 3; next = ref (Some c2)}
let c5 = {data = 5; next = ref (Some c3)}

let rec displayList (c : rlist) =
  match !c with
  | None -> []
  | Some { data = d; next = l } -> d :: (displayList l)

let cell2rlist (c : cell) :rlist = ref (Some c)

let bigger((x:int), (y:int)) = (x > y)

let insert (comp : (int * int) -> bool) (item : int) (listt :rlist)=
  let itemm = {data=item ; next = ref None} in
  let rec helper (prev : rlist) (item : cell) (current: rlist) funcc =
    match !current with
    |None -> (match !prev with
        |Some w -> w.next := (Some itemm))
    |Some q -> if comp (item.data, q.data) then (itemm.next := (Some q) ; match !prev with
      |Some w -> w.next := (Some itemm))
        else  prev := !current; current:= !(q.next); (helper prev item current funcc)
  in let previous = ref (Some {data=0; next = listt}) in
  helper previous itemm listt comp

Here are examples of the right return values for the code in action:
 let l5 = cell2rlist c5;;
val l5 : rlist = ....
(* Messy display deleted. *)

 displayList l5;;
- : int list = [5; 3; 2; 1]

 displayList l5;;
- : int list = [5; 3; 2; 1]

 insert bigger 4 l5;;
- : unit = ()

 displayList l5;;
- : int list = [5; 4; 3; 2; 1]

 insert bigger 9 l5;;
- : unit = ()

 displayList l5;;
- : int list = [9; 5; 4; 3; 2; 1]

 insert bigger 0 l5;;
- : unit = ()

 displayList l5;;
- : int list = [9; 5; 4; 3; 2; 1; 0]

But when I ran my codes, here is what I get:
insert bigger 10 (ref(Some c5)) ;;
- : unit = ()

c5 ;;
- : cell =
{data = 5;
 next =
  {contents =
    Some
     {data = 3;
      next =
       {contents =
         Some
          {data = 2;
           next = {contents = Some {data = 1; next = {contents = None}}}}}}}}

As you can see, if I insert a number that is supposed to be inserted at the beginning of the list, I can't see it.
Here is another example,
insert bigger 4 (ref(Some c5)) ;;
- : unit = ()

c5 ;;
- : cell =
{data = 5;
 next =
  {contents =
    Some
     {data = 4;
      next = {contents = Some {data = 1; next = {contents = None}}}}}}

So as you see the code doesn't work at all as the updated list should have values [5;4;3;2;1] but it has [5;4;1] instead.
Here is another example:
insert bigger (-9) (ref(Some c3)) ;;
- : unit = ()

c3 ;;
- : cell =
{data = 3;
 next =
  {contents =
    Some
     {data = 2;
      next =
       {contents =
         Some
          {data = 1;
           next = {contents = Some {data = -9; next = {contents = None}}}}}}}}

So it seems that the method does insert the element correctly into the list, but the lists that the inserted cell suppose to point to seem to be wrong.
Comment: It would be more helpful if you would give an example where your code is failing rather than examples of how it's supposed to work.
Answer: For reference, here is a session showing a failure of your code:
# let (l: rlist) = ref None;;
val l : rlist = {contents = None}
# insert bigger 1 l;;
- : unit = ()
# l;;
- : rlist = {contents = Some {data = 1; next = {contents = None}}}
# insert bigger 0 l;;
- : unit = ()
# l;;
- : rlist = {contents = None}

For what it's worth, it would also be good if your code was indented properly.
At any rate, what I see when I look at your code for a short time is this fragment:
current:= !(q.next);
helper prev item current funcc

It looks to me like you're imagining that the first line here will advance some local variable to point to the next element of the list. But what it actually is doing is modifying the list.
You might want something more like this:
helper prev item q.next funcc

There are other problems in your code as well. It seems odd, for example, that the then part is parenthesized but the else part isn't parenthesized.


Qual a vantagem de usar o método Set<>?

Question: Qual a vantagem ou diferença em utilizar o método Set<> sendo que eu posso fazer a mesma coisa sem ele como na alternativa 2?
Alternativa 1
var aluno = contexto.Alunos.First(x => x.Id == entidade.Id);
contexto.Set<**Aluno**>().Remove(aluno);
contexto.SaveChanges();

Alternativa 2
var aluno = contexto.Alunos.First(x => x.Id == entidade.Id);
contexto.Alunos.Remove(aluno);
contexto.SaveChanges();

Answer: A vantagem na verdade existe quando você quer implementar um comportamento genérico em alguma função sua.
Por exemplo, você quer escrever um método que traga apenas os 10 primeiros registros de qualquer DbSet. Você pode fazer da seguinte forma:
public IEnumerable<T> PrimeirosDez<T>() {
    return contexto.Set<T>().Take(10).ToList();
}

Ou seja, implemento uma extensão para o contexto que traz os 10 primeiros elementos para qualquer DbSet.
Uso:
var teste = PrimeirosDez<Aluno>();
var teste2 = PrimeirosDez<Professor>();

Comment: Cigado, mas o T não foi definido com um tipo específico para ser usado? Como no exemplo que você deu, T espera um classe podendo ser Aluno ou Professor?
Comment: Você pode limitar `T` usando uma sintaxe assim: `public IEnumerable PrimeirosDez() where T: class, IMinhaInterface { ... }`
Answer: A escolha entre utilizar o método DbContext.Set ou o objeto DbSet instanciado no Contexto depende da utilização e de como você trabalha com o contexto.
O método DbContext.Set<T> retorna utilizando Generics o DbSet do contexto, avaliando o parâmetro de tipo da assinatura do método. Isso demonstra que quando chamamos o mesmo, ele realiza uma "pesquisa" nos objetos do contexto e "carrega" os dados daquele tipo dentro do Contexto.
O objeto DbSet<T> do Contexto é um objeto que em tese é carregado quando você instância o Contexto e este objeto é pré carregado para a utilização dentro da aplicação.
Os dois métodos realizam praticamente a mesma coisa, porém em momentos diferentes. Outro fator que pode influenciar na utilização de um ou de outro é a exposição dos objetos entre bibliotecas e namespaces diferentes. Se você repassar o seu contexto para um método utilizando a classe DbContext no enunciado deste método, você não tem conhecimento dos DbSets do contexto, portanto a forma de carregar os dados é utilizando o DbSet genérico. Abaixo um pequeno exemplo:
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Collections.Generic;

public class Contexto : DbContext
{
    public DbSet<Aluno> Alunos { get; set; }

    public Contexto()
    {
        Configuration.LazyLoadingEnabled = true;
        Configuration.AutoDetectChangesEnabled = false;
        Configuration.ValidateOnSaveEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    }
}

public class Aluno
{
    public String Nome { get; set; }
}

public class Program
{
    public List<Aluno> GetAlunos(DbContext ctx)
    {
        // O compilador não irá reconhecer se chamarmos o DbSet ctx.Alunos.
        return ctx.Set<Aluno>().ToList();
    }

    public List<Aluno> GetAlunos2(Contexto ctx)
    {
        return ctx.Alunos.ToList();
    }
}

Answer: Neste caso específico realmente não há vantagem. Use a segunda forma.
Este método foi criado para situação onde você não sabe com que tipo de dado está trabalhando, ou seja, quando está escrevendo código genérico:
contexto.Set<T>();

Coloquei no GitHub para referência futura.
Eu sei que tem alguma vantagem quando se está usando migrations mas não conheço em profundidade.
Comment: Então, quando você está escrevendo um código genérico você vai usar um "tipo variável", ou seja, o `T`. Depois quando for usar estes código que você escreveu aí você vai passar o tipo que está usando para ser substituído em `T`. Mas aí você não estará usando o tipo (no seu exemplo `Aluno`) no `Set<>` e sim no seu código. Ou seja, o `Set<>` serve só para produzir código genéricos e não para consumir códigos genéricos. Se você sabe que vai usar sempre `Aluno` não produza um código genérico. Está criando um código genérico?Acho que não.Então use o `contexto.Alunos.Remove(aluno)` e não se preocupe
Comment: bigown, mas com genérico eu não especifico um tipo determinado, diferente de collections?

Qual a vantagem de usar o método Set<>?