Causality and time

Question: In every instance of A and B (A and B always occur when either occurs), A always comes before B.
In such cases, it can be inferred that A causes (predicts) B.
Does a single instance of B coming before A discredit this?
Consider the alleged theoretical reason against information traveling faster than the speed of light - causality. Consider that in every instance of A and B,  that A comes before B, and then based on this you conclude that A causes B. That is, that A PREDICTS B. But if in one instance B happens before A, there IS a case where B comes before A. Is this sufficient to say that causality has not been established? If so, why is it necessary for A to always come before B in order to say A causes B? By what PROOF does A always have to precede B in every instance in order to establish causality? Is it sufficient to say that, in all instances of A and B, that A almost always has to come before B, to infer causality? Is it established that B can never come before A?
In terms of faster than light travel, A is the information about the launch, travelling at the speed of light, arriving at point X. B is the arrival of the space craft at  X. The theory is that A HAS to occur before B, or the basic inviolate tenants of causality are breached. My ultimate question is, 'is there any proof in statistics that supports this'?
Comment: Every time I have danced at night, the sun came up the next day.  What powers I must have over the heavens!
Comment: Whole books (MANY books) have been written about this. Since you asked on a statistics website, I'd suggest _Causality_ by Judea Pearl. But there's lots of others in statistics and also a bunch in philosophy.
Comment: My point is that Granger causality is explicitly NOT the same thing as causality. So explaining something that you get with causality but you don't necessarily get with Granger causality would be showing *how* Granger "causality" is not in fact causality in the usual sense. Surely this is not remotely controversial. Granger causality is a useful concept, but we should not read more into the use of the word *causality* in the name than was really intended.
Comment: Consider the possibility that there is some other $N$ (which you may not even be aware exists!) that causes $A$ and then causes $B$. While $A$ and $B$ are not causally linked ($N$ just causes each in turn), $B$ always follows $A$. How will you rule out this scenario? Answering that question well will help bridge part of the gap here. [e.g. If I notice that if I see lots of people carrying umbrellas in the morning (even though it's not raining then) then it's almost certain to rain that day, I might imagine that it's at least partly causal, but actually it has no effect at all.]
Comment: As far as I know, the idea that causality flows unidirectionally in time is taken as an axiom, it's not proven using statistics. Philosophers work on choosing the axioms. Statistics gives us tools to learn about particular causal relationships, when the axioms apply. If you are a time traveler, we shouldn't assume our methods work on you. :)

We do know that causation can be simultaneous - e.g. the simultaneous transfer of information between entangled particles in quantum physics. So on the quantum scale, the statistical tools we use to learn about causation would no longer work.
Comment: you stated "A and B". does B happen without A; or A without B?
Comment: To clarify, the wording is 'In EVERY instance of A and B, A ALWAYS comes before B'. Thus, every A AND every B occur together. If A occurs, it MUST occur before B, therefore B MUST occur when A occurs.
Comment: It might make sense to migrate this to Philosophy SE.
Comment: Philosophy does not quite fit. 'Statistics' because of the 'probability of B given A' connection. I know what 'conventional' physics says, but it always reverts back to 'time' as being 'linear', 'sequential'. If there are four red socks in a box and one blue one, and I draw out the blue one, what is the probability the next draw is a red sock? Drawing out the blue sock does not 'cause' the next sock to be red, it always WAS red. The CAUSE of the next sock being red was already established from the original composition. Drawing the blue sock didn't cause the remaining socks to turn red.
Comment: @Glen_b, I believe this would be covered by Granger causality. That is, does 'predictive ability' denote 'causality'? And if you arrive at the same usable, useful and meaningful conclusion, that it is almost certain to rain, does it make any difference if it is predictive or causal? In either case, you have a good idea of weather or not to prepare for rain.
Comment: @Justin The difference between predictive and causal is crucial in exactly the way I explained above -- if you try to *directly manipulate* a predictive-but-not-actually-causal variable in order to effect the thing it predicts, you get nowhere. If you want to *use* causality, you have to pull the right lever and past predictive behavior is useless. As an example, an increase or decrease in the number of Catholic priests in a city is reasonably highly predictive of the number of fires per year in that city, but a policy of removing priests will be useless at reducing fires.
Comment: @Glen_b I do not see that requirement in Granger causality. My background is not statistics, but it is germane to my research - causality and time line - does the cause ALWAYS have to appear to occur BEFORE the event?  Thus, if the meaning of 'causality' and 'prediction' is in dispute, this in part addresses the issue.
Comment: @Glen_b It is my understanding that there IS controversy over the issue. Guns cause death, but if you eliminate guns, you do not eliminate deaths. Your test  of the existence of causality assumes a one-to-one mapping. It does not allow for other causes. The key is the phrase 'the usual sense'. Granger causality is, well, an unusual sense. That does not make it illegitimate.
Comment: You're completely misrepresenting my position -- indeed you seem quite determined to argue with people instead of coming any closer to understanding the issues. While it's of no great concern to me whether you care to understand the various issues with the question I am trying to convey (a number of mistaken premises), it brings you no closer to having an open question.
Comment: @Glen_b, my question is specific and clear, unambiguous, and clearly in the realm of statistics. It has an unambiguous answer, if a proof exists. Perhaps the reason for my being put on hold, is that the posters on this site just don't know, and do not want to admit it. Another presentation of the question: given events A and B, where A comes before B, statistics has considered P(B|A). My question is, why not P(A|B)? Is this just ASSUMED to be absurd, or is it PROVEN to be absurd? Remember, Granger causality was assumed to be absurd until applications were discovered, THEN people wanted proof.
Comment: @Lizzie Silver simultaneous causation also applies when you put two balloons in a box that is larger than one but not larger than both. Each balloon simultaneously deforms the other as they are pushed in. It's not  one balloon goes in, and the other forms around it. Newtons' Law is also simultaneous causation. I suspected it was an axiom in statistics, but I still need it clarified.  I find it regarded as an assumption not an axiom. Axioms have surprises. 1=1 is an axiom (equality) but 10=9.999999... is provable by math and routine assumptions.
Answer: Let $A$ be the event "a hurricane warning is issued", and $B$ "a hurricane arrives." In the past X years, $A$ has always preceded $B$, because the weather service is pretty good. Does $A$ cause $B$?
Comment: @Aksakal That merely serves to demonstrate that "Granger causality" *is not causality*, at least not in anything like the usual sense. If the weather service now attempted to prevent hurricanes by no longer predicting any, they'd fail, horribly -- while if it was causal in anything like the usual sense, it should succeed.  Granger causality is a jargon term with an entirely different meaning to the usual thing "causality" is taken to mean. It's a useful concept in its intended application area, but we should be careful not to conflate it with causality in what seems to be the intended sense.
Comment: Without experiments it's impossible to establish causality based on solely observations.
Comment: Yes, in the sense of [Granger causality](http://www.scholarpedia.org/article/Granger_causality).
Comment: Regarding Granger causality, what is the difference between 'predictability' and 'causality'? If A always predicts B, and always comes before B, then does the existence of A cause B?

Causality and time


ReadWriteLock in Java

Question: I want to be sure:
read lock:
If a thread is inside a read lock also another thread can enter in this read or in another read lock but any threads can enter in a write lock while 1 or more threads are in inside in a read lock.
write lock:
if a thread is inside in a write lock any threads can enter in a write lock or in a read lock.
Comment: There is no correlation between you being sure and how `ReadWriteLock` works.
Comment: why not ??? i think that the reply that i received is the same thing that i said no?
Answer: Read lock: other threads can also take a read lock, but no thread can hold a write lock.
Write lock: held by at most one thread; no threads can hold a read lock.
So: you can have one of:

no readers or writers
one or more readers and no writers
no readers and exactly one writer
Comment: If by "any" you mean "no" then you read right (e.g. "if a thread is inside in a write lock [then] *no* [other] threads can enter in a write lock or in a read lock").

ReadWriteLock in Java


How can I scale down everything that Lilypond is outputting?

Question: How can I scale down/shrink everything that Lilypond is outputting so that I can fit more material on each page? I tried using
\layout{
    #(layout-set-staff-size XX)
}

inside the \score{} block (where XX can be any number), to just change the staff size, but this screws up the overall look and relative dimensions, so it's not what I want.
Answer: I think that you want
#(set-global-staff-size XX)

Here is the lilypond 2.19 staff size documentation (also works in 2.18).
Note that you don't put this command inside the \layout block; the following is what I've tested/verified (v2.18) in constructing this answer:
#(set-global-staff-size 36 )
\relative c'{
  c d e g f g a c e e d2
 }

Comment: `"Here is the lilypond 2.19 staff size documentation (also works in 2.18)."` I think this is a little confusing, since his example is the second option there.  I had the same problem once I did not notice this was the `2.19` documentation and the second option is not working properly in `2.18`
Comment: @nath I referenced the 2.19 (current) documentation, but on my own machine I'm running 2.18, so that is how I verified it.  It worked for me.


How can I prove that a polynomial with degree $n$ is continuous everywhere in $\mathbb{R}$ using definitions?

Question: How can I prove that a polynomial with degree $n$ is continuous everywhere in $\mathbb{R}$ using definitions?
With induction. I can show that this polynomial is continuous at $x_0$ but I do not know how to prove that it is continuous everywhere in $\mathbb{R}$. I know that a function is continuous on an interval if it is continuous at every point on the interval but this implies that I need to show for every $x_0\in\mathbb{R}$, the polynomial is continuous.
Comment: Related: http://math.stackexchange.com/questions/314552/proving-that-all-polynomials-are-continuous
Comment: Your question is not clear. Saying "I can show that this polynomial is continuous at $x_0$", which $x_0$ do you mean, it is not mentioned in the statement you want to prove. If it is an arbitrary real number, your proof is complete. Did you maybe mean instead that you proved continuity at $x=0$?
Comment: No, I meant arbitrary $x_0$.
Answer:
$f(x)=x$ is continuous everywhere
If $f(x)$ and $g(x)$ are continuous in $D$ then $f(x)g(x)$ in continuous on $D$.
Using 2 and 1 show that $x^n$ is continuous for every $n\in \mathbb{N}$
If $f(x)$ and $g(x)$ are continuous on $D$ then $f(x)+g(x)$ is continous on $D$
Now use 3 and 4.
Comment: Hi, I've follow your steps and would like to check if my proof is okay
1)elementary proof
2)algebraic property of coninuous functions proof
3) Proof: If f1(x)=x and f2(x)=x are both continuous on D then f1(x)f2(x)=x^2 is continuous. Hence we can conclude that f1(x)....fm(x)=x^n, for n=m(m+1)/2 is continuous on D.
4)algebraic property of continuous functions
5)proof: from 3) we know that x^n is contionuous on D and hence if we add a polynomial of degree n-1 or smaller then by 4) we can conclude that x^n+x^(n-1)+...+1 is continuous.
Hence all polynomials are continuous.
Comment: @ThePoorJew. Yes looks okay
Answer: Using the definition of a limit it is easy to prove (and you should prove as a simple exercise) that $$\lim_{x \to a}k = k, \lim_{x \to a}x = a\tag{1}$$ Using these results and induction and laws of algebra of limits it is an easy matter to prove that any polynomial function $f$ with real coefficients is continuous everywhere.
We will use induction on the degree of a polynomial. Polynomials of degree $0$ are constants and by first result in $(1)$ a constant is continuous everywhere. Now we assume that any polynomial of degree less than $n$ is continuous everywhere and let $f$ be a polynomial of degree $n$. Let $a$ be any arbitrary real number. Let $$f(x) = a_{0}x^{n} + a_{1}x^{n - 1} + \cdots + a_{n - 1}x + a_{n}$$ and then we have
\begin{align}
\lim_{x \to a}f(x) &= \lim_{x \to a}a_{0}x^{n} + a_{1}x^{n - 1} + \cdots + a_{n - 1}x + a_{n}\notag\\
&= \lim_{x \to a}x(a_{0}x^{n - 1} + a_{1}x^{n - 2} + \cdots + a_{n - 1}) + a_{n}\notag\\
&= \lim_{x \to a}xg(x) + a_{n}\notag\\
&\,\,\,\,\,\,\,\,\text{(note that }g(x)\text{ is a polynomial of degree }(n - 1))\notag\\
&= \lim_{x \to a}x\cdot\lim_{x \to a}g(x) + \lim_{x \to a}a_{n}\text{ (laws of algebra of limits)}\notag\\
&= ag(a) + a_{n}\text{ (}g(x)\text{ is continuous and using (1))}\notag\\
&= a(a_{0}a^{n - 1} + a_{1}a^{n - 2} + \cdots + a_{n - 1}) + a_{n}\notag\\
&= a_{0}a^{n} + a_{1}a^{n - 1} + \cdots + a_{n - 1}a + a_{n}\notag\\
&= f(a)\notag
\end{align}
Hence polynomial $f(x)$ is continuous at $a$. Since $a$ was an arbitrary real number it follows that $f(x)$ is continuous everywhere. The proof is now complete by principle of mathematical induction and every polynomial with real coefficients is continuous everywhere.
Answer: Lemma 1: Limit of power function is the corresponding value of the function itself.
$$
\begin{align}
\lim_{x\to a}a_ix^i&=a_i\lim_{x\to a}x^i\\
&=a_i\prod_{j=1}^{i}\lim_{x\to a}x\tag{product rule of limit}\\
&=a_ia^i
\end{align}
$$

