How to display panes/views/blocks based on time of day and day of week?

Question: Building a D7 site, I need to be able to automatically enable/disable Panel panes and/or views (or in the worst case scenario blocks) based on the time of day - different contact info for out-of-office hours and some other stuff. I also need to display drastically different sets of panes and views on the frontpage based on the day of week.
My temporary solution is to set up a number of Panels pages (for changing panes/views) and duplicate themes (for changing blocks) and run cronjobs with Drush's variable-set to change frontpage from one Panel page to another and to change theme to the one with different blocks enabled.
As simple as the above is, it's a terrible long-term solution because all other, unrelated changes made to the site then often require being made more than once and it's really hard to keep track of.
So is there a more straightforward way to configure per-pane, per-view or per-block setting to get enabled/disabled based on time of day / day of week?
Comment: Answering my own question - it appears that Views supports Drush and I can enable/disable specific views through my cronjobs. That mostly solves my problem.
Answer: Oddly enough, it doesn't look like any of the Date modules integrate with ctools for selection rules.
I think you have two options, that are essentially the same thing.

Panel page variants support PHP code selection rules.
Panels panes support PHP code visibility rules.

So, your page(s) could have variants based on date/time, and each variant could have panes that are only visible based on date/time.
Your PHP selection rules will use time and/or date.  For example, this should set a rule to only select or be visible on Monday.
$now = time();
$day = date("D", $now);
return $day == "Mon";

The date function does default to the current time, but explicitly using a $now parameter can prevent problems when you call date multiple times when you cross midnight.
Comment: Thank you, this solved my problem with visibility of a login pane to a webshop with specific opening hours! I love Drupal and all the helpful people around it!
Answer: If you're willing to use the "Rules" module, then you should be able to also get this to work for your "worst case scenario blocks" (as in your question). Provided you can express your actual "logic" (about the actual time-frames?) in appropriate Rules logic.
More details about doing so are explained below.
Part 1: Rules block visibility
Have a look at the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules implement the "actual time-frames" logic you asked about.
Part 2: Create an appropriate Rules Component
The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

Configuration is done on a per-block basis. To control a block
  visibility using a rule component, go to the block settings page,
  scroll down to the "Rules" tab, and select the Rules component that
  you want to use.
Notice that to be able to be used by this module, a Rules component
  must be constructed in a very specific way. See the next section for
  more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.