Every polynomial function is continuous
Let the polynomial be $P(x)=a_0+a_1x+a_2x^2+a_3x^3+...+a_nx^n=\sum_{i=0}^n a_ix^i$
$$
\begin{align}
\lim_{x\to a}P(x)&=\lim_{x\to a}\sum_{i=0}^{n}a_ix^i\\
&=\sum_{i=0}^{n}\lim_{x\to a}a_ix^i\tag{summation rule of limit}\\
&=\sum_{i=0}^{n}a_ia^i\tag{lemma 1}\\
&=P(a)\\
&Q.E.D
\end{align}
$$
In addition, Every rational function is also continuous
Let the rational function be $R(x)=\frac{P_1(x)}{P_2(x)}$, given that $P_2(x)\neq 0$
$$
\begin{align}
\lim_{x\to a}R(x)&=\lim_{x\to a}\frac{P_1(x)}{P_2(x)}\\
&=\frac{\lim_{x\to a}P_1(x)}{\lim_{x\to a}P_2(x)}\tag{reciprocal rule of limit}\\
&=\frac{P_1(a)}{P_2(a)}\tag{see proof of polynomial}\\
&=R(a)\\
&Q.E.D
\end{align}
$$


Ansible: how to remove AWS IAM group with an inline policy defined? (Ansible claims "changed" without performing the action)

Question: When AWS IAM group has an inline policy defined, the following Ansible task does not remove the group, although task status claims "changed":
- name: Ensure group {{ group_name }} exists
  iam:
    iam_type: group
    name: "{{ group_name }}"
    state: absent

The iam module doc page contains a note:

Currently boto does not support the removal of Managed Policies, the module will not work removing/adding managed policies.

but this is an inline policy, not a managed one.
As a workaround, because the return JSON contains delete_group key, I can at least cause the task to fail by adding:
  register: deletion_result
  failed_when: not deletion_result.delete_group

But why does it claim "changed" when the action was not performed (and it knows that, because delete_group is set to either true or false)?
Is it a bug in Ansible, or am I missing something?
And the big question: how to remove the group with a defined inline policy using Ansible?

MCVE

My play (create group, assign policy, delete group, delete group - again to show the problem):
---
- hosts: localhost
  connection: local
  gather_facts: no

  vars:
    group_name: test_group_01
    policy_name: test_policy_01

  tasks:
    - name: Ensure group {{ group_name }} exists
      iam:
        iam_type: group
        name: "{{ group_name }}"
        state: present

    - name: Ensure policy {{ policy_name }} exists and is assigned to group {{ group_name }}
      iam_policy:
        iam_type: group
        iam_name: "{{ group_name }}"
        policy_name: "{{ policy_name }}"
        policy_document: ./policy.j2
        state: present

    - name: Ensure group {{ group_name }} does not exist
      iam:
        iam_type: group
        name: "{{ group_name }}"
        state: absent

    - name: Ensure group {{ group_name }} does not exist
      iam:
        iam_type: group
        name: "{{ group_name }}"
        state: absent

policy.json (not relevant for results, just for completeness):
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt2017010101",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::my_bucket"
            ]
        }
    ]
}

The actual result:
PLAY [localhost] ***************************************************************

TASK [Ensure group test_group_01 exists] ***************************************
changed: [localhost]

TASK [Ensure policy test_policy_01 exists and is assigned to group test_group_01] ***
changed: [localhost]

TASK [Ensure group test_group_01 does not exist] *******************************
changed: [localhost]

TASK [Ensure group test_group_01 does not exist] *******************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=4    unreachable=0    failed=0

Expected result:
PLAY [localhost] ***************************************************************

TASK [Ensure group test_group_01 exists] ***************************************
changed: [localhost]

TASK [Ensure policy test_policy_01 exists and is assigned to group test_group_01] ***
changed: [localhost]

TASK [Ensure group test_group_01 does not exist] *******************************
changed: [localhost]

TASK [Ensure group test_group_01 does not exist] *******************************
ok: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=3    unreachable=0    failed=0

Answer: There is a bug in the iam module.
Here (and in some other places) error message is tested against string 'must detach all policies first', but as of today the actual error message is 'Cannot delete entity, must delete policies first.'.
You can replace all 'must detach all policies first' to 'must delete policies first' in iam.py and you will get expected behaviour of the module.
Comment: P.S. I'm a bit lazy on this day after New Year to file an issue and PR to ansible repo.


Using kint in views-view-unformatted

Question: What is corect way to use kint in  views-view-unformatted.html.twig
I do:
<code>{{ kint(rows) }}
</code>
but I get this error.
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20794259 bytes) in /home/inatcent/public_html/core/lib/Drupal/Core/Render/Renderer.php on line 448
And for {{ kint(row) }} I get null what is ok. But I want more staff. :)
Comment: `Fatal error: Allowed memory size of 134217728 bytes exhausted` you need to increase your php memory_limit.
Answer: Option 1: Try to increase your php memory limit above the 250 MB.
Option 2: Don't try to debug all the rows at once.
<code>{{ for row in rows }}
  {{ kint(row) }}
{{ endfor }}
</code>
P.S.
The reason <code>{{ row }}</code> was null, was because that variable does not exist in the template unless declared like in my example above.

Using kint in views-view-unformatted


Counting unique possibilities when many inputs yield same output.

Question: I'm trying to get better intuition on solving problems like the following:
Count the number of possible concatenations of $X-Y-Z$, where $X$ is an integer between 1 and 10 (inclusive), $Y$ is an integer between 1 and 50 (inclusive), and $Z$ is an integer between 1 and 100 (inclusive).
Example: $X = 9, Y=15, Z=42$. Then our concatenated number is $n=91542$.
The question is to count how many such unique concatenations are possible. Of course, the crux of the problem is to handle cases where different choices of $X,Y,Z$ yield the same concatenation. E.g., $X=7,Y=23, Z=4$ and $X=7,Y=2,Z=34$ result in the same concatenation.
What would be helpful in addition to a specific solution to this problem is the key tool/way of thinking that is needed to break down such a problem and others like it.
Thanks
Answer: This is all about the absence of leading zeros.
$N$ = 10 times the number of distinct Y - Z concatenations (since a number starting with 10 can only result from X = 10, never from X = 1 )
The only cases in which duplication can occur are those in which a 2 digit Y not ending in zero is followed by a one digit Z, all of these can be reproduced by a one digit Y followed by a 2 digit Z
There are a total of $41-5=36$ possible two digit Y's not ending in zero, any of which can be followed by 9 one digit Z's
$$N = 10( 50\times 100 - 36 \times 9 ) = 46760$$


Differential equation solutions are equal or finite

Question:
Let $y_{1}$ and $y_{1}$ be solutions of $y''+p(x)\ y'+q(x)\ y = r(x)$ on $[a,b]$, where $P,Q,R$ are continuous functions on $[a,b]$. Prove that either $y_{1} =y_{2}$ or $\{ x\in [a,b]\ :\ y_{1}(x) = y_{2}(x)\}$  is finite.

It is known that there is a unique solution, so if $y_{1},y_{2}$ are both solutions, then by the Wronskian, $\frac{y'_{1}}{y_{1}}=\frac{y'_{2}}{y_{2}}$ or $\frac{y'_{1}}{y_{1}}\not=\frac{y'_{2}}{y_{2}}$. But how do proceed after this? Help!!
Answer: $u=y_2-y_1$ solves $u''+pu'+q=0$. If the claim were false $u$ could be a non-zero function with infinitely many roots in $[a,b]$.
What do you know about infinite subsets in bounded intervals? What consequence does the limit point have for the derivative $u'$ in that point and thus the solution $u$, invoking uniqueness?
Comment: No, because any more hints or steps would mean to completely solve this (elementary) homework task. Obviously, you start with "let $y_1,y_2$ be not identical and the set of intersection points infinite, then..."
Comment: Can you please elaborate or show detailed working
Comment: But is my proof on identical  solution right
Comment: I see nothing that constitutes proof or an argument. And yes, the Wronskian determinant is zero at least once is equivalent that one solution is a multiple of the other, but that is only true for homogeneous equations, which the equation in your task is not.
Comment: Yes but every non homogeneous differential equation has a corresponding homogenous form


How to know what is the most viewed node without installing a module?