By looking at these samples, I was able to create another Rules Component which looks like so:
{ "rules_block_visibility_hide_blocks" : {
    "LABEL" : "Hide blocks",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : {
          "data" : [ "site:current-date" ],
          "op" : "\u003E",
          "value" : 1485351000
        }
      },
      { "data_is" : {
          "data" : [ "site:current-date" ],
          "op" : "\u003C",
          "value" : 1485365400
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

You should be able to import this rule in your own environment.
What this Rules Component does is "only" return a boolean (1 or 0), based on the condition if the site's current time (in GMT) is between 2017-01-25 14:30:00 and 2017-01-25 18:30:00.
With that, we're coming close to an actual answer to your question, as detailed in Part 3 below.
Part 3:
Head over to the "Block" settings for the block you want to conditionally hide. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "Rules". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.".
And guess what, in my case I just selected my Rules Component from Part 2.
Note: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.


Cannot configure the site as SAML SP with simplesamlphp_auth

Question: I have a functioning SAML IdP, implemented with LemonLDAP::NG. I know it functions because it works with Nextcloud as an SP. I've also successfully configured a DokuWiki SP in the past.
The IdP, the Nextcloud SP and the Drupal 8 SP are all behind an Nginx reverse proxy. All of them are directly reachable from my IP, but I have restricted access from other IPs.
I have been trying on and off for a year to make SAML login work with Drupal 8, using simplesamlphp_auth, but without success. I have lost count of how many articles I have read on the net, which all suggest that configuring SAML is trivial. Sadly, not for me.
Currently, when I select the Drupal 8 SP under 'Test authentication sources' in the 'Authentication' tab, I get the following error:

Too many redirects occurred trying to open "https://www.xxxx.tld/simplesaml/module.php/core/authenticate.php?as=wmh-www-sp&%5CSimpleSAML%5CAuth%5CState.exceptionId=_568428306a7ad7ad7bf8f8f47a94940de364239c67%3Ahttps%3A%2F%2Fwww.xxx.tld%2Fsimplesaml%2Fmodule.php%2Fcore%2Fas_login.php%3FAuthId%3Dwmh-www-sp%26ReturnTo%3Dhttps%253A%252F%252Fwww.xxx.tld%252Fsimplesaml%252Fmodule.php%252Fcore%252Fauthenticate.php%253Fas%253Dwmh-www-sp". This might occur if you open a page that is redirected to open another page, which then is redirected to open the original page.

The log file contains repeated occurrences of the following error messages:

2019/04/03 22:31:48 [error] 21251#21251: *982 FastCGI sent in stderr: "PHP message: simplesamlphp DEBUG [e54b9408f4] Session: 'wmh-www-sp' not valid because we are not authenticated.
PHP message: simplesamlphp DEBUG [e54b9408f4] getIdpMetadata: METADATANOTFOUND('%' => '\'https://cloud.xxx.tld/saml/metadata\'')
PHP message: simplesamlphp DEBUG [e54b9408f4] getIdpMetadata: METADATANOTFOUND('%' => '\'https://cloud.xxx.tld/saml/metadata\'')
PHP message: simplesamlphp DEBUG [e54b9408f4] Saved state: '_f37c552249cf34b640de1dac7ad22b1481c763fc0f:https://www.xxx.tld/simplesaml/module.php/core/as_login.php?AuthId=wmh-www-sp&ReturnTo=https.xxx.tld.php.php-www-sp'
PHP message: simplesamlphp DEBUG [e54b9408f4] saving key SimpleSAMLphp.session.161a8f86a89cf6e93f36117cc21a26af to memcache" while reading response header from upstream, client: NN.NNN.NNN.NNN, server: www.xxx.tld, request: "GET /simplesaml/module.php/core/authenticate.php?as=wmh-www-sp HTTP/2.0", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "www.xxx.tld", referrer: "https://www.xxx.tld/simplesaml/module.php/core/authenticate.php"
2019/04/03 22:31:48 [error] 21251#21251: *982 FastCGI sent in stderr: "PHP message: simplesamlphp DEBUG [e54b9408f4] loading key SimpleSAMLphp.session.161a8f86a89cf6e93f36117cc21a26af from memcache" while reading upstream, client: NN.NNN.NNN.NNN, server: www.xxx.tld, request: "GET /simplesaml/module.php/core/authenticate.php?as=wmh-www-sp HTTP/2.0", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "www.xxx.tld", referrer: "https://www.xxx.tld/simplesaml/module.php/core/authenticate.php"

(www.xxx.tld is the SP, cloud.xxx.tldis the IdP, wmh-www-sp is the entityID of the SP.)
Specific things I do not understand:

we are not authenticated - I have logged into the simplesamlphp_auth interface
METADATANOTFOUND('%' => '\'https://cloud.xxx.tld/saml/metadata\'') - this is the address of the IdP's metadata and is correct as such

I created file metadata/saml20-idp-remote.php from the IdP's metadata URL, https://cloud.xxx.tld/saml/metadata using simplesamlphp_auth's metadata converter under the "Federation" tab.
Can anyone help me to make sense of all the above?
Steve
Comment: I recently set up an integration with this module - very tricky, so I feel your pain. I can't tell you why it's not working, but I can shed light on `we are not authenticated`. This refers to the SAML authentication on the Idp, not your authentication into the SimpleSAMLphp dashboard. The screenshot does indeed show you are logged into the dashboard.
Comment: @Jaypan You gave me hope for a minute there, but logging in to the IdP makes no difference.
Answer: The problem was - as so often - between the keyboard and the chair. I had some subtle mistakes in a couple of file paths in config/config.php. Apparently simplesamlphp_auth doesn't do any validation of file names, so mistakes blow up without any apparent context at runtime.


What is the Slonimsky-Schillinger Symmetric System?

Question: What is the Slonimsky-Schillinger Symmetric System? What's the theory behind it? How is it used in composition?
Comment: A mouthful for certain..
Answer: In short, it's a way of approaching scales based on regular divisions of one or more octaves.
Schillinger used the term symmetric scale to describe a set of notes increasing by the same interval.  These include:

the chromatic scale (each note on a piano)
the whole-tone scale (a whole step between neighbor notes, 6 notes per octave)
the notes of the diminished seven chord (for example, B-D-F-Ab)
the notes of the augmented triad (for example, C-E-G#)
a tritone (for example, B and F)

You can, of course, create music based around these.  Debussy famously used whole-tone quite a bit.  Whether you apply rigors of symmetry to your chords and melodies or just use these notes as the 'space' within which your composition can operate is a matter of whim.
Slonimsky extended this to more octaves (for example, you can play perfect fourths until you reach the same note as your starting note, several octaves up) and experimented with combinations of such patterns.  His book Thesaurus of Scales and Melodic Patterns gives many patterns which can be useful for practicing technique as well as for finding inspiration for composition and improvisation.
The Octatonic Scale is a nice scale which we can think of as two diminished seven chords a half-step apart.  Here's a fairly contemporary example which draws from that heavily, and, to my ears, very effectively:

Here's a quick intro of the SSSS concept as well.


Simplifying an indefinite integral representing the calculation of an average

Question: I have an equation for a term $z_i$:
$$
z_i = \ln\frac{a_iR+p_i}{T_o* tan\theta_i }
$$
This represents a value in a grid, at location $i$, with the grid representing a geographic area.  To get the average value of $z_i$ over the geographic area, I believe this is the proper representation:
$$
z_{avg} = \frac{1}{A}\int_A[\ln(\frac{a_iR+p_i}{T_o* tan\theta_i})]dA
$$
In hoping to separate out parts of this equation for substitution into other equations, I develop this:
$$
z_{avg} = \frac{1}{A}\int_A[\ln(\frac{a_i}{T_o* tan\theta_i}) + \ln(R+\frac{p_i}{a_i})]dA
$$
Is there anyway to pull the second ln() term out of the integral?  Similarly, since this grid is made up of defined area cells, how quickly can I make the transition from using the indefinite integral to a mere summation from i to N for all grid cells?  (with N being the total number of grid cells)
Comment: Should you divide the integral by the area?
Comment: @Marty Yes totally forgot that!
Comment: New to mathTex and just getting everything else right (or near-right) took a little bit.
Answer: This is more a comment.
$\ln(\frac{a_iR+p_i}{T_o* tan\theta_i})
=\ln(a_iR+p_i)-\ln(T_o* tan\theta_i)
$
so this would split the integral
into two parts.
Comment: yes, but for reasons I didn't want to go into here, I need to keep the left hand term as close to $\ln(\frac{a_i}{T_o* tan\theta_i})$ as possible.  I have another equation like  $ln R = ...$ that I am hoping to substitute in at some point...And is there any chance this is my uncle Martin Cohen?  Ahaha, should've looked at your bio - it is not, sadly?


elementary abelian subgroup of finite non-cyclic $p$-group

Question: Let $G$ be a finite non-cyclic $p$-group of order $p^n$, $n >1$, where $p$ is odd prime. I need to prove(By elementary methods)that $G$ has a subgroup isomorphic to $\Bbb{Z}_p \times \Bbb{Z}_p$?
Comment: This is not true unless you also assume that $p > 2$.
Comment: why? i think it is correct
Comment: Then you should look at some examples of $2$-groups.
Comment: @TobiasKildetoft Also I think it is correct for *any* prime $\;p\;$. Do you have some counter example in mind?
Comment: @DonAntonio All the generalized quaternion groups (these are in fact precisely the counter examples).
Comment: @TobiasKildetoft Of course, you're right. I could have sworn the question was about *abelian* groups. All the proper subgroups of $\;\mathcal Q_8\;$ are cyclic...and normal, btw. Thanks.\
Comment: @TobiasKildetoft thanks, i editet  question
Comment: Hmm, not sure about an elementary proof. Normally, I would note that by induction one can assume that the group has a cyclic subgroup of index $p$ and use the classification of these.
Comment: since $G$ is non-cyclic, it has at least two maximal subgroups. induction on what?
Comment: Induction on the size of the group (i.e. consider a minimal counter example).
Comment: I don't get it, $|G|=p^n$ so $o(g) \ |\ p^n$ and $o(g^a) = p$ for some $a$, and taking a $h \ne 1$, $\  \langle h \rangle \ \cap \ \langle g^a \rangle = \ \{1\}$ should do the trick : $o(h^b) = p$ and  $\langle g^a,h^b \rangle \simeq \mathbb{Z}_p \times \mathbb{Z}_p $ ?
Comment: Thanks, if i cant use of the classificatin, then i can prove question?
Comment: Sure, the classification says that up to isomorphism there is a unique non-abelian group of order $p^n$ with a cyclic subgroup of index $p$ (when $p$ is odd). And it is easy to check that this group has plenty of subgroup of order $p$.
Comment: @user1952009 That will not work as it does not account for those cases where the result is not true.
Comment: @TobiasKildetoft that's why I said "I don't get it". Can you explain the problem with my algorithm ? (once you have $o(g^a) = p$, there exists a $h \ne 1, \langle g^a \rangle \cap \langle h \rangle = \{1\}$ since otherwise $G$ is cyclic)
Comment: @user1952009 Well, that last claim is not true.
Comment: @user1952009 extraspecial groups satisfy all those conditions, except they are not isomorphic to $\mathbb{Z}_p\times \mathbb{Z}_p$. For example, $D_8$ is generated by 2 reflections of the square.
Answer: If $G$ is abelian, then $G$ has at least two distinct subgroups of order $p$ such as $H,K$. Thus $H \times K \cong \Bbb{Z}_p \times \Bbb{Z}_p $.
Now let $G$ is non-abelian. We use induction on $n$. If all maximal subgroups of $G$ are cyclic, then $G \cong Q_8$, a contradiction. Thus there exists a non-cyclic maximal subgroup of $G$ such as $H$. By induction hypothesis $H$ has a non-cyclic subgroup of order $p^2$. Thus $G$ has a non-cyclic subgroup of order $p^2$.
Comment: Under what assumption on an abelian group $G$ are you assuming it has at least two distinct subgroups of order $p$?
Comment: @Nex Because if $G$ is a finite abelian $p$-group such that $G$ has exactly one subgroup of order $p$, then $G$ is cyclic.


Showing irreducible submodule is isomorphic to summand

Question: Let $V$ be a $\mathbb{C}G$-module and assume
$$V \simeq V_1 \oplus \dots \oplus V_n,$$
where the $V_i$ are irreducible.
 Let $W$ be an irreducible submodule of $V$.
 I would like to show that $W$ is isomorphic to one of the $V_i$'s
 I know that any representation can be decomposed into irreducible ones, but I am not sure how to show that any irreducible submodule is of this form.
Comment: Consider the projections $V \to V_i$ and note that their restrictions to $W$ are either trivial or an isomorphism (Schur's Lemma). But since the sum of of all these projections is an isomorphism, at least one of the restricted projections cannot be trivial.
Comment: https://en.wikipedia.org/wiki/Maschke%27s_theorem contains a proof
Answer: You could view this as a corollary of the Jordan-Hölder theorem.
Since $V$ is clearly semisimple, you can find another decomposition into irreducible submodules with $W$ as a summand.  Both decompositions yield composition series whose factors are isomorphic to the irreducible submodules in the sum.
But Jordan-Hölder says that the factors can be re-ordered so that they pair up into isomorphic pairs.  So, your $W$ is isomorphic to one of the $V_i$'s.


When can the level of the test be exactly $\alpha ?$ in non randomized test. And how to use CLT to find the critical value.

Question: Let $X_{1}, \ldots, X_{n}$ be a sample from the Bernoulli distribution with parameter $p$ Consider testing $H_{0}: p=p_{0}$ versus $H_{1}: p=p_{1}$ where $p_{0}<p_{1}$ are known numbers.
(a) Using the Neyman-Pearson lemma, find the most powerful test (Non-Randomized) among tests with level at most $\alpha$.   When can the level of the test be exactly $\alpha ?$
(b) Use the CLT to find a critical value such that the level of the test is approximately (asymptotically for large $n$ ) $\alpha$.
To use Neyman Peason lemma I calculate $r$ as :
$$r= \frac{f_1}{f_0} = \frac{p_1^{\Sigma x_i}(1-p_1)^{n-\Sigma x_i}}{p_0^{\Sigma x_i}(1-p_0)^{n-\Sigma x_i}}$$
For $p_1>p_0$ we have non randomized test is $\phi(x) =$ Reject $H_0$ for $\Sigma x_i \geq k$.
For given at most level $\alpha$ :
$$\alpha \geq E_{p_0} \phi(x) = P_{p_0}\{\Sigma x_i \geq k\} = \Sigma_{r=k+1}^n (n_{C_r}) p_{0}^r (1-p_{0})^{n-r}$$
(a) I don't know how to proceed after this and what to say about When can the level of the test be exactly $\alpha ?$
(b) How to use CLT to find the critical value which satisfies the given condition.
Please help me with this problem. Thankyou.
Answer: I will get you started with couple of particular numerical examples that illustrate the main issues involved in a general answer.
Example 1. Let $n = 10, p_0 = .5, p_1 = .7, \alpha = 0.5.$ Then NP says to reject
when $T = \sum_{i=1}^{10}X_i \ge k.$
The issue is to
find $k$ so that $\alpha \le 0.05.$ Under $H_0,$
$T \sim \mathsf{Binom}(n=10, p=.5).$ Then using $k = 8$ would give $\alpha = 0.0547 > 0.05,$ so use $k = 9$ to
get $\alpha=0.0107 < 0.05.$  Computations in R,
qbinom(.95, 10,.5)
[1] 8
sum(dbinom(8:10, 10, .5))
[1] 0.0546875
sum(dbinom(9:10, 10, .5))
[1] 0.01074219

Thus, there is no nonrandomized test exactly at level $\alpha = 0.05.$
Under $H_0,$ we have $E(T) = np = 5,$ $SD(T) = \sqrt{np(1-p)} = \sqrt{2.5} = 1.581.$
So $T\stackrel{aprx}{\sim}\mathsf{\mu=5, \sigma=\sqrt{2.5}}.$ So an approximate value of $k = 7.6.$
This is not a good approximation for $n$ as small as $n=10,$ but this kind of approximation is useful for large $n.$
qnorm(.95, 5, sqrt(2.5))
[1] 7.600742

t = 0:10;  pdf = dbinom(t, 10, .5)
plot(t, pdf, type="h", lwd = 3, col="blue")
 abline(h=0, col="green2"); abline(v=0, col="green2")
 abline(v = 8.5, lwd=2, lty="dotted")
 curve(dnorm(x, 5, sqrt(2.5)), add=T, col="red")

Example 2. Now suppose $n=100,$ keeping the other parameters the same. Then we have
$T\sim\mathsf{Binom}(100, .5)$ under $H_0$ and $k = 59$ gives a test at level $\alpha = 0.044$ and the normal
approximation says to use $k = 58.22.$
qbinom(.95, 100, .5)
[1] 58
sum(dbinom(58:100, 100, .5))
[1] 0.06660531
sum(dbinom(59:100, 100, .5))
[1] 0.04431304
qnorm(.95, 50, 5)
[1] 58.22427

t = 0:100;  pdf = dbinom(t, 100, .5)
plot(t, pdf, type="h", col="blue")
 abline(h=0, col="green2"); abline(v=0, col="green2")
 abline(v = 58.5, lwd=2, lty="dotted")
 curve(dnorm(x, 50, 5), add=T, col="red")


Input Mismatch Exception?

Question: I'm still fairly new to java. I created this program for class and it's giving me an error that I have never gotten before. If someone could help that would be great. Thank you!
import java.util.Scanner;
import java.io.*;

public class grades {

    public static void main(String[] args) throws IOException {
        // Define file names
      final String INPUT_FILE  = "gradesinput.txt";
        final String OUTPUT_FILE = "gradesoutput.txt";

      // define variables
      int grade;
      String name = null, filename;
      double value = 0;
      String msg;

        // Access the input/output files
      File inputDataFile = new File(INPUT_FILE);
        Scanner inputFile  = new Scanner(inputDataFile);
        FileWriter outputDataFile = new FileWriter(OUTPUT_FILE);
        PrintWriter outputFile = new PrintWriter(outputDataFile);
      System.out.println("Reading  file " + INPUT_FILE + "\r\n" +
                           "Creating file " + OUTPUT_FILE);

      // Read all of the values from the file
      while (inputFile.hasNext()) {
       grade = inputFile.nextInt();
       name = inputFile.nextLine();
       name = name.trim();

     } // End while

      if(value >= 90)
          {
          msg = "OUTSTANDING";
          }
          else if (value >= 70)
          {
          msg = "Satisfactory";
          }

          if(value >= 90){
               msg = "OUTSTANDING";
     }else{
     if(value >= 70){
                    msg = "Satisfactory";

     }else
                    msg = "FAILING";
              }

          outputFile.println(value + " " + name + " " + msg);
          outputFile.println("processed names");
          outputFile.println("between 70 and 89 inclusive");
          outputFile.close();

       } // End outputResults
} // End class

I'm getting this error:
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at grades.main(grades.java:37)

Comment: I'm assuming you already googled the exception to find the [documentation](https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html): _Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type._ - What is your question?
Comment: `String name = null, filename;` Is that correct?
Comment: Please clearify your actual problem.
Comment: If you will be reading file, just read the file using FileInputStream. Don't use Scanner.
Answer: The error is here: grade = inputFile.nextInt();
You are trying to read an int, but the file has no int at this location.
Citing from the documentation:

Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

Input Mismatch Exception?


Variáveis globais não aparecem mais no Xdebug Client do Sublime Text 2

Question: Estou com um problema com o plugin Xdebug Client. Até umas duas semanas atrás estava perfeito porém agora na aba de Xdebug Context não está mais aparecendo as variáveis globais e todas as variáveis que antes eram exibidas nessa aba.
Estou tendo problemas tanto no Ubuntu 12.04 quanto no Fedora 17. Não se se o problema está relacionado a alguma atualização do Xdebug ou mesmo do plugin Xdebug Client já que não alterei nada no Fedora 17 e parou de exibir. Alguém já teve esse problema ou tem alguma sugestão? Anexo imagens para ilustrar.
Comment: Me desculpe @brasofilo, fiz no linux aqui e não prestei atenção a esse detalhe. Já corrigi o formato, obrigado pela atenção ae.
Answer: Verifique nas configurações do xdebug se o item xdebug.dump_once está ativado, se não estiver habilite do seguinte modo:
xdebug.dump_once => On => On

Para maiores informações consulte a documentação.


smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Question: Estava tentando enviar um email com python:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

host = 'smtp.gmail.com'
port = 587
user = '***********@gmail.com'
password = '*********'

print('Criando objeto servidor...')
server = smtplib.SMTP(host, port)

print('Login...')
server.ehlo()
server.starttls()
server.login(user, password)

message = 'Ola Mundo!'

print('Criando mensagem...')
email_msg = MIMEMultipart()
email_msg['From'] = user
email_msg['To'] = '*****************@gmail.com'
email_msg['Subject'] = 'Assunto da Mensagem'

print('Adicionando texto...')
email_msg.attach(MIMEText(message, 'plain'))

print('Enviando mensagem...')
server.sendmail(email_msg['From'], email_msg['To'], email_msg.as_string())

print('Mensagem enviada!')
server.quit()

Prompt:
Criando objeto servidor...
Login...
Criando mensagem...
Adicionando texto...
Enviando mensagem...
Traceback (most recent call last):
  File "c:\Users\Ivone\Desktop\git\web scraping\emailTest.py", line 29, in <module>
    server.sendmail(email_msg['From'], email_msg['To'], email_msg.as_string())
  File "C:\Users\Ivone\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 887, in sendmail
    (code, resp) = self.data(msg)
  File "C:\Users\Ivone\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 574, in data
    (code, msg) = self.getreply()
  File "C:\Users\Ivone\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 398, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Comment: você permitiu o acesso por terceiros no gmail? Por default, o gmail bloqueia acessos feitos por script. Para mandar o email usando python, você precisa autorizar o acesso por portas não-default antes. Veja esse link: https://support.google.com/accounts/answer/6010255?hl=en
Comment: Já está ativado
Answer: Eu achei a resposta: desativar o módulo email do antivírus (Avast, no meu caso)


Hi, my 2D game character teleport a little bit higher, and then he come down very slow, like a leaf when i press the jump button

Question: enter image description here
If i keep presing the button it keeps going up. When i remove the script for moving left pr right it works good but when i add it , i have this problem.
here is my code
`
{
Rigidbody2D rb;
<code>float dirX;
float jumpForce = 300f;
float moveSpeed = 5f;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}
void Update()
{
    dirX = CrossPlatformInputManager.GetAxis("Horizontal");
    rb.velocity = new Vector2(dirX * 10, 0);

    if (CrossPlatformInputManager.GetButtonDown("Jump"))
        DoJump();
}
    void DoJump()
    {
        if (rb.velocity.y == 0)
            rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Force);
    }

}`
</code>
Answer: rb.velocity = new Vector2(dirX * 10, rb.velocity.y);
rb.AddForce(new Vector2(rb.velocity.x, jumpForce), ForceMode2D.Force);
Comment: i made the changes, but now it wont even jump
Comment: maybe remove "if (rb.velocity.y == 0)" and use something different
Comment: Why are these two answers the exact same with the exact same comment on it
Answer: Yea only these changes have to be done
rb.velocity = new Vector2(dirX * 10, rb.velocity.y);
rb.AddForce(new Vector2(rb.velocity.x, jumpForce), ForceMode2D.Force);
Comment: i made the changes, but now it wont even jump
Comment: gimme some time to think over  it


Homework questions with scans of notes/exam papers

Question: We have a user who is asking lots of questions like Cournot competition question or Consumer theory with lump sum fee
I don't like them (the questions)!They are homework questions that nominally satisfy our policy (effort is shown) but contribute essentially nothing to the long-term value of the site. Rather than taking the time to type the solution, we just get scans of exam papers or handwritten workings. So while there may be some "effort" in answering the question, there is essentially zero effort in contributing to the site, which makes me disinclined to offer any effort in answering.
Is this the kind of content we want on the site? If not, does anyone have any views on how our site policy should be modified to kill-off such questions?
Comment: If we're taking a vote, I think we should require that work be shown using the markdown features.
Comment: @EconJohn Add slightly more detail and post this as an answer?
Comment: @denesp as you wish.
Comment: @denesp Should I  make a post for a vote on changing site policy?
Comment: @EconJohn You are the moderator, it is up to you :) Seems to me the current vote was about that though, wasn't it? And as Alecos points out questions with only pictures should already be closed according to the previous consensus.
Comment: @denesp Wow, thats exciting. Ok new meta post coming soon
Answer: As suggested by denesp previously in a flag. I suggest that we modify our homework policy to be that the question must be copied down in a markdown form.
If our site's objective is to help make information available, taking pictures of work doesn't seem to help as images are not searchable.
I think such questions should be flagged and downvoted.
Comment: Honest question- should we be a bit more forgiving (closing and clarifying the new policy) instead of downvoting right off the bat? I can go either way- my only hesitation is it might push away potentially good users, especially if its a new change in policy. (And they aren't a habitual repeat offender.) Again, whatever you guys think works for me
Comment: we can do that. I'll have to make a new generic response to the new policy like this one for regular homework questions.
Comment: Scans are not searchable. That's all there is to it, and it is enough. In an answer of mine, https://economics.stackexchange.com/a/14473/61, I resorted to using scans, but alongside a lot of searchable text.
Comment: Why "however"? I don't see where what I wrote disagrees with what you wrote.
Comment: Just have a question regarding the point that images are not searchable. I was wondering if the heading of the question and the answers to that question contain important keywords then this issue may not to be as severe as it seems?
Comment: @Amit Im not so comfortable with it. but lets see what the rest of the site thinks.
Comment: @AlecosPapadopoulos I do feel however that its not in the spirit of the site to just post an image of question test and the effort done. this is again due to the lack of searchability.
Comment: @AlecosPapadopoulos I  must have misread. Sounds good
Answer: I tend to agree with you, although I admit that I am guilty of occasionally answering such questions to get easy rep point, thus keeping the problem alive.
The problem I see with these questions is two-fold:

Often the effort displayed is not with regard to the question itself, but earlier sub-questions from the same main question.
As has been pointed out by @denesp on occasion pictures are non-searchable so they do not add much information to the site.

If we choose to alter the site's policy than perhaps we should require that:

The question and effort shown are specific to one question (more than "these are the previous questions and how I solved them and I'm confused about subquestion c") and  and we enforce that by downvotes and closing votes. We already have the question specifity requirement I think, so that may just require stronger enforcement.
The use of pictures is limited to illustrations and graphics. Any other use that could have been achieved with simple typing results in downvotes or closing.

I realize that equations may be a grey area with regard to 2. I also do not always know how to Latex certain complicated equations. Then again if your question is specific you probably wouldn't need too many equations.


Calculating average using R with 3 grouped columns

Question: I have recently started exploring R.
I have a csv which has many rows, using which my goal is to calculate average of one column by grouping 3 other columns.
For small data, the code works pretty well, but when it comes to million rows, it takes time (around 10 sec).
Here is what I have tried.
Used fread to read only 4 columns from the large csv [Takes around 5 sec]
mydata <- fread("csv_data.csv", select = c("Col1", "Col2","Col3","Time"))

Used aggregate
aggregate(mydata$Time,by=list(mydata$Col1,mydata$Col2,mydata$Col3),mean,rm.na=TRUE)

The aggregate function takes around 6 sec for calculation and result generation.
I also tried sqldf, but takes more than 30 sec.
My goal is to find the average of time for a unique combination of Col1, Col2 and Col3
So my question is; how to calculate the average time for a unique combination of other three columns efficiently?
Comment: It is likely that you can use `data.table` to help you improve the speed of computation. It would be great if you can use `dput` to share your example dataset.
Comment: Hello @A3006. There is no question in your post. Could you please update your post to include a question for which you would like an answer? There are many ways to do a particular thing in R, some of which are less efficient than others.
Answer: Here is a solution with generated data and timings showing that data.table() outperforms aggregate() on 1,000,000 rows of data.
> library(data.table)
data.table 22.214.171.124
  The fastest way to learn (by data.table authors): https://www.datacamp.com/courses/data-analysis-the-data-table-way
  Documentation: ?data.table, example(data.table) and browseVignettes("data.table")
  Release notes, videos and slides: http://r-datatable.com
> # generate data
> col1 <- rep(1:10,100000)
> col2 <- rep(c(2,4,6,8,10),200000)
> col3 <- c(rep(c("A","B"),250000),rep(c("C","D"),250000))
> rate <- x <- rexp(1000000,rate=.2)
>
> theData <- data.frame(col1,col2,col3,rate)
>
> # aggregate with stats::aggregate()
> system.time(aggData1 <- aggregate(rate ~ col1 + col2 + col3,data=theData,mean,na.rm=TRUE))
   user  system elapsed
   1.71    0.03    1.77
>
> head(aggData1)
  col1 col2 col3     rate
1    1    2    A 5.021857
2    7    4    A 5.020089
3    3    6    A 4.991095
4    9    8    A 4.963572
5    5   10    A 5.001005
6    6    2    B 5.007399
>
> #use data.table
> theTable <- as.data.table(theData)
>
> system.time(aggData2 <- theTable[,mean(rate,na.rm=TRUE),by=.(col1,col2,col3)])
   user  system elapsed
   0.03    0.02    0.05
>
> head(aggData2)
   col1 col2 col3       V1
1:    1    2    A 5.021857
2:    2    4    B 5.000865
3:    3    6    A 4.991095
4:    4    8    B 5.023281
5:    5   10    A 5.001005
6:    6    2    B 5.007399
>

Comment: Thanks Len, when I checked with aggregate, it took 14 sec as against the data table, which took 5.4 sec. Out of which 5 sec was for importing file. Now I'm checking if I can do something to reduce that time as well.
Answer: Here is a possible solution using data.table. Because you are already using fread, which is a function from data.table, it seems like data.table is a good choice. The computation speed is one of the advantages to use data.table.
library(data.table)
# Convert your data frame to data.table
setDT(mydata)
# Perform the calculation
mydata2 <- mydata[, .(Time_mean = mean(Time, na.rm = TRUE)), by = .(Col1, Col2, Col3)]

Since you did not provide any reproducible example of mydata, I have no ways to test the codes. Below I used the built-in dataset mtcars as an example.
library(data.table)

mydata <- mtcars

setDT(mydata)

head(mydata)
#     mpg cyl disp  hp drat    wt  qsec vs am gear carb
# 1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# 4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# 5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# 6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Assuming that I want to calculate the mean mpg based on the grouping variable of am, gear, and carb, which mimics your task. Below is the code.
mydata2 <- mydata[, .(mpg_mean = mean(mpg, na.rm = TRUE)), by = .(am, gear, carb)]

mydata2
#  am gear carb mpg_mean
#  1:  1    4    4 21.00000
#  2:  1    4    1 29.10000
#  3:  0    3    1 20.33333
#  4:  0    3    2 17.15000
#  5:  0    3    4 12.62000
#  6:  0    4    2 23.60000
#  7:  0    4    4 18.50000
#  8:  0    3    3 16.30000
#  9:  1    4    2 25.90000
# 10:  1    5    2 28.20000
# 11:  1    5    4 15.80000
# 12:  1    5    6 19.70000
# 13:  1    5    8 15.00000

Comment: Thanks... Worked like a charm and reduced my computation time...My new total time has come down to 6.2


Under certain conditions, the size of a subset $X$ of a group $G$ is a multiple of another subgroup $Y$ of $G$.

Question: Here is the full text (taken from MA Armstrong's book Groups and Symmetry): Given subsets $X$ and $Y$ of a group $G$, if $X$ and $Y$ are both finite, $Y$ is a subgroup of $G$, and $XY\subseteq X$, then the size of $X$ is a multiple of the size of $Y$.
My idea is to use Lagrange's Theorem applied to the sets $X$ and $Y$, but that hinges on showing that $Y$ is a subgroup of $X$. I haven't been able to do that. Am I on the right track? Hints only please.
Comment: $XY$ will consist of various left cosets of $Y$, and hence, the number of elements in $XY$ is multiple of the number of elements in $Y$. Also, because $XY$ definitely contains $X$, it follows from the condition $XY\subseteq X$ that $XY = X$. Hence, the size of $X$ is a multiple of the size of $Y$.
Comment: @vnd I posted an "answer" using your advice, but I am not convinced.
Answer: Clearly, $X\subseteq XY$ and we can state immediately that $X=XY$. Now either $X\subseteq Y$ or $Y\subset X$. In the first case we may conclude that $XY=Y$ and the orders of $X$ and $Y$ are equal. In the second case, $Y\subset X$, let $x_1\in X-Y$ and consider the set $x_1Y=\{x_1y:y\in Y\}$. Since $Y\rightarrow x_1Y:y\mapsto x_1y$ is a bijective map between finite sets, $|Y|=|x_1Y|$. Moreover, $Y\cap x_1Y=\varnothing$, for if $x\in Y\cap x_1Y$, then $x=x_1y=y'$ for some $y,y'\in Y$ and $x_1 = y'y^{-1}\in Y$, contradicting our assumption. So either $X= x_1Y \cup Y$ and $|X|= 2|Y|$ or there is some other element $x_2 \in X-(x_1Y\cup Y)$ such that $x_2Y\cap(x_1Y\cup Y) = \varnothing$ and $|x_2Y|=|Y|$ and $X=3|Y|$. We can only repeat this process so many times since $X$ is finite. So eventually we get $|X|=k|Y|$ for some positive integer $k$.
Comment: $X\subseteq XY$ and $XY \subseteq X$ together imply $X=XY$.
Comment: I understand, but why do I need that condition?
Comment: So that you can conclude $X=XY$.
Comment: But did I need that to show that the order of $X$ is a multiple of the order of $Y$?


Grouping CoreData by Date() in SwiftUI List as sections

Question: My goal:
I want to be able to group CoreData Todo items by their dueDate ranges. ("Today", "Tomorrow", "Next 7 Days", Future")
What I attempted...
I tried using @SectionedFetchRequest but the sectionIdentifier is expecting a String. If it's stored in coreData as a Date() how do I convert it for use? I received many errors and suggestions that didn't help. This also doesn't solve for the date ranges like "Next 7 Days". Additionally I don't seem to even be accessing the entity's dueDate as it points to my ViewModel form instead.
    @Environment(\.managedObjectContext) private var viewContext

    //Old way of fetching Todos without the section fetch
    //@FetchRequest(sortDescriptors: []) var todos: FetchedResults<Todo>

    @SectionedFetchRequest<String, Todo>(
        entity: Todo.entity(), sectionIdentifier: \Todo.dueDate,
        SortDescriptors: [SortDescriptor(\.Todo.dueDate, order: .forward)]
    ) var todos: SectionedFetchResults<String, Todo>

Cannot convert value of type 'KeyPath<Todo, Date?>' to expected argument type 'KeyPath<Todo, String>'

Value of type 'NSObject' has no member 'Todo'

Ask
Is there another solution that would work better in my case than @SectionedFetchRequest? if not, I'd like to be shown how to group the data appropriately.
Answer: You can make your own sectionIdentifier in your entity extension that works with @SectionedFetchRequest
The return variable just has to return something your range has in common for it to work.
extension Todo{
    ///Return the string representation of the relative date for the supported range (year, month, and day)
    ///The ranges include today, tomorrow, overdue, within 7 days, and future
    @objc
    var dueDateRelative: String{
        var result = ""
        if self.dueDate != nil{
            //Order matters here so you can avoid overlapping
            if Calendar.current.isDateInToday(self.dueDate!){
                result = "today"//You can localize here if you support it
            }else if Calendar.current.isDateInTomorrow(self.dueDate!){
                result = "tomorrow"//You can localize here if you support it
            }else if Calendar.current.dateComponents([.day], from: Date(), to: self.dueDate!).day ?? 8 <= 0{
                result = "overdue"//You can localize here if you support it
            }else if Calendar.current.dateComponents([.day], from: Date(), to: self.dueDate!).day ?? 8 <= 7{
                result = "within 7 days"//You can localize here if you support it
            }else{
                result = "future"//You can localize here if you support it
            }
        }else{
            result =  "unknown"//You can localize here if you support it
        }
        return result
    }
}

Then use it with your @SectionedFetchRequest like this
@SectionedFetchRequest(entity: Todo.entity(), sectionIdentifier: \.dueDateRelative, sortDescriptors: [NSSortDescriptor(keyPath: \Todo.dueDate, ascending: true)], predicate: nil, animation: Animation.linear)
var sections: SectionedFetchResults<String, Todo>

Look at this question too
You can use Date too but you have to pick a date to be the section header. In this scenario you can use the upperBound date of your range, just the date not the time because the time could create other sections if they don't match.
extension Todo{
    ///Return the upperboud date of the available range (year, month, and day)
    ///The ranges include today, tomorrow, overdue, within 7 days, and future
    @objc
    var upperBoundDueDate: Date{
        //The return value has to be identical for the sections to match
        //So instead of returning the available date you return a date with only year, month and day
        //We will comprare the result to today's components
        let todayComp = Calendar.current.dateComponents([.year,.month,.day], from: Date())
        var today = Calendar.current.date(from: todayComp) ?? Date()
        if self.dueDate != nil{
            //Use the methods available in calendar to identify the ranges
            //Today
            if Calendar.current.isDateInToday(self.dueDate!){
                //The result variable is already setup to today
                //result = result
            }else if Calendar.current.isDateInTomorrow(self.dueDate!){
                //Add one day to today
                today = Calendar.current.date(byAdding: .day, value: 1, to: today)!
            }else if Calendar.current.dateComponents([.day], from: today, to: self.dueDate!).day ?? 8 <= 0{
                //Reduce one day to today to return yesterday
                today = Calendar.current.date(byAdding: .day, value: -1, to: today)!
            }else if Calendar.current.dateComponents([.day], from: today, to: self.dueDate!).day ?? 8 <= 7{
                //Return the date in 7 days
                today = Calendar.current.date(byAdding: .day, value: 7, to: today)!
            }else{
                today = Date.distantFuture
            }
        }else{
            //This is something that needs to be handled. What do you want as the default if the date is nil
            today = Date.distantPast
        }
        return today
    }
}

And then the request will look like this...
@SectionedFetchRequest(entity: Todo.entity(), sectionIdentifier: \.upperBoundDueDate, sortDescriptors: [NSSortDescriptor(keyPath: \Todo.dueDate, ascending: true)], predicate: nil, animation: Animation.linear)
var sections: SectionedFetchResults<Date, Todo>

Based on the info you have provided you can test this code by pasting the extensions I have provided into a .swift file in your project and replacing your fetch request with the one you want to use
Answer: It is throwing the error because that is what you told it to do. @SectionedFetchRequest sends a tuple of the type of the section identifier and the entity to the SectionedFetchResults, so the SectionedFetchResults tuple you designate has to match. In your case, you wrote:
SectionedFetchResults<String, Todo>

but what you want to do is pass a date, so it should be:
SectionedFetchResults<Date, Todo>

lorem ipsum beat me to the second, and more important part of using a computed variable in the extension to supply the section identifier. Based on his answer, you should be back to:
SectionedFetchResults<String, Todo>

Please accept lorem ipsum's answer, but realize you need to handle this as well.
On to the sectioning by "Today", "Tomorrow", "Next 7 Days", etc.
My recommendation is to use a RelativeDateTimeFormatter and let Apple do most or all of the work. To create a computed variable to section with, you need to create an extension on Todo like this:
extension Todo {

    @objc
    public var sections: String {
        // I used the base Xcode core data app which has timestamp as an optional.
        // You can remove the unwrapping if your dates are not optional.
        if let timestamp = timestamp {
            // This sets up the RelativeDateTimeFormatter
            let rdf = RelativeDateTimeFormatter()
            // This gives the verbose response that you are looking for.
            rdf.unitsStyle = .spellOut
            // This gives the relative time in names like today".
            rdf.dateTimeStyle = .named

            // If you are happy with Apple's choices. uncomment the line below
            // and remove everything else.
  //        return rdf.localizedString(for: timestamp, relativeTo: Date())

            // You could also intercept Apple's labels for you own
            switch rdf.localizedString(for: timestamp, relativeTo: Date()) {
            case "now":
                return "today"
            case "in two days", "in three days", "in four days", "in five days", "in six days", "in seven days":
                return "this week"
            default:
                return rdf.localizedString(for: timestamp, relativeTo: Date())
            }
        }
        // This is only necessary with an optional date.
        return "undated"
    }
}

You MUST label the variable as @objc, or else Core Data will cause a crash. I think Core Data will be the last place that Obj C lives, but we can pretty easily interface Swift code with it like this.
Back in your view, your @SectionedFetchRequest looks like this:
@SectionedFetchRequest(
    sectionIdentifier: \.sections,
    sortDescriptors: [NSSortDescriptor(keyPath: \Todo.timestamp, ascending: true)],
    animation: .default)
private var todos: SectionedFetchResults<String, Todo>

Then your list looks like this:
 List {
      ForEach(todos) { section in
          Section(header: Text(section.id.capitalized)) {
               ForEach(section) { todo in
               ...
               }
          }
      }
  }

Comment: Lorem ipsum? I only see your answer on this post. and thank you providing an answer. I will try this tonight or tomorrow.
Comment: He had one posted that dealt with the harder part of dealing with the sections in the sectioned fetch request. I am not sure why he deleted it, but I will have to recreate my code that I was working on this afternoon. I will update this answer.
Comment: I do remember seeing that code, is there anyway for me to retrieve a deleted answer? It was helpful for the sections.
Comment: Only he can. I updated my answer with regard to custom sectioning.
Comment: My apologies. I was only looking to make sure OP had all of his questions answered.
Answer: You can use this method for achive that,
like this:
func formattedDate () -> String? {
    let RFC3339DateFormatter = DateFormatter()
    RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
    RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    let date1 = RFC3339DateFormatter.date(from: date.formatted()) ?? Date()

    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    dateFormatter.timeStyle = .none

    // ES Spanish Locale (es_ES)
    dateFormatter.locale = Locale.current//Locale(identifier: "es_ES")
    return dateFormatter.string(from: date1) // Jan 2, 2001
}


HTML5 form validation? Something more 'elegant' than an alert box?

Question:
Possible Duplicate:
Recommendation for javascript form validation library

I've got a HTML5 login form. The user enters their Username and Password. Currently if the password is incorrect an alert box is thrown which informs them. However, alert boxes are ugly and make everything look horrible. I'm looking for alternatives, easy to implement ideas that others find much more elegant. Something you don't have to click to get rid of but make it very aparent to the user what happened.
Answer: My advice is to check nice jQuery plugin for form validation:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Answer: Perhaps a jQuery hide/show of an error message along side the offending text box is what you need.
Your question suggests that the validation is being done on the client side, not the server.  If that's not correct, you can make an Ajax call to the server with the credentials.  Your server can do the lookup in the directory or database, determine whether the person is a valid user, and respond accordingly.
Answer: I concur with duffymo.
If the password field is incorrect for instance, instead of an alert box you can probably try using a colored border to highlight the field(use filters and shadowbox for better effects) and make span element come along side the password field indicating that the user has entered the wrong data (You can use a text and image combo or just plain text, concise.) and fadeout the span element after sometime. I have used this concept extensively for some of the pages i have created in my company.


Find CDF of $Z:=\min\{X,Y\}$

Question: Let be $X,Y$ independent random variables with $X\sim\mathcal{U}(\{0,1\})$ and $Y\sim\mathcal{U}(\{0,1,2\})$. Compute the CDF of $Z:=\min\{X,Y\}$.
My idea:
$$
\begin{align*}
P(\min\{X,Y\}\leq x) &= 1-P(\min\{X,Y\}>x)\\
&= 1-P(\{X>x\}\cap\{Y>x\})\\
&=1-P(X>x)\cdot P(Y>x)\\
&= 1-(1-P(X\leq x))(1-P(Y\leq x))\\
&=1-(1-F_X(x))(1-F_Y(x)),
\end{align*}
$$
while
$$F_X(x)=\begin{cases} 0 &,x<a\\ \frac{x-a}{b-a} &, x\in[a,b]\\ 1&, x>b \end{cases}.$$
What sould I do next?
Comment: You are almost there. However, if the definition of $X$ you gave is exact (i.e., uniform on $\{0,1\}$), then the cdf of $X$ is not what you gave (first, there is no $a,b$ in the problem; second, it must be a piecewise-constant function with two jumps.) Then, do a distinction of cases in the expression you get for the cdf of $\min(X,Y)$: $x < 0$, $x\in[0,1)$, $x\in[1,2)$, and $x\geq 2$.
Answer: Hint: If $X$ takes on two possible values and $Y$ takes on three possible values, then the pair $(X,Y)$ has six possible values, each one equally likely (since $X$ and $Y$ are independent and each one has uniform distribution). This means you can enumerate the possible values for $Z:=\min(X,Y)$ and determine their probabilities (construct a table!). You'll find that $Z$ takes value $0$ with probability $2/3$ and value $1$ with probability $1/3$, which is enough information to determine the CDF.
Answer: You gave a generic definition of the CDF of uniform continuous distributions.
You have two specific uniform discrete distributions.   These will have step functions.
The CDF of the minimum of those RV will also be a step function, although the steps will not be uniform .   We also know the support of $Z$ since: $\min\{X, Y\}\in \{0,1,2\}$
$$\begin{align}F_X (x) & = \begin{cases} 0 & x < 0 \\ \tfrac 12 & : 0\leq x < 1 \\ 1 & : 1\leq x\end{cases} \\[2ex] F_Y (y) & = \begin{cases} 0 & y < 0 \\ \tfrac 13 & : 0\leq y < 1 \\ \tfrac 2 3 & : 1\leq y < 2 \\ 1 & : 2\leq y\end{cases} \\[3ex] F_Z(z) & = 1-(1-F_X(z))(1-F_Y(z)) \\[1ex] & = \begin{cases} 0 & z < 0 \\ ? & : 0\leq z < 1 \\ ? & : 1\leq z < 2 \\ 1 & : 2\leq z\end{cases} \end{align}$$
Can you complete?

Find CDF of $Z:=\min\{X,Y\}$


How to optimize performance of cluster model without any ground truth?

Question: I had a general question on what to do when no ground truth data is available and clustering is initiated.
Are there still metrics which can indicate how good or bad the clustering worked on the "baseline" data set? I am not sure how to tune the initial model without appropriate measures for (internal) model performance on the baseline data.
What is a best practice?
Comment: We have many questions in the [tag:clustering] tag that may be helpful, e.g., [How to decide on the correct number of clusters?](https://stats.stackexchange.com/q/23472/1352) I don't see a better way than deciding on the correct number of clusters to evaluate a clustering, so I'll vote to close as a duplicate of that one. If you have something else in mind by "how good or bad the clustering worked", please consider clarifying.
Comment: https://stats.stackexchange.com/q/195456/3277
Comment: I did not understand this: `to tune the initial model without appropriate measures for (internal) model performance on the baseline data`.
Comment: https://stats.stackexchange.com/q/21807/3277
Answer: This article lists a number of internal cluster validity indices: https://www.ncbi.nlm.nih.gov/pubmed/26389570.
These internal indices are used to determine the quality of your clusters and some of these have been implemented in sklearn. Considering your tag I am going to assume that you are using Python.
Here is a link to the cluster performance metrics implemented in sklearn, there is also an example:
https://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics.
Hope this answered your question.


Why do runners wear helmets?

Question: Why do they have to wear knee pads for that matter?
I watched so many matches and I always wondered why the bye runners ever have to wear a helmet?
Comment: Please note that the correct term, as used in the Laws, is [_runner_](https://www.lords.org/mcc/laws-of-cricket/laws/law-2-substitutes-and-runners-batsman-or-fielder-leaving-the-field-batsman-retiring-or-batsman-commencing-innings/) rather than "bye-runner". Runners have no particular connection with the concept of [_byes_](https://www.lords.org/mcc/laws-of-cricket/laws/law-26-bye-and-leg-bye/).
Answer: As per the cricketing rules,

The player acting as a runner for a batsman shall be a member of the
  batting side and shall, if possible, have already batted in that
  innings. The runner shall wear external protective equipment
  equivalent to that worn by the batsman for whom he runs and shall
  carry a bat.

Helmets,pads and other things are external protective equipment which is worn by the batsman needs to be worn by the runner too.
Note: Currently bye-runners rule is not available. The rule is removed since it was used in a wrong way.
Reference:
Comment: @neena It is not completely obsolete. Runners are still part of the Laws, so they may be used in any match unless otherwise stated. To prevent runners, the provision has to be explicitly removed, as has been the case in international cricket since 2009. Therefore you may see runners in village cricket, for instance, but not in Test cricket (as of 2015).
Comment: what was the wrong way?
Comment: @neena Taking advantages from that rule. Like he is fine but still asking for bye-runner to not to waste the energy.
Comment: is it true that runners provision is completely obsolete?
Comment: yup. [reference](http://www.espncricinfo.com/ci-icc/content/story/520924.html)
Answer: The role of a runner is a replacement for the injured batsman. In the interest of fairness to the fielding side, the runner must wear all the external protective equipment worn by the batsman he is running for, and must carry a bat.
This is obsolete now. Runners have been abolished from all forms of international cricket.

Why do runners wear helmets?


Change a paragraph link field title at runtime

Question: We have a site with numerous paragraphs, one of which is a Call-to-action, comprised of a title, summary and a link field (machine name: field_link).
The CTA is used so much that to change the word 'Enquire' to 'Inquire' for when we are on a US translation (en-US in url) would require the paragraph been edited manually for every content page that has a us translation would be a monumental task.
As such I've decide to attempt to simply handle this in the paragraph preprocess hook. The original idea was simply to check if we were in a us translation, then check for the word in the field_linl title and change it if needed, as per my snippet below.
<code>/* Translation modifier:
   * The call to action paragraph is used on almost all pages and translations
   * doesn't work with paragraphs at all. So we need to detect if we are in a US
   * translation and change out the spelling of certain words.
   */
  if($paragraph_type == 'call_to_action'){

    if(is_us_translation()){
      $cta_link = $paragraph->get('field_link');
      $cta_link->list[0]->values['title'] = 'Inquire';
      $paragraph->set('field_link', $cta_link);

      // $paragraph->values['field_link']['x-default'][0]['title'] = 'Inquire';
    }
  }
</code>
The commented out line was my other attempt.
My problem though is nothing I have tried seems to manage to change the title of the field. Is there a specific way to change this?
Answer: This worked for me
<code>function MYTHEME_preprocess_field(&$variables, $hook){
  $element = $variables['element'];

  /* Translation modifier:
   * The call to action paragraph is used on almost all pages and translations
   * doesn't work with paragraphs at all. So we need to detect if we are in a US
   * translation and change out the spelling of certain words.
   */
  if(is_us_translation()){
    if (isset($element['#field_name'])) {
      if ($element['#field_name'] == 'field_link') {
        $str_to_check = strtolower(trim($variables['items'][0]['content']['#title']));

        if(strpos($str_to_check, 'enquire') !== false){
          $variables['items'][0]['content']['#title'] = 'Inquire';
        }
      }
    }
  }
}
</code>
Comment: +1 thanks! $variables['items'][0]['content']['#title'] did the trick.


Implement asynchronous calls in .NET Remoting

Question: I want to implement async call in .NET remoting. The remoting service is consumed by a windows application ( dont ask me why not WCF. This is a legacy application). Is there any standard procedures, standard patterns to implement.
Comment: Sorry, Just learnt how to use SF!
Answer: Here you go: http://msdn.microsoft.com/en-us/library/0sa925ka.aspx


How to follow SOLID principles in Startup classes?

Question: Is there a native mechanism in AspNet Core that allows splitting the work being done inside a monolithic Startup class, in a way as to improve readability/maintainability/scalability in the long run? If so, how does it work?
We have a somewhat small .Net Core MVC WebAPI project that abstracts some product catalog concerns, but the Startup class is growing fast and getting hard to read and maintain in my opinion.
Here are some statistics:

244 lines of code
32 using namespace directives
~50 lines of manual domain-level container registrations

While this may not sound like a big deal, compared to a few classes following the SOLID principles in the rest of the project this can be daunting (especially the number of different namespaces included which are a good indication of SRP violation).
I could create a few additional .AddX() extension methods to reduce a good part of the manual DI registration code (for example, something on a "per module" basis or closely resembling Registry/Module from Autofac or Structuremap) like what is described here, but even then I'll be left with a good chunk of unrelated and somewhat complex logic for registering/configuring stuff like:

Mvc (including custom filters, serialization options, OData routes, OData EDM model builder)
Swagger (again including customizations and various settings)
ApiVersioning
Cors configuration
Complex IConfiguration builder using an external configuration system
explicit IsDevelopment check for configuring default exception page

These all seem like completely isolated, independent concerns, and I feel like I'm violating SRP by putting them together into the same class.
Is there a known mechanism I could leverage to split the work being done inside Startup into separate classes, to more closely follow SRP for example? Would that be advisable?
Even if aspnet core only supports a single Startup class (I have found no confirmation on this) I think I could come up with some sort of composite implementation with child Startup classes each dealing with one of these concerns, but I didn't want to reinvent the wheel or increase the complexity too much if a similar mechanism was already widely available and built for that purpose.
The fact that the class is so big also makes it much harder to have clean "per-environment" configurations, which are natively supported by the convention system, due to potential massive code duplication it would cause.
For instance, we have this small code section inside Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // lots of code here

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    // ...and lots of code here
}

If this logic was abstracted in a completely isolated configuration class, we could have something like this instead:
public class ErrorPageConfigurationStartup
{
    private readonly IApplicationBuilder _app;

    public ErrorPageConfigurationStartup(IApplicationBuilder app)
    {
        _app = app;
    }

    public void Configure()
    {
        app.UseExceptionHandler("/Home/Error");
    }

    public void ConfigureDevelopment()
    {
        app.UseDeveloperExceptionPage();
    }
}

Or even this, leveraging method-level injection:
public class ErrorPageConfigurationStartup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseExceptionHandler("/Home/Error");
    }

    public void ConfigureDevelopment(IApplicationBuilder app)
    {
        app.UseDeveloperExceptionPage();
    }
}

I could come up with similarly small classes for most of the concerns listed above, which would result in drastically simpler logic overall due to reduced dependencies/responsibilities.
I'm looking for ways to achieve this without having to create a significant amount of custom infrastructure code to support it.
Comment: What is growing hard? Is it DI registrations? These can (and should) be abstracted away in their own extension method. same applies for everything else actually
Comment: Yes, DI registrations is one aspect that of course will tend to grow with the functionality in the API itself @Tseng. I'm not quite sure I follow you when you say everything can be refactored into extension methods similarly though. How do you refactor the MVC/Cors/OData/ApiVersioning/etc concerns I mentioned? I mean, they are already mostly extension methods themselves.
Comment: Looks like I got some downvotes. I'd really appreciate if you could share the reasons so that I can improve the question.
Answer: Our startup file has grown quite a bit, but most of it is abstracted away behind classes and helper methods:
DI > Startup has configure method > goes to a DI bootstrapper > goes to a file I named IocConfig.cs that contains the composite root.  Swapping the container took a couple hours last time I did it with this as a bonus.
For .NET Core, the config is called directly as the container is built in, see : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1
Swagger > when you install the nuget it should have given you a config file already, again w config 1 line in startup.
If this isn't the case in .net Core, I'd still create the config file by hand and move my code.
Past that it's all doing more of the same, and is language agnostic, make a method or a provider class to abstract out the logic and have it fire off a line or two in startup.
There's no standard here from what I can tell, how far you choose to go is up to you on abstracting out the code.  For example, my oauth configure methods are methods at the bottom of startup.cs (they then call more classes) weighing in about a dozen lines each, so moving them to their own classes doesn't make a lot of sense, however the caching singleton is a bit more complex, so it gets a cachingprovider.cs file.
Comment: Thanks for your answer. Not marking as the actual answer yet as I wanted to wait for a definition on this: "There's no standard here from what I can tell..."
Comment: @julealgon I think you mean clarification... ;) but I gotcha.  As with all design patterns there's competing concerns.  SRP competes with encapsulation for example.  So, all I'm saying here is use the level of abstraction that makes the most sense to your problem at hand. Provider class vs helper method vs inline startup code.   Hope that makes sense!
Comment: Thanks for the follow-up, but what I meant was that I'd wait for a definitive answer about aspnet core supporting the split via a native mechanism. Your answer seemed to imply you were not aware it existed, just that you didn't know about it (as I don't). If that's not the case, and you know for sure such mechanism really doesn't exist, I kindly ask you to update your answer (preferably with sources) so that I can mark it as accepted.
Comment: @julealgon Ah, yeah I'm not aware of one, and we're looking at migration to .net Core 2 is where we're at, however see my answer for the update on the differences I'm aware of.  I don't think there's an overarching technical mechanism for SOLID principles in .net Core, just various individual implementations of providers.


Why I am getting output 0 while running this code

Question: When I run this code, it gives 0 as output
But I am calling func(a). Why it is not
not assigning 1 to a
a = 0
def func(x):
    x = 1
func(a)
print(a)

Comment: I think you would find the answer to your question in this previous SO question https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
Comment: @pastaleg, In that case, shoot a close vote.
Answer: This is because you are making a local variable in the function, ideally what you should be doing is this.
a = 0
def func():
    global a
    a = 1
func()
print(a)

Comment: To avoid using a global: `def func(): return 1` then `a = func()`.


Exibir imagem a ser carregada PHP

Question: Olá gostaria de saber como exibir uma imagem que está para ser carregada em um INPUT FILE
Por exemplo, quando o usuário clicar para carregar a imagem e após seleciona-la como faço para exibir um Preview da imagem antes do submit do formulário?
Comment: Estude como carregar arquivos utilizando a File API. É pré-requisito ter conhecimento em Javascript para implementar este tipo de funcionalidade.
Answer: Esta abordagem resolve este problema de maneira simples, usando apenas jquery:

<input id="imgInput" type="file">

Comment: Pode explicar um pouco o código? Ele vai exibir a imagem pelo caminho do arquivo na maquina do usuário ou faz um upload paralelo?
Comment: https://developer.mozilla.org/pt-BR/docs/Web/API/FileReader e http://caniuse.com/#feat=filereader
Comment: Ele não faz upload, apenas mostra a imagem em tempo de execução, direto da máquina. Fazer o upload é outra história.

Exibir imagem a ser carregada PHP


With the epsilon-delta definition of continuity, are the rationals continuous?

Question: My current knowledge is that a function is continuous at a point $x=a$ if and only if, for any $\epsilon>0$, there exists some $\delta>0$ such that
$$
 |x-a|<\delta \implies |f(x)-f(a)|<\varepsilon.
$$
If I have a function $f: \mathbb{Q} \to \mathbb{R}$, say $f(x)=\log\left(\sqrt{x}\right)$, where the domain is all positive rationals, surely I can always find a $\delta$ for any $\varepsilon$?
However, I feel like I've heard that the rationals aren't continuous. Is that false (that is, they are actually continuous), or is there an additional restriction to the definition of continuity?
Comment: Continuity is a property of *functions*.  The rationals are a set, not a function, so speaking of the rationals being "continuous" is not meaningful.  I suspect you are misremembering what you heard, or that whoever said it was confused.  Maybe you are thinking of the fact that the set of rationals isn't *closed*, or that the *indicator function* of the rationals (aka the Dirichlet function) isn't continuous?
Comment: Hello and welcome to math.stackexchange. The answer to your question is YES. If you take a continuous function such as $f(x) = \log \sqrt{x}$ and restrict its domain, it reamins continuous. The rational numbers don't form a *continuum*, but that is a different matter and not relevant here.
Comment: Sets (including $\mathbb{Q}$ and $\mathbb{R}$) can be "[dense](https://en.wikipedia.org/wiki/Dense_set)", not "continuous" (which, as Nate said, is a concept that applies only to *functions*).
Comment: What do you mean by "the rationals aren't continuous"?
Comment: Or maybe you're thinking of the concept of a "continuous random variable", whose value is taken from a dense set, as opposed to a "discrete" one like $\mathbb{Z}$.  This is a different definition of the word "continuous" than the one in "continuous function".
Comment: Maybe you meant, is the inclusion $\Bbb Q\hookrightarrow\Bbb R$ continuous?
Comment: Nate's suspicion is correct, and I did misremember what I heard. This makes a lot more sense now.
Answer: You seem to a bit confused on terminology.  The epsilon-delta definition of "continuity" applies to functions.  The rational numbers ($\mathbb{Q}$) are a set, not a function.
There are a couple of related concepts that do apply to sets:

A dense set has the property that between any two members of the set, there exists another member of the set.  ($\forall x_1, x_2 \in S, x_1 < x_2: \exists x_3 \in S: x_1 < x_3 < x_2$)

Rationals ($\mathbb{Q}$) and reals ($\mathbb{R}$) are dense sets.
Complex numbers ($\mathbb{C}$) can also be called dense, using a more careful definition of "dense" that deals with the fact that the word "between" (and relational operators $<$, $\le$, $\ge$, and $>$) aren't defined between complex numbers.
Integers ($\mathbb{Z}$) are not dense, because, for example, there is no integer between 1 and 2.

A complete set is one for which every Cauchy sequence of members of the set converge to a limit that is also in the set.  While $\mathbb{R}$ and $\mathbb{C}$ are complete sets, $\mathbb{Q}$ is not.

If you're done anything with probability or statistics, you may have heard of the idea of a "continuous random variable", versus a "discrete random variable".  Roughly speaking, this is equivalent to a variable from a dense set versus a variable from a non-dense set.  But this sense of the word "continuous" is different from the "continuous" in "continuous function", which may be the source of your confusion.
It is however, meaningful to ask if a particular function with a domain of $\mathbb{Q}$ is continuous.  For example, $f(x) = x^2$ is a continuous function, whether you define it on $\mathbb{Q} \to \mathbb{Q}$ or $\mathbb{R} \to \mathbb{R}$.  Your example of $f(x) = \log(\sqrt{x})$ is also a continuous function for $x > 0$, whether it's defined on $\mathbb{R} \to \mathbb{R}$ or $\mathbb{Q} \to \mathbb{R}$ (but $\mathbb{Q} \to \mathbb{Q}$ doesn't work).
And then there's the Dirichlet function:
$$f(x \in \mathbb{R}) = \begin{cases} 1 && x \in \mathbb{Q}\\ 0 && x \notin \mathbb{Q} \end{cases}$$
This is nowhere continuous.  But if you were to restrict its domain to the rationals, then you just get the constant function $f(x \in \mathbb{Q}) = 1$, which is everywhere continuous.
Answer: Continuity is the property of a function and by saying that the Rationals are not continuous makes no sense.
Answer: An important point to note is that a function being continuous on the rationals does not necessarily mean it behaves how you would expect a continuous function on the reals to behave. For example, a step function which is 0 everywhere below some threshold and 1 above it is clearly discontinuous on the reals, but it can be continuous on the rationals:
$$f(x) = \begin{cases} 0 && x < \pi \\ 1 && x > \pi \end{cases}$$
For every $x \in \mathbb{Q}$ and $\epsilon > 0$, let $\delta$ be some rational number between 0 and $|x - \pi|$; such a $\delta$ exists because $|x - \pi| \ne 0$ for all rational $x$. Then $|f(x + a) - f(x)| = 0 < \epsilon$ for all $a \in (-\delta, \delta)$, and hence $f$ is continuous at $x$.
The analogous function on the reals is of course discontinuous at $x = \pi$, but continuous everywhere else. It's only continuous on the rationals because $\pi$ isn't rational. So in a sense, the rational numbers aren't a very useful domain to talk about continuity in, because they allow for "discontinuities" to hide in the irrational gaps.
This might be (casually, informally) summarised as "the rationals aren't continuous", but as explained by the other answers, this sentence is formally nonsense because continuity is a property of functions, not sets.
Comment: Interesting function. I seem to understand the math, but I'll probably need a few days to accept it's really continuous on the rationals. :)
Answer: What applies to rationals is not continuity, but rather "density".
A subset $A \subset \mathbb{R}$ is said to be dense when : $\forall a < b \in \mathbb{R}, [a, b] \cap \mathbb{R} \neq \varnothing$.
This is strictly equivalent to the following definition:
$\forall x \in \mathbb{R}, \exists (x_n) \in A^{\mathbb{N}}, x_n \longrightarrow x$.
$\mathbb{Q}$ is, indeed, dense in $\mathbb{R}$ (just as $\mathbb{R} \setminus \mathbb{Q}$ !)
This means that for any real number, you can find a sequence of rational numbers converging to it.
"Continuity" applies to functions, not subsets. And functions defined on $\mathbb{Q}$ can be continuous, as well as discontinuous.
Have a nice day


Error when importing Pandas from python canopy

Question: I have installed Python Canopy 2.7 and have made it the default. When I start python I see the version from "Enthought Canopy Python 2.7.6 | 64-bit |"
I can import pandas and numpy... but when I try to import statsmodels.api I get this error
ImportError: No module named statsmodels

I have checked the Enthought website and in theory statsmodels would be inclueded in the express distribution.
Thanks in advance for any help!
Comment: Thanks! Just realized I have to install the required packages from the package manager... thought they would come already installed... which makes me wonder how I could import pandas... as it was not installed as well...
Comment: OK, thanks!! Do you want to make it an answer so I can check as answered?
Answer: Enthought Canopy comes bundled with a package manager. Use that package manager to install the module you require.
You are able to import pandas and numpy, since the installation comes bundled with these modules along with matplotlib etc.


Move file in Drupal 6

Question: I am using drupal 6 as i am trying to save file that comes from another server through Json format
I am using
file_move('path of image','sites/default/files');

I also tried this  one Still having same error
file_move('path of image','sites/default/files', $replace = FILE_EXISTS_RENAME));

But it gives this error

Fatal error: Only variables can be passed by reference in

How to solve this? Anybody have idea ?
Thanks
Answer: Your First argument must be a variable. The file_move() documentation says:

$source: Either a string specifying the file location of the original file or an object containing a 'filepath' property. This parameter is passed by reference and will contain the resulting destination filename in case of success.
Comment: Now i got this error

he selected file could not be copied, because no file by that name exists. Please check that you supplied the correct filename.
Can you tell me how to solve this please

Move file in Drupal 6


execute jQuery code and animation before PHP Code

Question: Hi i have been adding some animations to my website like on the login page etc
however I first found that the Animation executes but not the PHP code and when i get the PHP code to execute then the Animation doesnt work... PHP code is more important however it seems even if i use the form.submit() function in jquery the PHP code never triggers. i know this as i tried alternate methods and it works without the jQuery.
i am using 1.9.0 and here is the jQuery code
jQuery('#loginform button').click(function()
        {
            if(!jQuery.browser.msie)
            {
                if(jQuery('#username').val() == '' || jQuery('#password').val() == '')
                {
                    if(jQuery('#username').val() == '') jQuery('#username').addClass('error'); else jQuery('#username').removeClass('error');
                    if(jQuery('#password').val() == '') jQuery('#password').addClass('error'); else jQuery('#password').removeClass('error');
                    jQuery('.loginwrap').addClass('animate0 wobble').bind(anievent,function()
                    {
                        jQuery(this).removeClass('animate0 wobble');
                    });
                }
                else
                {
                    jQuery('.loginwrapper').addClass('animate0 fadeOut').bind(anievent,function()
                    {
                        $.post(username, {username});
                        $.post(password, {password});
                        jQuery('#loginform').submit();
                    });
                }
                return false;
            }
        });

as you can see, originally i got the code to post from the jquery however the animation does not run no matter what i tried.
can anyone tell me why... or what way am i supposed to make it that the animation happens then the PHP???
Comment: I don't see any PHP; what is the form's action? (Also, why no support for IE?)
Answer: Do you have the above JS wrapped such that it waits to execute until after the document has finished loaded? If you don't, what may be happening is that the javascript is trying to act on elements that have not yet been rendered. So, perhaps #loginform button does not yet exist when it is attempting to bind to that element.
Wrap your JS in this:
jQuery(function(){
    // All JS that executes on load here.
});


How to get Width or ActualWith of the StackPanel.Children item

Question: How to get Width or ActualWith of the StackPanel.Children item?
foreach (var item in stackPanel1.Children)
{
 // item.Width ???
}

Thank you!
Comment: @SLaks I tried item.Width but this property is not accessible.
Answer: Use FrameworkElement class since ActualWidth and Width belongs to this base class-
foreach (FrameworkElement item in stackPanel1.Children)
{
    double width = item.ActualWidth;
}


subgroup having index $2$ of $R^*$

Question: The question is to find all the subgroups of $R^*$ (non-zero reals under multiplication) of index $2$.
The index can be found out for finite groups. How to find subgroups having certain index for an infinte group?
The index is also the no. of distinct cosets(left/right). Is it the way to proceed to the answer? Please put light into it.
Answer: $\newcommand{\R}{\mathbb{R}}$Hint
If $H$ is such a subgroup, then the quotient group $\R^{\star}/H$ is a group of order $2$, hence the squares of all of its element are the unit element $H$ of $\R^{\star}/H$.
Comment: ohh yes.. that's the exact answer. I made a mistake of not considering the basic coset property of $r^{2} H = H$ if an only if $r^{2} \in H$.
Comment: so, if any element x (non identity) belongs to $R^*$/H , then its order will be 2. so |rH| = 2 $\Rightarrow$ $r^2$H=H$\Rightarrow$ |r|=2$\Rightarrow$r= +1 or -1.. So H can be $R^*$ or $R^+$. Is it right?? please check. thanks.
Comment: Not quite. $r^{2} H = H$ iff $r^{2} \in H$. So $H$ contains all squares. Now the set $S = (\mathbb{R}^{\star})^{2}$ of squares is a subgroup of index $2$, because $\mathbb{R}^{\star} = S \cup (-1)S$. So $H = S$.
Comment: But this "set of all squares" is a specific subset, with a *much* nicer description...
Comment: Of course ;-) $\ $
Answer: You can construct homomorphisms (surjective) from $\mathbb{R}^{*}$ to $\mathbb{Z}_2$ the only group of order two and compute the kernel.
Answer: negative$\times$negative$=$...?
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/572358)
Comment: @MickG Well, it does. Answer the question I ask, and you find the unique subgroup of index two.

subgroup having index $2$ of $R^*$


Local event listener called even though object failed to be constructed

Question: In the constructor of an object, Listener, we take an argument and subscribe to one of its events. If an exception is thrown within the constructor after the event is subscribed the OnSomethingChanged() method is still called when the event is raised - even through the object was not successfully constructed and, as far as I'm aware, no instance exists.
Now I can fix this by obviously re-factoring the design slightly, however I'm more interested in why an instance method is called even though the constructor did not complete successfully? If the method uses any local variables that have not been initialised before the exception then obviously it goes BOOM!
class Program
{
    static void Main(string[] args)
    {
        Input input = new Input();

        try
        {
            new Listener(input);
        }
        catch (InvalidOperationException)
        {
            // swallow
        }

        input.ChangeSomething(); // prints "Something changed!"
    }
}

public class Listener
{
    public Listener(Input input)
    {
        input.SomethingChanged += OnSomethingChanged; // subscibe

        throw new InvalidOperationException(); // do not let constructor succeed
    }

    void OnSomethingChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Something changed!");
    }
}

public class Input
{
    public event EventHandler SomethingChanged;

    public void ChangeSomething()
    {
        SomethingChanged(this, EventArgs.Empty);
    }
}

Answer: While throwing an exception from a constructor means an instance may potentially end up in an incomplete state, doing so doesn't stop the instance itself from being created and stored in memory (as that happens before its constructor is called).
Furthermore, the event handler has already been bound by the time you throw the exception, so raising the event will cause the handler to be invoked.
To quickly illustrate the first point, if you gave Listener a field to initialize in its constructor, then tried to initialize it after throwing the exception (which obviously isn't going to work):
    string foo;

    public Listener(Input input, string f)
    {
        input.SomethingChanged += OnSomethingChanged;

        // Because this is thrown...
        throw new InvalidOperationException();

        // ... this never happens
        foo = f;
    }

And then tried to access it in its OnSomethingChanged handler:
    void OnSomethingChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Listener.foo = " + foo);
    }

Regardless of how you call new Listener(...), the output would be

Listener.foo =

simply because the listener didn't get a chance to initialize its foo field. Although it wasn't fully initialized, it's still a complete object in terms of allocation.
Comment: That is indeed extremely interesting and not what I expected. I have also found [this post](http://stackoverflow.com/questions/5697446/is-an-object-constructed-if-an-initializer-throws) to be quite informative. Thanks for your reply
Comment: You're welcome. That post touches on a different matter altogether, but a similar premise is there.


How to use NOT operator (^) in regular expression pattern of XSLT?

Question: I want to write an XSLT function which should substitute all the characters except below:
0-9A-Za-z_ * & . , #

So, I wrote a regular expression pattern in below function:
<xsl:function name="wd:allowed_characters">
        <xsl:param name="input_param" />
        <xsl:if test="$input_param !=' '" >
            <xsl:value-of select="normalize-space(replace($input_param,'^[a-zA-Z0-9_ * & . , #]',''))" />
        </xsl:if>
    </xsl:function>

Looks like, Not operator (^) is not working as other languages.
Can you suggest me about where am I doing wrong? How can I achieve my goal here?
Correct Function is below:
 <xsl:function name="wd:allowed_characters">
        <xsl:param name="input_param" />
        <xsl:if test="$input_param !=' '" >
            <xsl:value-of select="normalize-space(replace($input_param,'[^.#, \- _ * a-zA-Z0-9]',''))" />
        </xsl:if>
    </xsl:function>

Comment: Why is `-` added and `&` went missing in your "correct function"?
Answer: Put the ^ inside the square brackets replace($input_param,'[^a-zA-Z0-9_ * & . , #]',''), but you could also simply use translate($input_param, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0-9_ * & . , #', '').
Comment: Thank you @Martin. It helped me in correcting my function and it worked. I updated the correct function in my question.


Estimating initial conditions of an ODE system using least squares

Question: I am trying to estimate the parameter values of the differential equation,
${dN\over dt}=\lambda N$. I know how to estimate the parameter value of $\lambda$ but I am having trouble in estimating the initial value of $N$, $N_0$. I am using non-linear least squares to estimate the parameters using Matlab through the function lsqnolin. The code is as below and I would like to know if the way I am estimating the initial condition is correct. The actual model is more complex and the data is different but I want to clarify of a way to estimate ODE initial conditions. With the below code I am not that sure if the method is right as if I start with an initial guess of $10^{12}$ for $N_0$ the estimated output is also the same, so I am not sure if is being optimised properly.
function [estimates,error]= leastSquaresModel()

t=[0;1;2;3];

dataN=[10;9;8;7];

initial=[10,10^12];%initial guesses of the estimates and intial condition
options=optimoptions(@lsqnonlin,'MaxFunctionEvaluations',10000,'MaxIterations',10000);
[estimates,error]=lsqnonlin(@(xEstimate)errorFun(xEstimate,dataN,t),initial,[],[],options);

end

function err=errorFun(xEstimate,y_meas,thours)
    y_est=model2(xEstimate,thours);%y_est are the estimated results from the model fit
    err=y_meas-log10(y_est);%y_meass are the data
end

function output= model2(xEstimate,thours)
    intVals=xEstimate(2);  %inital value of ODE (N_0)
    options = odeset('AbsTol',1e-13,'RelTol',1e-11);

    [~,values] = ode45(@(t,y)Equations(t,y),thours,intVals,options);

    function s=Equations(~,y)

        r=xEstimate(1);
        s=zeros(1,1);
        s(1)=r*y(1);
    end

output=values';

end

Answer: The answer consists of two parts. The first the Matlab code error, and the second is an optimization trick.

The line [~,values] = ode45(@(t,y)Equations(t,y),thours,intVals,options); gives you a vector. Then you transpose it as output=values';, and you have a row. Thus, when you compute err=y_meas-log10(y_est);, you have a matrix. It is not probably what you expect since what you need is a vector of errors. How to fix it? First, you can replace output=values'; with output=values;. Second, you can control your dimensions using size, isrow, and iscolumn.
Your initial guess for the second parameter is $10^{12}$, that is way larger than the initial guess for the first one, that is $10$. It can be a good idea to redefine as initial=[10,12]; and update the model2 function as intVals=10^xEstimate(2);. I.e., it can be nice to use as the second parameter not the value itself, but the power.

With these two modifications, the optimization result is $\lambda=-2.306$ and $N_0=10^{10}$, that is very close to the real value $\lambda=\log(0.1)=-2.303$.
And one more remark. For your model, it is reasonable to assume that $\lambda<0$, i.e., $N$ does not diverge. Then it is a good idea to take the initial guess negative as well.


Autenticação com Spring Security

Question: Olá, estou fazendo um projeto utilizando o Spring Framework, e preciso fazer uma autenticação bem simples, usando usuários criados na tabela user mesmo (sem qualquer integração com redes sociais). Porém não sei como fazer, estou utilizando Spring e AngularJs, como faço para o usuário se autenticar? Tenho pouquíssima experiência com Spring.
Obrigado.
Answer: Utilizando JWT.
Manager:
public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    private UserRepository repository;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        try {
            User user = repository.findByEmail(auth.getName().toString());
            if (auth.getCredentials().toString().equals(user.getPassword())) {
                return auth;
            }
        } catch (NullPointerException e){
            throw new BadCredentialsException("Usuário não cadastrado!");
        }
        throw new BadCredentialsException("Senha incorreta");
    }
}

Configuration:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // disable caching
        http.headers().cacheControl();
        http.csrf().disable()
                // disable csrf for our requests.
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/login").permitAll()
                .antMatchers(HttpMethod.GET, "/api/questions/**").permitAll()
                .antMatchers(HttpMethod.GET, "/api/answers/**").permitAll()
                .antMatchers(HttpMethod.POST, "/api/users").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/api/users").permitAll()
                .antMatchers(HttpMethod.GET, "/api/comment/**").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the api/login requests
                .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                // And filter other requests to check the presence of JWT in header
                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.addAllowedOrigin("*"); //Cors
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.addExposedHeader("Authorization");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return new CustomAuthenticationManager();
    }
}