Question: How to know what is the most viewed node withotut installing a module?
Is there a core way to do that months (more than one year) after enabling the statistics module?
Comment: The statistics module provides a block *Popular content*. It also provides a Views integration. See web/core/modules/statistics/statistics.views.inc
Answer: You can refer the below code to get most viewd node by using preprocess function in your .theme file.get statistics count for all required nodes.
Save Node name and count in a array, then later check array for largest count.
function [THEME_NAME]_preprocess_node(&$variables) {
//get all node ids
$nids = \Drupal::entityQuery('node') ->condition('status', 1) ->condition('type', 'YOUR-NODE-TYPE') ->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
// now with foreach loop save each node name and count in array
foreach ($nids as $nid){
$node_name = Node::load($nid); $node_details->field_FIELD_NAME->value;
  $statistics = statistics_get($variables['node']->id());
  $variables['node_stats'] = \Drupal::translation()->formatPlural($statistics['totalcount'], '1 view', '@count views');
}

Comment: In which file do you put this code and where do you print the output? BTW please review my edit.
Comment: put this code in  your .theme file using preprocess function .  you can print output node_stats inside template file like below.

      {{ node_stats }}

This will print the node statistics count in submitted area of content.
Answer: You can use the core statistics module to get the count of views for each node or you can write simple code to get same result..
function getMostViewedNodeBetweenDates($start_timestamp, $end_timestamp) {
  // Query the database for the node with the highest view count.
  $query = \Drupal::entityQuery('node')
    ->condition('status', 1) // Published nodes.
    ->condition('type', 'article'); // Change 'article' to the desired content type.

  // Add a condition for the date range.
  $query->condition('created', [$start_timestamp, $end_timestamp], 'BETWEEN');

  // Sort the nodes by view count in descending order.
  $query->sort('statistics_counter_totalcount', 'DESC');
  $query->range(0, 1); // Retrieve only one result, the most viewed node.

  // Execute the query and get the result.
  $nids = $query->execute();

  // If we have results, load the most viewed node.
  if (!empty($nids)) {
    $most_viewed_nid = reset($nids);
    $most_viewed_node = \Drupal\node\Entity\Node::load($most_viewed_nid);
    return $most_viewed_node;
  }

  // No nodes found.
  return null;
}

You can then call this function in your custom code to get the most viewed node:
$start_timestamp = strtotime('2023-01-01');
$end_timestamp = strtotime('2023-12-31');

$mostViewedNode = getMostViewedNodeBetweenDates($start_timestamp, $end_timestamp);

if ($mostViewedNode) {
  // Do something with $mostViewedNode.
  $title = $mostViewedNode->getTitle();
  $viewCount = $mostViewedNode->get('statistics_counter_totalcount')->value;
  // ...
}
else {
  // No most viewed node found in the specified date range.
}

I hope this answers your question.


How to set up Media module with image editor?

Question: I have installed Media module (7.x-2.0-beta2), but I can't find the module or setting for editing images that is in the video Drupal 7: Media Upload with Image Editing.
I want to set up the Media module for editing images as per this video.
Image editor in the media module
Answer: Take a look at the article "Crop, rotate, and scale embedded images".
You have to install Media crop module. Some details about this module (from its project page):

Adds cropping, rotating and scaling to the media module's image embed
  function. Only available for images local to the server (not for
  remote images), and only when adding media via CKeditor.


how to know selected switch in table view in iOS

Question: I have multiple sections in table view and a switch for every row. In each section
when user clicks on save button, i want to know that which switches are in "ON" or "OFF" state. How to assign tags for switches ?
Comment: What have you tried ? Assigning a tag likely won't work or at least isn't the best solution for this problem. What are you trying to achieve ?
Comment: IMHO, you shouldn't be using tags for your switches. I'd recommend you identify which `UITableViewCell` the switch is in (e.g. the `superview` will presumably be the content view, and its superview will be the `UITableViewCell`), and then call `indexPathForCell` to identify which `NSIndexPath` this is for, and go from there.
Comment: i want to know which switch is in "On " position for a particular row in particular section.
Comment: @user3816512 That's backwards. You don't want to look at the switch to identify whether its on or off. You have a model that indicates whether its on or off, and when the user flips the switch, you update the model. The only time you look at the switch state is when you're responding to a user changing of the switch state, and then it's only to update your model. But if you want to look up the state of a row in the table view, don't look at the cell, but rather refer to your model. Cells are reused and you'll run into problems if you try to use the cell's switch to hold the correct state.
Comment: possible duplicate of [How can I get index path of cell on switch change event in section based table view](http://stackoverflow.com/questions/28319611/how-can-i-get-index-path-of-cell-on-switch-change-event-in-section-based-table-v)
Answer: If your problem is to give unique tag for each switch in different section then you can do is:
Assign each section a starting tag number like for First Section 1001, so the first cell switch will have tag like switch.tag = 1001+indexPath.row and continues.
For Second Section initial tag will be 2002, so the second cell switch will have tag like switch.tag = 2001+indexPath.row and continues.
So this will solve your tagging problem.
Answer: Implement a delegate for your cell:
@protocol SampleTableViewCellDelegate <NSObject>
- (void)sampleCellDidSelectSwitch:(UISwitch*)sender withIndexPath:(NSIndexPath*)indexPath;
@end

@interface SampleTableViewCell : UITableViewCell

@property (nonatomic, strong) NSIndexPath *cellIndexPath;
@property (nonatomic, assign) id <SampleTableViewCellDelegate> cellDelegate;

@end

In your Cell.m :
@implementation SampleTableViewCell

- (IBAction)switchValueChanged:(UISwitch *)sender {
    if (self.cellDelegate) {
        [self.cellDelegate sampleCellDidSelectSwitch:sender withIndexPath:self.cellIndexPath];
    }
}

@end

In your ViewController.m:
#import "SampleTableViewCell.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate, SampleTableViewCellDelegate>

@end

@implementation ViewController

#pragma mark UITableViewDataSource methods

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"sampleCell";
    SampleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[SampleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.cellDelegate = self;
    cell.cellIndexPath = indexPath;
    return cell;
}

#pragma mark - SampleTableViewCellDelegate methods

- (void)sampleCellDidSelectSwitch:(UISwitch*)sender withIndexPath:(NSIndexPath *)indexPath {
    if (sender.on) {

    }
}

@end


Can drush accept piped commands for aliases?

Question: Can drush take piping commands for a multisite command using an alias?
I'm trying to setup a simple refresh function from my prod to dev/staging. Any pointers or tips would be welcome. just started learning this stuff.
<code>drush $prodalias sql-dump --gzip >/tmp/$site.sql.gz

gunzip /tmp/$site.sql.gz | drush $devalias sqlc
</code>
Answer: It should be allowed to use piping in drush aliases as this feature was added recently by improving escaping options for core-exec.
So you have to upgrade your drush to the recent version (7.x).
See: Are pipes allowed in shell aliases?

If you prefer to use script, here is one which I'm usually using:
<code>#!/bin/sh
# pull-db.sh
# Script to pull the database from remote to local environment.
[ -z "$1" ] && { echo "Usage: $0 @remote (args)"; exit 1; }
SRC="$1"
shift
drush $SRC sql-dump | drush $* sql-cli
</code>
Answer: I write bash/shell scripts involving Drush all the time. If it's just the variables you're interested in, that has nothing to do with Drush and works fantastically. As for piping, I i'm not too sure what all is supported.
For bash to interpret your variables, you just need to wrap them in quotes.
Example:
<code>#!/bin/bash
source=$1
dest=$2

# Check if we have both a source and a destination.
if [ -z "$dest"]; then
  # Looks like at least one of our parameters are missing, notify and exit.
  echo "A source and destination Drush alias is required."
  exit 1
fi

drush sql-sync "$source" "$dest"
</code>
Usage:
<code>./my-sync-script.sh @alias.prod @alias.dev
</code>


Código sendo realizado apenas quando clica duas vezes?

Question: Bom, precisei fazer com que ao clicar em um botão mostrasse as div's e se ao clicar em outro botão e a alguma div estiver aparecendo(display:block;) iria adquirir um display: none; foi o que fiz no código a baixo:

function movel(){
 var divMovel = document.getElementById("divMovel");

 if(divMovel.style.display == "none" || divRoupa.style.display == "block" || divOutros.style.display == "block" || divCozinha.style.display == "block"){
  divMovel.style.display = "block";
  divRoupa.style.display = "none";
  divOutros.style.display = "none";
  divCozinha.style.display = "none";
 }

 else{
  divMovel.style.display = "none";
 }
};

function roupa(){
 var divRoupa = document.getElementById("divRoupa");

 if(divRoupa.style.display == "none" || divMovel.style.display == "block" || divOutros.style.display == "block" || divCozinha.style.display == "block" ){
  divMovel.style.display = "none";
  divOutros.style.display = "none";
  divCozinha.style.display = "none";
  divRoupa.style.display = "block";
 }
 else{
  divRoupa.style.display = "none";
 }
};

function outros(){
 var divOutros = document.getElementById("divOutros");

 if(divOutros.style.display == "none" || divRoupa.style.display == "block" || divMovel.style.display == "block" || divCozinha.style.display == "block" ){
  divRoupa.style.display = "none";
  divMovel.style.display = "none";
  divCozinha.style.display = "none";
  divOutros.style.display = "block";
 }
 else{
  divOutros.style.display = "none";
 }
};

function cozinha(){
 var divCozinha = document.getElementById("divCozinha");

 if(divCozinha.style.display == "none" || divRoupa.style.display == "block" || divMovel.style.display == "block" || divOutros.style.display == "block"){
  divRoupa.style.display = "none";
  divMovel.style.display = "none";
  divOutros.style.display = "none";
  divCozinha.style.display = "block";
 }
 else{
  divCozinha.style.display = "none";
 }
};
.itens{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: white;
}
.moveis{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: green;
 display: none;
}
.roupa{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: blue;
 display: none;

}
.outros{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: red;
 display: none;

}
.cozinha{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: black;
 display: none;

}
<!DOCTYPE html>

<button id="linkMovel" onclick="movel()">Móveis</button>

<button id="linkRoupa" onclick="roupa()">Roupas</button>

<button id="linkOutros" onclick="outros()">Outros</button>

<button id="linkCozinha" onclick="cozinha()">Itens de Cozinha</button>

    asdasdasd

    333333

    333333

    333333

Porém por algum motivo o script só é executado quando se clica duas vezes sobre o botão, quero saber a solução que fará com que seja aparecido assim quando clicar.OBS: Utilizando somente HTML, CSS e JS(Sem jQuery).Se possível mostrar também uma solução com jQuery utilizando algum efeito como o toggle. Agradecido.
Answer: O problema que está a acorrer é que apesar de os elementos começarem escondidos a propriedade display.style de cada um deles começa vazia, depois passa a none e só então mostra.
Esse é o motivo de ter de dar dois cliques para mostrar.
No entanto, todo o código é um pouco repetido. Uma melhor solução para o problema seria:

var divs = [
  document.getElementById("divMovel"),
  document.getElementById("divRoupa"),
  document.getElementById("divOutros"),
  document.getElementById("divCozinha")
]; //criar um array com todos os divs a mostrar

divs.forEach(x => x.style.display = "none"); //iniciar todos escondidos

//funcao agora para todos os botoes, que recebe a posicao do div a controlar
function ativar(posicao){
  if (divs[posicao].style.display == "none"){
    divs.forEach(x => x.style.display = "none"); //esconde todos os outros
    divs[posicao].style.display = "block"; //mostra este
  }
  else {
    divs[posicao].style.display = "none";
  }
}
.itens{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: white;
}
.moveis{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: green;
 display: none;
}
.roupa{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: blue;
 display: none;

}
.outros{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: red;
 display: none;

}
.cozinha{
 position: relative;
 margin: auto;
 width: 80%;
 height: 600px;
 background-color: black;
 display: none;

}
<!DOCTYPE html>

<button id="linkMovel" onclick="ativar(0)">Móveis</button>

<button id="linkRoupa" onclick="ativar(1)">Roupas</button>

<button id="linkOutros" onclick="ativar(2)">Outros</button>

<button id="linkCozinha" onclick="ativar(3)">Itens de Cozinha</button>

    asdasdasd

    333333

    333333

    333333

O que implicou mudar também a chamada a função no html para onclick="ativar(0)" para o primeiro li, e assim sucessivamente para os restantes.
JQuery
Para jquery não seriam necessário os atributos onclick nos li, assim como não seria necessário um array para controlar os vários elementos.
$(function(){
    $(".classes li").click(function(){
      //construir a posição clicada com base no li
      var indice = $(this).index() + 1;
      //ir buscar o elemento correspondente com base no seletor nth-child
      var elemento = $(".itens > div:nth-child(" + indice + ")");

      if (elemento.is(":visible") === true) { //ver se esta visível
        elemento.hide(); //esconder o elemento corrente se estava visível
      }
      else {
        $(".itens > div").hide(); //esconder todos
        elemento.show(); //mostrar o que interessa
      }
    });
});

Comment: Sem o else o elemento nunca ia a `display.none`, logo também depois não conseguia voltar a `display.block` pela lógica dos `ifs`
Comment: Muito bom, porém quando eu tirava os "else" das minhas funções parava de funcionar o script, seria por qual motivo ?
Comment: Por algum motivo eu copiei o seu código tanto do jQuery quanto o outro e não funcionou mas consegui resolver apenas adicionando um .style.display = "none", depois da declaração de cada variável de cada função fazendo com que eles já iniciem como none, além de poder tirar o else.
Comment: O de JQuery para funcionar tem de estar dentro de `$(function(){ });`, que é o que garante que o código apenas é interpretado depois de o html estar construído. Quanto ao de Js normal é estranho porque o snippet funciona na perfeição.


Recover data after PCA

Question: I have a linear regression problem with about 120 predictors and I tried to remove a number of predictors from it.
First I tried to remove multi-collinearities by calculating the variance inflation factor. This left me with about 20 different (hopefully not collinear anymore) predictors.
Then I used a PCA to reduce dimensionality even further. Because the predictors' variances are very different to one another I used the correlation matrix for this.
I can get the 'final' data when I multiply the eigenvectors with the largest eigenvalues with my original data, right?
In the end I want to find out which original predictors are left and how I can recover the 'new' original data. But for some reason I am not able to recover correct numbers.
Comment: Which software are you using? And the principal components are linear combinations of the original predictors, so it doesn't make much sense to ask which predictors are left. To obtain the new data, which I assume is the original data projected onto the first $k$ of the $p$ principal components, multiply the original data matrix by the matrix whose columns are the principal components.
Comment: This doesn't sound like a sensible approach to subset selection to me.
Answer: PCA does not get rid of any of the variables, although some may be very unimportant. Suppose you use the first three components from your PCA, each of these is a linear combination of the 20 variables you put into it.
If you want to be able to interpret the importance of the original variables in the regression, I don't think PCA is the way to go. I would consider one of the penalized regression methods such as LASSO or LAR
Comment: So PCA helps me to reduce dimensionality, so I can let's say save the data  more efficiently, but in this case I can't remove any of the original counters.
Comment: However, you can look at how much each original variate contributes to the scores (= new variate values) for different cases. If your original data was standardized, the PC loadings will tell you that. If not, you need to multiply the loadings element-wise with the original data (i.e. stop before the summation of the matrix multiplication you need to obtain the scores).

Recover data after PCA


Pagination with Blog/index.html in Jekyll-3.2.1

Question: I am having a problem that seems to be somewhat common with using pagination on pages other than index.html in a Jekyll project.
I found this post that seemed to be exactly what I am looking for:
Jekyll Pagination on every page
However, the solution does not work for me. According to the documentation on Jekyll's website, the following code in _config.yml should change the paginator to use /Blog/index.html rather than /index.html:
gems: [jekyll-paginate]
paginate: 2
paginate_path: "/blog/page:num/"

I have rebuilt and restarted my local server, but the paginator still only works on the /index.html and not /Blog/index.html.
Does anyone have an idea what I could be missing here?
Answer: The paginator internal logic is to :

(from code comment) "Determine if a page is a possible candidate to be a template page. Page's name must be index.html and exist in any of the directories between the site source and paginate_path."
choose the one closest to paginate_path in length.

In your case Blog/index.html is not recognized as existing in /blog/ path, because Blog != blog.
Or you rename your containing folder to blog, or you set paginate_path: "/Blog/page:num/"
Comment: Wow.. Thank you so much @David Jaquel. I spent about 4 hours on this issue, and can't believe it was that simple!


Can I run a Time Series Database (TSDB) over Apache Spark?

Question: I'm starting to learn about big data and Apache Spark and I have a doubt.
In the future I'll need to collect data from IoT and this data will come to me as time series data. I was reading about Time Series Databases (TSDB) and I have found some open-source options like Atlas, KairosDB, OpenTSDB, etc.
I actually need Apache Spark, so I want to know: can I use a Time Series Database over Apache Spark? Does it makes any sense? Please, remember that I'm very new to the concepts of big data, Apache Spark and all matters that I've talked in this question.
If I can run TSDB over Spark, how can I achieve that?
Comment: I need to store all time series in a good database and later I'll need Spark to use it's Machine Learning algorithms over this data.
Comment: @SergeiRodionov I think the real problem that if you load data through REST API or SQL queries, it will be loaded at the driver process. Data will not be loaded distributively.
Comment: You should be able to, take a look at https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.sources.package and an implementation such as https://github.com/databricks/spark-csv/blob/master/src/main/scala/com/databricks/spark/csv/CsvRelation.scala - I haven't found any OpenTSDB Java API, so you might need to go digging.
Comment: That's an interesting topic, but what do you mean by `TSDB over Spark`? Which part of the sensor data processing do you need to perform in the database and which part in Spark?
Comment: @FernandoPaladini Should be no problem, can Spark act as a client, e.g. by executing REST queries or SQL queries via JDBC?
Answer: I'm an OpenTSDB committer, I know this is an old question, but I wanted to answer. My suggestion would be to write your incoming data to OpenTSDB, assuming you just want to store the raw data and process it later. Then with Spark, execute OpenTSDB queries using the OpenTSDB classes.
You can write data with the classes also, I think you want to use the IncomingDataPoint construct, I actually don't have the details at hand at the moment. Feel free to contact me on the OpenTSDB mailing list for more questions.
You can see how OpenTSDB handles the incoming "put" request here, you should be able to do the same thing in your code for writes:
https://github.com/OpenTSDB/opentsdb/blob/master/src/tsd/PutDataPointRpc.java#L42
You can see the Splicer project submitting OpenTSDB queries here, a similar method could be used in your Spark project I think:
https://github.com/turn/splicer/blob/master/src/main/java/com/turn/splicer/tsdbutils/SplicerQueryRunner.java#L87


Erro que esta ocorrendo

Question:
  @Html.ActionLink("Editar","EditarPessoa", new { cod=item.Id }) |
  @Html.ActionLink("Details", "Detalhes", new { cod=item.Id }) |
  @Html.ActionLink("Deletar","DeletarPessoa", new { cod=item.Id })

public ActionResult EditarPessoa(int id)
{
  var pessoaOBJ = pessoaNegocio.BuscarPessoa(id);
  var pessoaVM = ModelParaModel(pessoaOBJ);
  return View(pessoaVM);
}

[HttpPost]
public ActionResult EditarPessoa(ViewModelPessoa modelPessoa)
{
  pessoaNegocio.Alterar(ViewModelParaModel(modelPessoa));
  return View("ListarPessoa","Pessoa");
}

public ActionResult DeletarPessoa(int id)
{
  var pessoaOBJ = pessoaNegocio.BuscarPessoa(id);
  var pessoaVM = ModelParaModel(pessoaOBJ);
  return View(pessoaVM);
}

[HttpDelete]
public ActionResult DeletarPessoa(ViewModelPessoa modelPessoa)
{
  var pessoa = ViewModelParaModel(modelPessoa);
  pessoaNegocio.Deletar(pessoa.Id);
  return View();
}

quando clica no botão excluir e editar da o seguinte erro:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult EditarPessoa(Int32)' in 'ProjetoDadosPessoa.Controllers.PessoaController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  Nome do parâmetro: parameters

Erro de Servidor no Aplicativo '/'.

The number of primary key values passed must match number of primary key values defined on the entity.
  Nome do parâmetro: keyValues
  Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.

Detalhes da Exceção:

System.ArgumentException: The number of primary key values passed must match number of primary key values defined on the entity.
  Nome do parâmetro: keyValues

Erro de Origem:
Linha 34:         public T Buscar(params object[] Key)
Linha 35:         {
Linha 36:             return _db.Set<T>().Find(Key);
Linha 37:         }
Linha 38:

Arquivo de Origem:

C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa.DAL\Repositorio\GenericRepositorio.cs    Linha: 36

Rastreamento de Pilha:
[ArgumentException: The number of primary key values passed must match number of primary key values defined on the entity.
Nome do parâmetro: keyValues]
   System.Data.Entity.Internal.WrappedEntityKey..ctor(EntitySet entitySet, String entitySetName, Object[] keyValues, String keyValuesParamName) +429
   System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues) +121
   System.Data.Entity.DbSet`1.Find(Object[] keyValues) +29
   ProjetoDadosPessoa.DAL.Repositorio.GenericRepositorio`1.Buscar(Object[] Key) in C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa.DAL\Repositorio\GenericRepositorio.cs:36
   ProjetoDadosPessoa.Negocio.Negocio.PessoaNegocio.BuscarPessoa(Int32 id) in C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa.Negocio\Negocio\PessoaNegocio.cs:42
   ProjetoDadosPessoa.Controllers.PessoaController.DeletarPessoa(Int32 id) in C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa\Controllers\PessoaController.cs:47
   lambda_method(Closure , ControllerBase , Object[] ) +96
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
   System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
   System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
   System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

Informações sobre a Versão: Microsoft .NET Framework Versão:4.0.30319; Versão do ASP.NET:4.7.2558.0

da esse erro aqui

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjetoDadosPessoa.DAL.Repositorio.Interface;
using System.Linq.Expressions;
using ProjetoDadosPessoa.DAL.Contexto;
using System.Data.Entity;

namespace ProjetoDadosPessoa.DAL.Repositorio
{
    public class GenericRepositorio<T> : IGenericRepositorio<T>, IDisposable where T : class
    {
        private readonly ProjetoDadosPessoaContexto _db;

        public GenericRepositorio()
        {
            _db = new ProjetoDadosPessoaContexto();
        }

        public void Adicionar(T entidade)
        {
            _db.Set<T>().Add(entidade);
            Commit();
        }

        public void Atualizar(T entidade)
        {
            _db.Entry(entidade).State = EntityState.Modified;
            Commit();
        }

        public T Buscar(params object[] Key)
        {
            return _db.Set<T>().Find(Key);
        }

        public void Commit()
        {
            _db.SaveChanges();
        }

        public void Deletar(int i)
        {
            var obj = Buscar(i);
            _db.Set<T>().Remove(obj);
            Commit();
        }

        public void Dispose()
        {
            if(_db != null)
            {
                _db.Dispose();
            }

            GC.SuppressFinalize(this);
        }

        public List<T> Obter(Expression<Func<T, bool>> predicate)
        {
            return _db.Set<T>().Where(predicate).ToList();
        }

        public List<T> ObterTodos()
        {
            return _db.Set<T>().ToList();
        }

        public T Primeiro(Expression<Func<T, bool>> predicate)
        {
            return _db.Set<T>().Where(predicate).FirstOrDefault();
        }
    }
}

Comment: Sua view não deve estar com `id` preenchida, ou ela nem existe lá
Comment: O que é `cod`, vey? Troca `cod` pra `id`
Answer: Pelo o que posso ver no seu trecho de código, você recebe no seu método o parametro int id, mas no seu código você passa cod. Isso faz com que o parametro não seja reconhecido.
Você não mostrou o código dos Detalhes, mas irei fazer para ele da mesma forma que fiz para os outros.
Tente fazer o seguinte:

    @Html.ActionLink("Editar","EditarPessoa", new { id = item.Id }) |
    @Html.ActionLink("Details", "Detalhes", new { id = item.Id }) |
    @Html.ActionLink("Deletar","DeletarPessoa", new { id = item.Id })

Erro que esta ocorrendo


Can censored data act as the dependent variable for a logistic regression?

Question: I need to do the research about the risk factors that contribute to heart failure.  The data I have just the censored data with some risk factors of heart failure.  And I need to use logistic regression and exponential regression to find out the risk factors that contribute to heart failure. The censored data define as 0=censored, 1=died, can I use this as my dependent variable for logistic regression? If not, if someone got data that related the risk factors that contribute to heart failure which can use exponential and logistic regression to find out the risk factors of heart failure, is possible to share with me?
Comment: censored is fine - so long as you keep that in mind when building your model. for example, you probably want to include "exposed to risk" time in your model (i.e. how long you observed the 0s and 1s)
Comment: Hi, TQ for answering my question. So, I can use the censored data(0=censored, 1=died) as my response variable in logistic regression? Cuz I wondering that logistic regression only apply in dichotomous outcome(i.e.0=survive,1=died),but I just have censored data(0=censored, 1=died)as my response variable. Is it make my result to be biased?
Answer: Time-to-event analysis (the field of survival analysis) exists primarily because of the need to handle censoring.  When subjects are followed different lengths of time, the binary logistic model has no way to handle this.  For example suppose that one subject was followed only one week and was event-free as of that time.  Her time-to-event is recorded and used in survival analysis as 7+ days.  Another subject followed one year without an event would be used as 365+ days.  The 7+ days subject contributes very little to the analysis - it's almost as if she isn't there.  The 365+ days subject contributes in a significant way.  Treating these values as right-censored is the way to account for different follow-up periods, and to account for what we don't know.
Even were there no censoring (loss to follow-up), using a binary logistic model would be a mistake because it treats a failure at one day as no worse as a failure at 5 years.  This is a huge information loss that leads to loss of statistical power and precision.
Finally there is the "how useful is the output" question.  A single survival model can be used to estimate the probability of surviving at least t days for many different t.
Comment: Thanks for replying my question. I am still confuse, my data is something like this: survival time:97 180 31...event(status): 0  0  1...which 0=censored and 1=died, smoking: 0  1  1....which 0=non smoker and 1=smoker, ejection fraction: 50  30  20...,so how can I use this data to carry out logistic regression?
Comment: The point of my answer was to demonstrate why you should **not** use logistic regression here.  Use a method from survival analysis that properly handles censoring and keeps all the information in time-to-event.
Comment: @FrankHarrell, does your above answer still apply to the LONGITUDINAL binary/ordinal logistic model i.e. expanding the data to long format and modeling time using a flexible spline? Your interesting post demonstrates that this model approximates the Cox model
Answer: You just need to connect your data to your inference properly. If the inference is not the one you want to make, then you need to change the model.
it might help to think of two scenarios. the first you observed everyone for say 10 years. Then your model is really a prediction of "person lives for at least 10 years".
for the second suppose that you observed the 0s for just 1 year, but the 1s were watched for 10 years. Then you can perfectly predict the outcome in this sample by simply having a variable "person was watched for 2 years or more".
your real data will be somewhere in between, but you need to include "time exposed to risk" somehow in your model.
when including an "exposed to risk" in your model, your inferences may change, and your predictions now become dependant on this.
you may also want to include or test for interactions between the "exposed to risk" variable and your other predictors.
Comment: Using time exposed to risk is using a dependent variable as an independent variable and will result in an uninterpretable result.


python list sort

Question: I have got a list i.e.
ls= [u'Cancer',u"Men's",u'Orthopedics',u'Pediatric',u"Senior's",u"Women's"]

ls.sort() does not seem to work here due to presence of single quote in the list elements.
I need to sort this list. Any idea???
Comment: Your list is already sorted, and `ls.sort()` simply leaves it unchanged, as expected.  What exactly is your problem?
Comment: One common pitfall with list.sort" for beginners is that it does not return anything (actually, returns "None") - so, doing `sortedlist = mylist.sort()` does not work in any case. Use the builtin sorted if you need a copy of the list, like in: `sortedlist = sorted(mylist)`
Comment: Sorry mate I must be drunk... I need to remove this question. both of you are correct
Comment: Please explain what you mean by `does not seem to work`:  if it's not the order that you expect, show us what order you got!
Answer: Actually, the question is valid and the answer is not exactly correct in general case.
If the test material was not already sorted, it would not get correctly alphabetized but the 's would cause the list to be sorted to wrong order:
>>> l = ["'''b", "a", "a'ab", "aaa"]
>>> l.sort()
>>> l
["'''b", 'a', "a'ab", 'aaa']
>>> from functools import partial
>>> import string
>>> keyfunc = partial(string.replace, old="'", new="")
>>> l.sort(key=keyfunc)
>>> l
['a', 'aaa', "a'ab", "'''b"]

Comment: @user1170364: Please reconsider.  This answer says "the `'`s would cause the list to be sorted to wrong order", which simply is not true.  The truth is that `'` is sorted before all alphanumeric characters, which isn't "wrong", but might not be what you want in some given context.
Comment: If you refer to my answer as not being exactly correct, could you please clarify what exactly isn't correct?
Comment: kimvais is right..his explanation is more accurate..thanks man
Answer: >>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]
>>> ls.sort()
>>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]

Since the list was sorted in the first place, it didn't change. sort has no problem with ' - but note that it sorts before the a-z and A-Z characters:
>>> ls
[u'abc', u'abz', u"ab'"]
>>> ls.sort()
>>> ls
[u"ab'", u'abc', u'abz']
>>>

Comment: You can ignore case in sorting by `import string` and `ls.sort(key=string.lower)`
Comment: This is correct in this exact case, but not generally. @EliBendersky see my example, for example `["a'b", "aa"]` won't get correctly _alphabetically_ sorted without a `key` function.
Comment: @Kimvais: I truly don't understand what you mean, but hey, if the OP found in your answer what he needed, I don't mind! Good for him.
Comment: what I mean is that `aa'b` being _before_ `aaa` is _not in __alphabetically__ correct order_

python list sort


Beginner's text for Algebraic Number Theory

Question: What's a good book for learning Algebraic Number Theory with minimum prerequisites?
Assume that the reader has done a basic abstract algebra course.
Comment: Marcus has a good text (http://www.amazon.com/Number-Fields-Universitext-Daniel-Marcus/dp/0387902791) as well as Samuel (http://www.amazon.com/Algebraic-Theory-Numbers-Translated-Mathematics/dp/0486466663)
Comment: It would help if you revealed more about your goals. For example, do you plan to go on to do research in number theory or, is your aim to obtain a solid background for applications such as cryptography?
Comment: @jspecter I was about to recommend the very same! With a few more words your comment would make a good answer.
Comment: Research in Number theory. Actually, I'm interested in the Langlands program.
Answer: I'm a big fan of Murty and Esmonde's "Problems in algebraic number theory", which develops the basic theory through a series of problems (with the answers in the back).  Another nice source is Milne's notes on algebraic number theory, available on his website here.
Comment: Milne's notes have answers at the end as well.
Answer: I would recommend Ireland and Rosen's text Classical Introduction to Modern Number Theory. The prerequisites for the first 10 or so chapters are minimal (first semester undergraduate algebra course).
Comment: Although very good, this is an elementary number theory textbook with one chapter ( out of 20 ) dedicated to ANT.
Answer: I would recommend Stewart and Tall's Algebraic Number Theory and Fermat's Last Theorem for an introduction with minimal prerequisites. For example you don't need to know any module theory at all and all that is needed is a basic abstract algebra course (assuming it covers some ring and field theory). But again the first chapter gives a quick review of the basic material from abstract algebra that is used later on.
I have used this book when I took an introductory course in Algebraic Number Theory and the experience was really good. The book has many examples and the pace is not too fast.
Most other books I have seen rely more heavily on module theory to make the exposition more general but since probably you don't have that background yet then I guess that this book may very well suit you perfectly.
Comment: I second ndroock1.  Stewart and Tall's Algebraic Number Theory and Fermat's Last Theorem is supposed to be an introduction to the subject, but it has several logical gaps that beginners may find hard to fill in.  I would choose Alaca and Williams instead.
Comment: Add Stewart's book on Galois Theory to the 'minimal' requirements. The book is full of references to it. Both books are too sketchy to really grasp the topic from it.
Comment: Just a note that a [fourth edition](https://www.amazon.com/Algebraic-Number-Theory-Fermats-Theorem-dp-1498738397/dp/1498738397/ref=dp_ob_title_bk) appeared in 2015.
Answer: I liked Algebraic Theory of Numbers by Pierre Samuel.
Answer: Paulo Ribenboim, A Classical Introduction to Algebraic Numbers, Springer 2001 https://www.goodreads.com/book/show/1873959.Classical_Theory_of_Algebraic_Numbers
" The exposition of the classical theory of algebraic numbers is clear and thorough, and there is a large number of exercises as well as worked out numerical examples. A careful study of this book will provide a solid background to the learning of more recent topics. "
Answer: There are notes by William A. Stein, in particular if you like to use computer to experiment: https://wstein.org/books/ant/ant.pdf
Answer: I like Algebraic Number Theory, Second Edition by  Richard A. Mollin. It is simple and best book to self study.
Answer: I recommend Fermat's Last Theorem: A Genetic Introduction to Algebraic Number Theory by Harold M. Edwards.
I quote:

This introduction to algebraic number theory via the famous problem of "Fermat's Last Theorem" follows its historical development, beginning with the work of Fermat and ending with Kummer's theory of "ideal" factorization. The more elementary topics, such as Euler's proof of the impossibilty of $x^3 +y^3 = z^3$, are treated in an uncomplicated way, and new concepts and techniques are introduced only after having been motivated by specific problems. The book also covers in detail the application of Kummer's theory to quadratic integers and relates this to Gauss' theory of binary quadratic forms, an interesting and important connection that is not explored in any other book.
Answer: Paul Pollack, A Conversational Introduction to Algebraic Number Theory: Arithmetic Beyond $\bf Z$
From the American Math Society website:
Gauss famously referred to mathematics as the "queen of the sciences" and to number theory as the "queen of mathematics". This book is an introduction to algebraic number theory, meaning the study of arithmetic in finite extensions of the rational number field $\bf Q$. Originating in the work of Gauss, the foundations of modern algebraic number theory are due to Dirichlet, Dedekind, Kronecker, Kummer, and others. This book lays out basic results, including the three "fundamental theorems": unique factorization of ideals, finiteness of the class number, and Dirichlet's unit theorem. While these theorems are by now quite classical, both the text and the exercises allude frequently to more recent developments.
In addition to traversing the main highways, the book reveals some remarkable vistas by exploring scenic side roads. Several topics appear that are not present in the usual introductory texts. One example is the inclusion of an extensive discussion of the theory of elasticity, which provides a precise way of measuring the failure of unique factorization.
The book is based on the author's notes from a course delivered at the University of Georgia; pains have been taken to preserve the conversational style of the original lectures.
Readership:
Undergraduate and graduate students interested in algebraic number theory.
Comment: See also https://www.maa.org/press/maa-reviews/a-conversational-introduction-to-algebraic-number-theory for a review.
Answer: Quadratic Number Theory: An Invitation to Algebraic Methods in the Higher Arithmetic by J. L. Lehman. I read this as supplementary material to Cox's Primes of the Form $x^2+ny^2$ and Ireland & Rosen's A Classical Introduction to Modern Number Theory.
Answer: Jarvis's Algebraic Number Theory is a gentle, undergraduate introduction. It is certainly accessible with basic abstract algebra - groups up to Lagrange's theorem and some familiarity with rings and fields are enough to get started, along with linear algebra and a little elementary number theory.
Answer: The book Introductory Algebraic Number Theory by Saban Alaca & Kenneth S. Williams is a good choice to start studying algebraic number theory.
Answer: I want to recommend the Neukirch book "Algebraic Number Theorey". It is a good book.
Comment: It is a good book, but is it appropriate for beginners? The OP refers to minimum prerequisites, assuming only a basic abstract algebra course.


question about localhost:8080

Question: i am writing  projects in GWT    let see site
http://code.google.com/webtoolkit/doc/latest/tutorial/buildui.html

and when i run project it connects localhost:8080  (i have installed appache,PHP  ,mySQL,all works) and does not show me output can anybody help me how mixed this bug?
thanks very much
here is what  it says when i visit localhost:8080
Your server is now running

To replace this page, overwrite the file index.html in the document root folder of this server. The document root folder for this server is the docroot subdirectory of this server's domain directory.

To manage a server on the local host with the default administration port, go to the Administration Console.

Register GlassFish Server now

Use the Administration Console to register GlassFish Server now. Registration is optional, but as a registered user you receive benefits such as:

Patch information and bug updates
Screencasts and tutorials
News and events
Support and training offerings
Get Oracle GlassFish Server with Premier Support

For production deployments, consider Oracle GlassFish Server with Oracle Premier Support for Software. Premier Support helps lower the total cost and risk of owning your Oracle solutions, improve the return from your IT investment, and optimize the business value of your IT solutions. Benefits of Premier Support include product updates and enhancements, global reach, lifetime support, ecosystem support, and proactive, automated support.

Install and update additional software components

Use the Update Tool to install and update additional technologies and frameworks such as:

Hibernate JPA
JRuby runtime
Jython container
If you are using the web profile, you can also use Update Tool to obtain technologies that are included by default in the full platform, such as:

Enterprise Java Beans
Metro
Jersey
To improve the user experience and optimize offerings to users, Sun collects data about GlassFish Server usage that is transmitted by the Update Tool installer as part of the automatic update processes. No personally identifiable information is collected by this process.

Join the GlassFish community

Visit the GlassFish Community page for information about how to join the GlassFish community. The GlassFish community is developing an open source, production-quality, enterprise-class application server that implements the newest features of the Java™ Platform, Enterprise Edition (Java EE) platform and related enterprise technologies.

Learn more about GlassFish Server

For more information about GlassFish Server, samples, documentation, and additional resources, see as-install/docs/about.html, where as-install is the GlassFish Server installation directory

apaches error_log file
(OS 5)Access is denied.  : Failed to open the Apache2.2 Service
(OS 5)Access is denied.  : Failed to open the Apache2.2 Service
(OS 5)Access is denied.  : Failed to open the Apache2.2 Service
(OS 5)Access is denied.  : Failed to open the Apache2.2 Service
Starting the Apache2.2 service
(OS 5)Access is denied.  : Apache2.2: Failed to open the service.
Starting the Apache2.2 service
(OS 5)Access is denied.  : Apache2.2: Failed to open the service.
Starting the Apache2.2 service
(OS 5)Access is denied.  : Apache2.2: Failed to open the service.
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Wed Aug 11 23:33:48 2010] [notice] Apache/2.2.16 (Win32) configured -- resuming normal operations
[Wed Aug 11 23:33:48 2010] [notice] Server built: Jul 30 2010 16:15:37
[Wed Aug 11 23:33:49 2010] [notice] Parent: Created child process 5924
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Wed Aug 11 23:33:49 2010] [notice] Child 5924: Child process is running
[Wed Aug 11 23:33:49 2010] [notice] Child 5924: Acquired the start mutex.
[Wed Aug 11 23:33:49 2010] [notice] Child 5924: Starting 64 worker threads.
[Wed Aug 11 23:33:49 2010] [notice] Child 5924: Starting thread to listen on port 80.
[Wed Aug 11 23:33:55 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 09:18:59 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 09:32:14 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 09:33:02 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 09:33:02 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 09:33:21 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 09:33:21 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 09:34:05 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 09:36:19 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 09:36:19 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 09:36:58 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 09:36:58 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 09:38:48 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 09:38:48 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 10:00:50 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 10:00:51 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
[Thu Aug 12 10:01:14 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 10:01:14 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
(OS 5)Access is denied.  : Failed to open the Apache2.2 Service
[Thu Aug 12 10:01:35 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/phpinfo.php
[Thu Aug 12 10:01:35 2010] [error] [client 127.0.0.1] File does not exist: C:/Apache/htdocs/favicon.ico
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Thu Aug 12 10:05:11 2010] [warn] pid file C:/Apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Thu Aug 12 10:05:11 2010] [notice] Apache/2.2.16 (Win32) PHP/5.2.11 configured -- resuming normal operations
[Thu Aug 12 10:05:11 2010] [notice] Server built: Jul 30 2010 16:15:37
[Thu Aug 12 10:05:11 2010] [notice] Parent: Created child process 396
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Thu Aug 12 10:05:11 2010] [notice] Child 396: Child process is running
[Thu Aug 12 10:05:11 2010] [notice] Child 396: Acquired the start mutex.
[Thu Aug 12 10:05:11 2010] [notice] Child 396: Starting 64 worker threads.
[Thu Aug 12 10:05:11 2010] [notice] Child 396: Starting thread to listen on port 80.
[Thu Aug 12 10:08:24 2010] [error] [client 127.0.0.1] File does not exist: C:/websites/favicon.ico
[Thu Aug 12 10:57:15 2010] [error] [client 127.0.0.1] File does not exist: C:/websites/favicon.ico
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Thu Aug 12 12:04:31 2010] [warn] pid file C:/Apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Thu Aug 12 12:04:31 2010] [notice] Apache/2.2.16 (Win32) PHP/5.2.11 configured -- resuming normal operations
[Thu Aug 12 12:04:31 2010] [notice] Server built: Jul 30 2010 16:15:37
[Thu Aug 12 12:04:31 2010] [notice] Parent: Created child process 400
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Thu Aug 12 12:04:31 2010] [notice] Child 400: Child process is running
[Thu Aug 12 12:04:31 2010] [notice] Child 400: Acquired the start mutex.
[Thu Aug 12 12:04:31 2010] [notice] Child 400: Starting 64 worker threads.
[Thu Aug 12 12:04:31 2010] [notice] Child 400: Starting thread to listen on port 80.
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Thu Aug 12 18:34:11 2010] [warn] pid file C:/Apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Thu Aug 12 18:34:12 2010] [notice] Apache/2.2.16 (Win32) PHP/5.2.11 configured -- resuming normal operations
[Thu Aug 12 18:34:12 2010] [notice] Server built: Jul 30 2010 16:15:37
[Thu Aug 12 18:34:12 2010] [notice] Parent: Created child process 452
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
httpd.exe: Could not reliably determine the server's fully qualified domain name, using 192.168.1.100 for ServerName
[Thu Aug 12 18:34:12 2010] [notice] Child 452: Child process is running
[Thu Aug 12 18:34:12 2010] [notice] Child 452: Acquired the start mutex.
[Thu Aug 12 18:34:12 2010] [notice] Child 452: Starting 64 worker threads.
[Thu Aug 12 18:34:12 2010] [notice] Child 452: Starting thread to listen on port 80.