Serviço para autenticar o token:
public class TokenAuthenticationService {

    private long EXPIRATIONTIME = 1000 * 60 * 60 * 24 * 10; // 10 days
    private String secret = "Meu secret";
    private String tokenPrefix = "Bearer";
    private String headerString = "Authorization";
    public void addAuthentication(HttpServletResponse response, String username)
    {
        // We generate a token now.
        String JWT = Jwts.builder()
                    .setSubject(username)
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .compact();
        response.addHeader(headerString,tokenPrefix + " "+ JWT);
    }

    public String getUserName(String token){
        if(token != null)
        {
            // parse the token.
            String username = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
            if(username != null) // we managed to retrieve a user
            {
                return username;
            }
        }
        return null;
    }

    public Authentication getAuthentication(HttpServletRequest request)
    {
        String token = request.getHeader(headerString);
        if(token != null)
        {
            // parse the token.
            String username = Jwts.parser()
                        .setSigningKey(secret)
                        .parseClaimsJws(token)
                        .getBody()
                        .getSubject();
            if(username != null) // we managed to retrieve a user
            {
                return new AuthenticatedUser(username);
            }
        }
        return null;
    }
}

Autenticação com Spring Security


Forçar a atualização de um elemento em HTML/Javascript/ASP.NET

Question: No site que estou trabalhando, o usuário tem acesso a um editor de texto para mudar as labels em determinadas fotos. Ao editar o texto e dar "submit" nas respostas, os textos não atualizam nas páginas - O mesmo acontecia com as imagens do site, mas uma solução foi encontrada, colocando um número aleatório no final de todas elas, mantendo a unicidade.
As fotos a seguir demonstram o que quero dizer:

A imagem acima possui uma label (Polícia Militar, Navegantes).
Abaixo, o usuário tem a possibilidade de mudar tanto a imagem quanto o texto exibido ao lado dela:

Os valores não são atualizados. O mesmo acontecia com as imagens, mas como foi dito, um identificador aleatório foi "colado" no nome dela para o servidor (Azure) não confundir.
O que pode estar acontecendo?
(Estou usando cshtml/aspnet com mvc5!)
Já busquei diversas alternativas (tanto em inglês quanto em português) - a maioria delas informa sobre tags meta que incluem as opções "no-cache", "no-store", entre outras, mas nenhuma parece funcionar.
Comment: Bem vindo ao StackOverflow em Português. Editei sua pergunta para remover as saudações e agradecimentos pois costumamos manter o texto o mais limpo possível para focar na sua dúvida sobre programação. Caso tenha interesse em visitar uma parte do site que não é voltado para tirar dúvidas pode conhecer o [chat]. Se tiver dúvidas quanto ao funcionamento, regras e procedimentos do site visite o [meta] :)
Answer: Olá,
Talvez não seja a View e sim o método que você usa para trazer o conteúdo do banco de dados. Caso esteja usando EF para fazer a consulta no BD, tente fazê-la através de uma query em string (ex: "SELECT (campos) FROM dbo.Tabela") e executar com Database.SqlQuery(QUERY).ToList()
Isso faz com que os dados realmente sejam trazidos do banco, forçando a atualização.
Att.
Comment: Melhorei minha antiga solução com isso. Obg!!!
Answer: Na assinatura de cada Action que você não deseja cachear coloque a seguinte anotação: [OutputCache(NoStore = true, Duration = 0)] no exemplo a seguir eu tinha problema com cache e resolvi dessa maneira.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult LoginRegister()
{
}

Fonte(minha própria pergunta, é um propósito diferente, mas a solução é a mesma): Como não permitir o usuário acessar a página anterior de login/registro após fazer login ou registrar-se
Caso não resolva comenta que encontraremos outra solução.
Comment: Infelizmente estas garantias já estão! Temo que o problema possa ser no get do servidor, já que abrir a página em modo privado também não recupera as informações corretas.

Ainda assim agradeço a resposta, Leo!
Comment: De onde você recebe as informações das imagens? via banco de dados?
Comment: @Momentanius ^^^
Comment: Isso! Estou usando SQL com os servidores da Azure!
Comment: Tem certeza que as alterações estão sendo feitas no banco?
Comment: @Momentanius, é só digitar @ colado com meu nome
Comment: Sim! A cada atualização, vou no banco e faço um refresh no mesmo. Os dados são enviados para lá, mas não estão sendo exibidos corretamente na view.

Quando eu rebuildo o projeto inteiro ele dá atualiza, mas antes disso, não.
Comment: Teria como você postar o código que você utiliza para popular a view?
Comment: o código do controller e a view em sí ?