Comment: And what does it say exactly when you point browser to http://localhost:8080 ?
Comment: looks like it is using glassfish itself instead of apache
Comment: and what to do?
Comment: There's a lot of words there but very little useful information. Please describe your setup and what you think you should be seeing.
Answer: have you successfully completed step one of the tutorial?
it is talking about port 8888 and jetty and not port 8080 and glassfish.
Answer: I see "localhost" so I presume you're testing locally (I don't know GWT)
On SSH, try : netstat -tupan
to get the list of listening ports and the associated program name
And try to read the end of Apache's error_log to see what's happening.
Answer: Well your Glassfish server seems to be working just fine. Navigating to http://localhost:8080 simply displays the server's welcome page, so now you need to deploy your GWT application and navigate to it in your browser.
I've only used Tomcat for this, so I'm not sure how Glassfish works exactly. In Tomcat I can simply copy my .war file into a webapps directory and navigate to http://localhost:8080/<ProjectName>/<MainPage>.html.
This Glassfish tutorial may help you get started.

question about localhost:8080


PHP - Setting up/emulating fake date

Question: I have a bit weird question. Is it possible to set up fake date in PHP for the time in which script is working? I am using API which uses time periods, for example when you send request to get some data, you can specify time period (for example one month, but these periods are fixed) and it will return results from request_time-1month to request_time. Obviously, request data is present time, so I want to emulate this present time (for example set date from 10 May to 15 April). Is it possible? I can't see anything helpful in PHP documention and I don't even know if it would work, because I'm not sure if this API uses time from server in which it works or independent server which stores aforementioned data. But maybe someone has any idea.
Thanks from advance.
Answer: Use libfaketime (https://github.com/wolfcw/libfaketime). On ubuntu - just install faketime using apt-get or aptitude.

If you want to fake time for console app:
 LD_PRELOAD=/usr/lib/faketime/libfaketime.so.1 FAKETIME="2008-01-01 00:00:00" php yourscript.php

If you want to fake apache time, you will need to start apache with libfaketime preloaded. Just put
 export FAKETIME="2008-01-01 00:00:00"
 export LD_PRELOAD=/usr/lib/faketime/libfaketime.so.1

into /etc/apache2/envvars and restart Apache. Now your server response will always look like
$ curl -D - http://localhost
HTTP/1.1 200 OK
Date: Tue, 01 Jan 2008 00:00:00 GMT
Server: Apache/2.2.22 (Ubuntu)
Last-Modified: Tue, 01 Jan 2008 00:00:00 GMT
ETag: W/"420419-b1-4429c2a6653ac"
Accept-Ranges: bytes
Content-Length: 177
Vary: Accept-Encoding
Content-Type: text/html

2019 UPDATE :
On the latest systems, you would need a 64-bit version of libfaketime so you'd need LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1 (thanks @jtrautmann), or even libfaketimeMT.so.1 in a multithreaded environment.
Also, there are three ways to specify the faked time:

By setting the environment variable FAKETIME
By using the file given in the environment variable FAKETIME_TIMESTAMP_FILE
By using the file .faketimerc in your home directory
By using the file /etc/faketimerc for a system-wide default

Also, it is perfectly valid to use libfaketime inside a docker container.
Comment: This isn't working for me. I had to set `LD_PRELOAD` to `/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1`. When executing `curl -D - http://localhost`, I get an answer with the fake time, but when I open a page in the browser, the date hasn't changed. Do you maybe have any idea what could be the problem?
Comment: @jtrautmann, If PHP is run as mod_php in apache and apache reports fake date in Date header, then PHP date() function should also return fake date, as it inherits libraries and environment from the parent process, I just double checked that to be 100% sure. My only guess is that your PHP interpreter is not part of the webserver - eg it is running in a different process (eg as a standalone FPM/CGI server). In this case you should start this server with preloaded and configured libfaketime as well
Comment: I could successfully adapt this on Arch+lighttpd+FastCGI: Install `libfaketime` from community, then edit `/etc/lighttpd/conf.d/fastcgi.conf` (or where appropriate), and add `"FAKETIME" => "@2008…", "LD_PRELOAD" => "/usr/lib/faketime/libfaketime.so.1"` to `bin_environment`. (Maybe check `pacman -Qll libfaketime` first).
Comment: @jtrautmann - it depends how do you check the date in the browser. If you see proper Date header in the response with curl - you should see the same Date header when using browser. If you are accessing date functions with PHP - you should also get fake date. However, if you are accessing date from javascript within the browser - you will get actual date, not the fake one
Comment: @AleksandrGuidrevitch The date header in the browser is indeed the fake date. But through the `date` function from PHP I get the current date of my machine and not the fake date. That javascript wouldn't work with it makes sense, but that isn't my problem.
Comment: @AleksandrGuidrevitch You're right, thanks for the hint! It's true I'm using FPM. But I haven't discovered how to configure FPM to use `libfaketime`. I opened a question here, maybe you can help: https://stackoverflow.com/questions/59458394/fpm-setting-up-libfaketime
Answer: If the API you are connecting to is using "request_time - 1 month", then what your script thinks the time is isn't relevant, only what time the script behind the API thinks it is. (As a silly analogy: if a shop closes at 5PM, setting your watch early won't let you in at 5:30; you'd need to sneak in and change the clock on the wall so that the staff don't lock up.)
So unless you can find a way to fool the remote API into thinking you sent the request at a different time, there is nothing you can do.
If you control the API, then just edit the API to have a parameter which over-rides the definition of "now", perhaps only allowed in a special debug mode.
Comment: Seems like you are right. Unfortunately, I am unable to do anything, because I can't control the API. Well, I need to find another way. Thanks for your response.
Answer: This worked for me:
apt-get install faketime
faketime '2021-04-26 08:15:42' php cron.php

Answer: Effectively, the date and time you access through PHP is the server's system time. So if you are able to change that, you can achieve what you need. Have a look at this answer: https://stackoverflow.com/a/3923946/977431
Although personally, i would recommend just using a function which returns -30 days (for example) from the current date. When you would like to change the date back, replace the function with the real getdate().
Comment: I used shell_exec and yes, date() returns 'my' date, but results returned by API are still the same. Seems like I have nothing to say in matter of time. Thanks anyway.
Answer: What exactly are you trying to do? If you're testing something, you shouldn't rely on system configuration at all - better to do something like:
my_function(\DateTime $now = null) {

  if($now === null) {
      return new \DateTime();
  } else {
      return $now;
  }

}

In your normal code, you just call my_function(), but in your test, you call
$now = \DateTime::createFromFormat(...);
my_function($now);

Similar idea if it's for production code. Pass the date in as a parameter, instead of leaving the function to get it.
my_function(\DateTime $datetime) {
  // does stuff
}
call_my_function() {
  my_function(new \DateTime());
}
other_way_to_call_my_function() {
  $datetime = \DateTime::createFromFormat(...);
  my_function($datetime);
}

Comment: I was trying to 'cheat' API to make it thing that "today is not today", but I can see now that I'm unable to do anything.

PHP - Setting up/emulating fake date


On the greatest prime factor of $p^2+1$, $p\in\mathbb{P}$

Question:
Are there infinitely many pairs $(p,q)\in\mathbb{P}^2$ such that $p>q$ and $p\mid q^2+1$?

This is a very interesting. There are many methods for bounding the greatest prime factor of $n^2+1$, but when $n$ is a prime this gets tricky.
Full disclosure: This was originally posted on AoPS. Here are some arguments for the existance of such solutions: (credit goes to Tintarn)

A standard probabilistic heuristic would indicate that we certainly
expect infinitely many such solutions, in fact there should be roughly
$\asymp \frac{x}{(\log x)^2}$ solutions with $p,q \le x$. But proving
this is of course a completely different matter, and I don't see an
easy way to do this. This might just be an extremely hard problem,
compared with the famously unsolved problem whether $n^2+1$ is
infinitely often prime.

Any ideas, resources or implications are greately appreciated! For more information about the greatest prime factor of $n^2+1$ read these:

A lower bound for the greatest prime divisor of $n^2+1$

Greatest prime divisor of $ n^2+1$
Answer: A sufficient condition is that there are infinite many positive integers $\ k\ $ such that both $$10k+7$$ and $$10k^2+14k+5$$ are prime. This is a consequence of the generalized Bunyakovsky conjecture , which is however open. If we assume this conjecture to be true , because of $$(10k+7)^2+1=2\cdot 5\cdot (10k^2+14k+5)$$ we only have to set $$q:=10k+7$$ $$p:=10k^2+14k+5$$ to get a solution for every suitable $\ k\ $ , hence infinite many pairs doing the job. This is only one of many possible parametrizations we can establish. If any of them has infinite many solutions, infinite many pairs with the desired properties exist. So, the answer to the question should be "yes" although this is of course not a rigorous proof.
Comment: @Tintarn Yes, this is the proper name, but I always think of Bunyakovsky in this context. And yes, the conjecture is much weaker, but I have nevertheless no idea for a proof.
Comment: Well, if we allow ourselves the luxury of citing these general conjectures, then we can do with much less work: From Schinzel's Hypothesis H (I suppose this is what you mean by the "generalized Bunyakovsky conjecture") it certainly follows that $\frac{p^2+1}{2}$ is prime for infinitely many primes $p$.
Comment: So I agree, we certainly expect this to be true, but the interesting question really is: Can we prove this (which is much weaker than all these general conjectures) unconditionally?


Como restringir os clientes que recebem as mensagens com socket.io

Question: Galera, como faço para ter esse controle no socket.io. Vou ilustrar minha situação: imagine que eu tenha um lista de amigos, como faço para que as minhas mensagens cheguem apenas para meus amigos e não para todos os clientes conectados, tipo uma rede social onde só quem pode ver minhas publicações são meus amigos?
Answer: O ideal neste cenário é utilizar o conceito de rooms que o socket.io expõe. Basicamente você agrupa certos sockets, neste caso os dos seus amigos, em uma "sala", assim você pode enviar mensagens/eventos para esta room e todos nela vão receber. Uma leve complicação neste caso é que você é amigo de alguém e essa pessoa também é sua amiga, logo cada pessoa tem a sua própria room que contêm todos os seus respectivos amigos.
Um rascunho da ideia em código:
<code>var io = require('socket.io').listen(80);
var allSockets = {}; // todos os sockets conectados
io.sockets.on('connection', function (socket) {
    allSockets[socket.id] = allSockets;

    // adiciona um amigo na sua sala de amigos e também adiciona você na sala de amigos deste amigo. As salas são representadas pela ID contida no socket da sua conexão ("socket.id")
    socket.on('adicionarAmigo', function(amigoSocketId) {
        socket.join(amigoSocketId); // você ("socket") entra na sala de amigos do seu novo amigo
        allSockets[amigoSocketId].join(socket.id); // seu amigo (o socket em allSockets[amigoSocketId]) entra na sua sala de amigos
    });

    socket.on('enviarParaAmigos', function(message) {
        // aqui você envia a mensagem para todos os sockets que estão na sala "socket.id", que é sala dos seus amigos
        socket.broadcast.to(socket.id).emit('message', message);
    });
});
</code>
Comment: Obrigado pela explicação e o rascunho. Vou usa-lo e melhora-lo. Abs


Execute a custom function on 'user register' or 'login'

Question: I am new to Drupal. I want to execute my custom function every time when user registers or logins to my site. How can I do this?
Answer: You can do this using the following hooks in your module.

hook_user_login
hook_user_register (In D7 we had user_insert hook.)

Examples:
User Login Hook:
function mymodule_user_login($account){

   //your code here
}

User Register Hook:
function mymodule_user_insert(Drupal\Core\Entity\EntityInterface $entity){

   //your code here

}

Comment: How can i get form values like first name, last name, email and password in mymodule_user_insert
Comment: Thanq @esafwan . Where i need to place this code. In theme file or what ?
Comment: @Mithun You have put this in a module. What does the custom function do? You might be able to use rules module instead for some use cases.
Answer: You can also use rule module for user login/register.


Use function created in Class - VBA

Question: I learn how work class. Please help me how to do something like this.
I prepared in Excel that Class:
Class name "Complex"
Option Explicit

Public Re As Double   'Real
Public Im As Double 'Imaginary

Public Function CCAdd(ParamArray Complex1() As Variant) as Complex
Dim i As Variant
Dim ZXC As Complex
Set ZXC = New Complex

For i = 0 To UBound(Complex1) 'Numer of arguments passed to the function
    If Not IsMissing(Complex1(i)) Then 'Omit arguments which don't exist
        If TypeName(Complex1(i)) = "Complex" Then ' Check is it Complex
            ZXC.Re = Complex1(i).Re + ZXC.Re
            ZXC.Im = Complex1(i).Im + ZXC.Im
        End If
    End If
Next i
Set Add = ZXC
Set ZXC = Nothing
End Function

In the Module I placed:
sub asd()
    Dim K As Complex
    Dim Z As Complex
    Dim A As Complex

    Set K = New Complex
    Set Z = New Complex
    Set A = New Complex

    K.Re = 1
    K.Im = 2

    Z.Re = 3
    Z.Im = 4

       A = K.CCAdd(K, Z)
end sub

After execute function CCAdd I get error with passing the value to "A". How solve this ? Maybe function can't pass non standard type of data.
Answer: In the Complex class, this line:
Set Add = ZXC

needs to be:
Set CCAdd = ZXC

Then in the module, you just need:
Sub asd()
    Dim K As Complex
    Dim Z As Complex
    Dim A As Complex

    Set K = New Complex
    Set Z = New Complex

    K.Re = 1
    K.Im = 2

    Z.Re = 3
    Z.Im = 4

       Set A = K.CCAdd(K, Z)
End Sub

So you don't need to use Set A = New Complex but you do need to use Set when assigning it to the result of the CCAdd function.

Use function created in Class - VBA