System.TypeInitializationException Error when creating a Log Object | C#

Question: I'm creating a new project and just wrote up the following Log file, but am encountering an unhandled exception of type 'System.TypeInitializationException' occured in My_Project.exe
The inner exception states that {"Index (zero based) must be greater than or equal to zero and less than the size of the argument list."}
The error occurs when I first write to the Log. For example, when I use the following code, the program crashes with the error message.
using System;
using System.Windows.Forms;
using My_Project.forms;

namespace My_Project {
    public static class Program {
        [STAThread]
        public static void Main() {
            Utility.MyLog.Write("Test");   //<-- ERROR OCCURS HERE
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Window());
        }
    }
}

Here's where the Log is being instantiated..
public static class Utility
{
    // DEFAULT LOG OUTPUT.
    public static Log MyLog = new Log();

    ...
}

Here is my Log.cs file, in it's entirety so far..
using System;
using System.IO;
using System.Reflection;
using My_Project.Properties;

// STATIC USING MEMBERS
using static My_Project.LogFormat;
using static System.IO.File;
using static My_Project.Utility;

namespace My_Project {
    public enum LogFormat { None, Message, Evaluate, Process, Result }

    public sealed class Log {
        // USED TO LOCK THE OUTPUT THREAD WHEN WRITING TO A FILE.
        private readonly object _lock = new object();

        // DEFAULT VARIABLES
        public readonly string FileName;
        public readonly string FilePath;

        // DEFAULT CONSTRUCTOR
        public Log(string fileName = null, string filePath = null) {
            FileName = fileName ?? Resources.DefaultLogFileName;

            var directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
            if (directoryInfo != null)
                filePath = Path.Combine(filePath ?? directoryInfo.FullName, Resources.DefaultLogFilePath, FileName);
            FilePath = filePath;

            var projectName = Assembly.GetCallingAssembly().GetName().Name.ToUpper();
            Write("Hello World!");
        }

        // WRITES TO A TXT FILE, AND AUTO-CREATES A FILE IF IT DOESN'T EXIST.
        public void Write(string message) {
            lock (_lock) {
                try {
                    AppendAllText(FilePath, message);
                } catch (DirectoryNotFoundException ex) {
                    Console.WriteLine(string.Format(Resources.Error_CannotFindLogFile), ex.Message);
                    throw;
                }
            }
        }

        // OPENS THE LOG FILE IN NOTEPAD.
        public void Open() => OpenProgram(FilePath);

        // CLEARS ALL CONTENTS FROM LOG.TXT.
        public void Clear() => WriteAllText(FilePath, string.Empty);
    }
}

What am I doing incorrect?
Comment: This is caused by errors in initialization code for static members (either static prop/field declarations that call methods/constructors, or static constructors). In your case, the `Utility` type cannot be constructed, because in order to do so requires successfully constructing a new `Log`. The first time the `Utility` class is referenced in the code, the type initializers run (e.g. the line `public static Log MyLog = new Log();` runs) It seems like `new Log()` is throwing. Use a debugger. Find out where the issue is happening.
Answer: Not sure exactly in which line the exception is occurring since can't debug your code but you are getting the exception cause initializing Log() is failing somewhere either in the constructor or in the Write() method since inside constructor you are calling Write("Hello World!");. Specifically the line below. You should put a breakpoint in your Log class constructor and step through it and see where exactly it's failing. You already have the reason (see the inner exception message Index (zero based) must be greater than or equal).
public static Log MyLog = new Log();

Comment: @TheAuzzieJesus, no it does flow. Read the answer properly and put a breakpoint and debug through the code and see exactly where it fails. that's what can say at this point.
Comment: The error is occurring in the Main() function of the project, as listed above, and is occurring whenever  `Utility.MyLog.Write("Test");   //<-- ERROR OCCURS HERE` is called. It crashes on this line completely, and doesn't actually flow into the Log.cs class.
Comment: That's what I'm saying. It's crashing on the call of the object, and not allowing me to debug into the `Log.cs` class. I've been trying to debug the code the entire time.
Comment: @TheAuzzieJesus, you really didn't read the answer properly. well put a  breakpoint in your Log class constructor and in Write method and once breakpoint hits press F11.
Answer: I'd guess it's the line that has string.Format(Resources.Error_CannotFindLogFile). The format is unnecessary since WriteLine does it for you.
Comment: Nah, still receiving the same error after the change.
Answer: Turned out it was an Invalid File Path error occurring in my Resource file. I had the incorrect folder name that was being read-in.


Suppose that $x,y,z\in \mathbb{R}^n$ such that $\|y\| \le 1, \|x-y\|\le 4,\|y-z\| \ge 5$ Show that $ |\|x-y\| ^2-\|x\|^2|< \|x\|^2+\|z\|^2$

Question: Suppose that $x,y,z$ are vectors from $\mathbb{R}^n$ such that $\|y\| \le 1, \|x-y\|\le 4,\|y-z\| \ge 5$. Show that
$$ |\|x-y\| ^2-\|x\|^2|< \|x\|^2+\|z\|^2$$
How to prove this?
Here I know that $|\|x\|^2 - \|y\|^2| \le \|x-y\|\|x+y\|
$
So, $|\|x-y\| ^2-\|x\|^2|\le \|x-y+x\|\|x-y-x\|=\|y\|\|2x-y\|$
Answer: Note that
$$\tag1
5\geq\|x\|\geq3.
$$
Because if $\|x\|<3$ you get $\|x-y\|\leq\|x\|+\|y\|<3+1=4$. And $\|x\|\leq \|y\|+4=5$. Also,
$$\tag2
\|z\|\geq4,
$$
because otherwise we get $5\leq\|y-z\|\leq\|y\|+\|z\|<1+4=5$.
Now
\begin{align}
\big||x-y\|^2-\|x\|^2\big|
&=\|x\|^2+\|y\|^2-2\,\langle x,y\rangle-\|x\|^2\\[0.3cm]
&=\|y\|^2-2\langle x,y\rangle\\[0.3cm]
&\leq1+2\|x\|\\[0.3cm]
&\leq11\leq 3^2+4^2\\[0.3cm]
&\leq\|x\|^2+\|z\|^2.
\end{align}


Saving an image in an html document using Agillity pack

Question: I'm trying to save images in a jpeg (or any format) for a given page.
Say that I have this node in the document:

I want to save the image contained in the

HtmlNodeCollection allImgNodes = docToParse.DocumentNode.SelectNodes("//img");

and then this:
foreach(var allImgNode in allImgNodes)
{
    if(allImgNode.Attributes["alt] != null)
    {
        if(allImgNode.Attributes["alt"].Value == objName)
        {
            (... and here I am...)
        }
    }
}

The objName is a string that correspond to the name of the object, in this example, "Object #1" would be objName.
Can anyone help me figure out how to do this? Thank you.
Answer: Thanks to Darin (here: C# htmlagility pack , save image from a URL), I understood another method that helped me a lot.
First with Html Agility Pack I got the url of the image which I stored like this:
string fileName = directoryToStoreImgs + objName + ".jpeg";

Then I used a webClient to download the image:
using (var imgClient = new WebClient())
{
    imgClient.DownloadFile(objUrl, fileName);
}

And now I can store my images :)


Are $form_state values cleaned of malicious code even if #limit_validation_errors is set?

Question: I'm building a multi step form with a bunch of required fields on each step. The user has to be able to save the current step of the form, even if they haven't filled out all the required fields.
I will then save it to a custom entity I've created.
I'm using code like this:
#limit_validation_errors => array(),
#submit => array()

to disable validation. So will Drupal's internal code still clean these values of malicious code when I trigger a submit/save them to the entity? Or do I have to do it myself?
I'm using $this->set('key', $value); to save the data.
Comment: It is not the case. SQL injection is handled by the DB layer (prepared statements), and XSS will be filtered on output, not input (i.e. when rendered, not when saved to the DB or processed in validation/submission)
Comment: Why disable validation?
Comment: What do you mean by "still clean these values of malicious code"? What cleaning of malicious code do you think is being done during normal validation? Are you concerned about XSS? SQL injection? Something else?
Comment: Kevin I have to disable validation because otherwise all the required fields would be checked. If a user gets bored half way through they need to be able to save it and resume later.
Comment: Yes I want to avoid XSS, SQL injection. I assumed that during normal validation, Drupal would 'clean' $form_state values to avoid that kind of thing. Is this not the case?
Answer: If you set #limit_validation_errors, only elements passed into the value are validated. Everything else is not validated. So for example with this:
#limit_validation_errors = array()

Nothing in the form is validated. And with this:
#limit_validation_errors = array('field_1', 'field_2')

Only field_1 and field_2 will be validated.
To continue on with this, only fields that are validated become part of $form_state['values'], and are then passed on to any submit functions. These values will be as safe as any values in a FAPI form submission, as they will be both sanitized and validated.
Any fields not included in the array passed to #limit_validation_errors will not be part of $form_state['values'], and therefore there is nothing to sanitize, nor any malicious code to validate. The element will simply be missing (or maybe empty, I can't remember off the top of my head) from $form_state['values'] in the submit functions.
For myself, the only use case I've ever found for #limit_validation_errors, is one I stopped using. I would use it on a back button for ajax forms, so that the user could step back a step, without getting errors for any fields on that step of the form. The problem however is that any partially filled fields are then lost on that step of the form when going back, since the submitted values are entirely ignored.
What I do instead, is in my validation function, I check to see if the 'next' button has been clicked before validating.
Example form definition (imagine this is step 2 of a multi-step form)
function some_form_step_2($form, &$form_state)
{
  $form['some_field'] = array
  (
    '#type' => 'textarea',
    // See comments after code about why I did this:
    '#title' => t('Enter a value') . '*',
    '#default_value' => isset($form_state['values']['some_field']) ? $form_state['values']['some_field'] : '',
  );

  $form['actions'] = array
  (
    '#type' => 'actions',
  );

  $form['next'] = array
  (
    '#type' => 'submit',
    '#value' => t('Next'),
  );

  $form['back'] = array
  (
    '#type' => 'submit',
    '#value' => t('back'),
  );

  return $form;
}

function some_form_step_2_validate($form, &$form_state)
{
  // check to see if the clicked button was the 'next' button
  if($form_state['op'] == $form_state['next'])
  {
    // Ensure a value has been entered into some_field
    if(!strlen($form_state['values']['some_field']))
    {
      form_set_error('some_field', t('Please enter a value'));
    }
  }
}

function some_form_step_2_submit($form, &$form_state)
{
  // Here, if the 'next' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized
  // and validated

  // However, if the 'back' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized,
  // but not validated, as the validation only needs to happen
  // when advancing to the next step, not stepping back to the
  // previous step
}

As you can see from the code, the validation only happens when the 'next' button is clicked. The field some_field is actually required, however, if #required is set on the field, it will always be validated when the back button is clicked. This can be prevented with:
$form['#limit_validation_errors'] = array();

However, if the user has entered a partial value into this field, #default_value will be empty if the user goes back to the first step, and then returns to this step, since the value will not be made part of $form_state['values']. The way I've built it, the 'required' asterisk (*) is included with the form field title to show the user it is required, but the validation of the required field only happens when advancing to the following step, not when going back to the previous step. This way the user can go back whether a value has been entered into the field or not.
Another added advantage of this method is that a custom error message can be shown for required fields. If #required = TRUE was set on the field above, instead of  using the method I did, the error message would be 'Please enter a value? is required' (or something close), which is not very clean English. With the code above, the message is instead 'Please enter a value', with the field highlighted.
Comment: So I have implemented this and it works but it is a pain in the arse to setup. I think Form API should add a new attribute like #ignore_required which would still sanitise data but ignore required fields when a button with that attribute is clicked. I will post a feature request on Drupal 8.


When would a DNS server query my nameserver record?

Question: Our website went down for some people today because dotster changed their IPs for some of their nameservers. ( ns1.nameresolve.com, etc ) ..
Which made me wonder, all the people that had went to our site, would have it cached, people that have not made it to our site would look it up in their DNS, which would not have it and check the next DNS in the chain, which eventually would check nsX.nameresolve.com ( and that would fail if the record was old ).. So at which DNS does it check nsX.nameresolve.com.
Please feel free to edit my question to make it more clear.
Answer: Following up on sybreon's response, I think the issue comes down to TTL.  I don't think it really has anything to do with the TTL for your domain, but the TTL for ns1.nameresolve.com.  All the recursive DNS servers grabbed the IP for ns1.nameresolve.com and the provided TTL.  When nameresolve changed the IP address, they probably didn't degrade the TTL so all the servers that cached the IP address continued using it until the TTL expired.
One of the coolest features of djbdns' tinydns is you can set an expiration date for a particular address.  As you get nearer the time, tinydns gives smaller ttls so that all the dns caches expire at the same time.  At that point your new record becomes active and the transition is seamless.  Granted, it's probably rarely used, but it's ideal for this situation.
Comment: That's just nifty.
Answer: If you request a record your name server is authoritative of from a recursive DNS server it will first ask one of the root DNS servers to tell him an authoritative DNS server for the com. zone (assuming there is no caching). Then it requests the name server for the zone nameresolve.com. which will be nsX.nameresolve.com.. Via a glue record in the response of the com. server the recursive DNS server now knows the IP address of your DNS server and it will ask your server for the requested record.
Answer: Unless your domain itself is a subdomain of nameresolve.com it's likely that a query to the root servers wouldn't have returned any ip details for their nameservers, just the names (unless of course, you'd specifically specified the ip addresses with your registrar).
In that case, the most likely culprit is that the nameserver starting the query (say at their ISP) already had the NS details for nameresolve.com cached with the old IPs. After they request your domain, it'll come back as being assigned to nsX.nameresolve.com. If the requesting server already has that IP cached, it won't bother looking it up again.
When hosting a large number of domains, it's generally a good idea to reduce the cache time for a period before a nameserver ip change to prevent that from occuring. Once the change has gone through the time can be bumped back up again.
Answer: It all depends on the TTL value that you set for your domain. A typical value is to set it to 24-hours. That means that your old address will be cached by other DNS servers in the hierarchy for 24-hours.


Singular Value Decomposition for an image understanding

Question: I'm trying to get an intuitive understanding of what an SVD decomposition does to an image.
From my understanding, for an image $A \in \Bbb R^{m \times n}$, the singular values are the roots of the eigenvalues of $A^TA$ (or $AA^T$), the left singular vectors are the eigenvectors of $AA^T$ and right singular vectors the eigenvectors of $A^TA$.
What does, for instance, just the first left and right singular vector mean in an image and why are we looking at eigenvectors of $AA^T$ or $A^TA$ - how does this relate to an image? Many thanks!
For example, if we look at this image:

Looking at the first left singular vector shows an approximation of the intensity values in the image rows:

Hopefully that makes what I'm asking a little clearer: why does the eigenvectors of $AA^T$ show this relationship?
Comment: Perhaps one of [these interpretations](https://en.wikipedia.org/wiki/Singular_value_decomposition#Intuitive_interpretations) would be useful to you.
Comment: What do you mean by an "image"?  Do you mean that the $i,j$ entry of $A$ is giving us information about the $i,j$ pixel of an image, as in some image file on a computer?
Comment: @Omnomnomnom Yes :)
Answer: Here's an idea that you might like: let $\sigma_j$ denote the singular values (diagonal entries of $\Sigma$), $u_j$ the left singular vectors (columns of $U$), $v_j$ the right singular vectors (diagonal entries of $V$).  We then have
$$
A = U \Sigma V^T = \sum_{j=1}^{\min\{m,n\}} \sigma_j u_jv_j^T
$$
That is, we've expressed $A$ as a linear combination (with positive coefficients) of some set of rank-1 matrices $u_jv_j^T$.  These matrices are "mutually orthogonal" in some sense.
Since the singular values are ranked from largest to smallest, the matrices $u_j v_j^T$ are ranked in decreasing order of the prominence of their contribution to $A$.
A common trick in image processing, then, is to only look at the first few.  That is, we make the approximation
$$
A \approx \sum_{j=1}^k \sigma_j u_j v_j^T
$$
for some $k < \min\{m,n\}$.
Comment: The matrix $A^TA$ is relevant because $\|Ax\|^2 = x^T(A^TA)x$.  $AA^T$ necessarily has the same eigenvalues.
Comment: Thanks for this - I understand taking the sum of the first few singular values/vectors gives a low rank approximation of the image. What I don't understand is why we are looking at the roots of eigenvalues and the eigenvectors of the image multiplied by its transpose. For instance, If I plotted the first left singular vector as a signal, it gives an approximation of the intensity values of the rows of the image. I'm a bit unsure why it shows this.
Comment: That's because $\sigma_1 u_1v_1^T$ gives us a good rank-1 approximation of the image.
Comment: Potentially helpful things to know about: [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis), [min-max theorem](https://en.wikipedia.org/wiki/Min-max_theorem)
Comment: I've added a picture to illustrate what I meant if that's a help. I'm still a bit confused as to why we're looking at $AA^T$.
Comment: OK, I think I understand now. Many thanks for the time.
Comment: Oh, also: $\|x^TA\|^2 = x^TAA^Tx$


Assigning OG group title to OG group image title field

Question: Every member of my site can create groups (OG.) Each group requires a title, an image, and a mission statement. The image Title field is enabled because in some parts of the site, the group images are displayed as thumbnails without the group titles.
However, most users don't bother to fill in the image title field so there is no indication of the group's title or purpose.
The idea here is to have the title of the group show automatically when the mouse cursor hovers above the group image after the group is created.
Any idea on how to accomplish this feast?
Comment: Do you already have rules installed? Pretty sure that could be an easy solution.
Comment: Yes, I have Rules installed. but I can't find the appropriate data selectors after the event "After a group is created."
Comment: Added an answer.
Answer: Your event should be after saving new content of type: your group content type.
Then add a condition, entity has field: node > your image field.
You should then be able add a condition to check if that field is empty.
Your action would then be to set a data value on the image using the node title.
Comment: That was tricky, but it works well! Thanks. :)


Marginal effect calculation in Stata

Question: My estimated dynamic GMM model results are as follows.
$$Y = -0.009 + 0.009PF + 0.015PS - 0.001(PF\times PS)$$
I want to calculate the marginal effect of $PF$ at $PS$ (min, mean, max), which I can express as follows:
marginal effect of $PF = 0.009 - 0.001 PS$.
I can calculate it manually, but it is time-consuming. Is there any command that calculates the marginal effect after dynamic GMM along with its significance in Stata 12 other than margins, or any way that margins can work? The margins command in Stata does not work after dynamic GMM.
Answer: Have you tried using lincom like this?
foreach PS in 10 20 30 {
    lincom _b[PF] + _b[INT]*`PS'
}

You would need to alter the values of PS and the name of your interaction variable. You can use the coeflegend option in xtabond to determine what the coefficients are named.

Marginal effect calculation in Stata


Effectiveness of Median

Question: New to this board and hoping this question is something easy to describe.  I am working on a project that look at median cycle times of emergency department patients length of stay.  Across a quarter, the sample size is fairly large (n=5000).  However, some of the patients (<10% of the sample) have elongated length of stay times since they are technically being held in the emergency department even though they have been admitted to the hospital.  Technically, these patients are supposed to have their cycle times calculated with an endpoint of when they have been placed into this status and not when they leave the department (which is not data that we have available).
Some are arguing that this will unfairly increase the true median time being measured since we cannot make the above calculation due to data limitations.  My feeling is that since we are using median and this only impacts less than 10% of the sample, that the results of including them in the population are nominal and may not be significant.
I would welcome the opinions any other proof statistically to support this argument
Comment: What timescales will the median be calculated on? If you're computing it every week, for example, any week where over half of the patients are in the elongated condition will cause trouble, even if it won't cause trouble in the quarterly statistics.
Comment: How are you modeling this? Are you using a Cox model or some other non- / semi- parametric model?
Comment: Sorry, I'm a bit of a non-statistical guy and don't know about Cox models or others but we are measuring the median on a patient level basis. So that is about 55 samples per day and we will then aggregate a quarters worth of patients and perform the above.  Again, no more than 500 patients per quarter follow the different process whose cycle time is elongated and I am trying to determine if this would sway the median as it is only 10% or so of the entire sample.  My thought is no, but some feel like it does make a significant impact.  Any way to statistically prove them wrong? :)
Answer: I take it that you mean that you have the times that patients are physically transferred to wards rather than those of the decision to admit.
As you state that the extended stays are the ones you think are inappropriately excessive due to the reasons given, then you could remove or censor the highest 7-10% of values and determine the median of the remainder. As you state, if you did an audit for a week or so, you would probably find that the difference in the median will be nominal, as there will be a tendency for most durations to cluster in value relatively close to the median calculated by whichever method is used.
Even without an audit, you could just try it and see with and without such censoring.
However, it may be advisable to review your national regulatory requirements to see whether such an approach would be acceptable.
The advantage of quickly placing patients in specialist wards is that they will get the specialist care that they need and that the emergency unit may not be able to give them the care they need due to pressure of work arising from needing to deal with new arrivals.

Effectiveness of Median


Difference between training, test and holdout set data mining model building

Question: What is the difference between training, test, and holdout sets?
I know these concepts, just want to ensure that I have understood correctly.
Training set is something that we have as of now. We will remove subset from it and removed subset will be called holdout set.
We will build models using remaining data (what remains after removing holdout set) and the holdout set is used to finalized estimates of tuning parameters (step 1)
Then we will build a final model on the entire Training set (including holdout set). Tuning parameters values are same as that we got from step 1.
Test data is something that we get in future. We don't know their Y/dependent variable value and we predict it using our model.
Answer: Well, Hastie, Tibshirani, and Friedman, in their seminal The Elements of Statistical Learning (page 222), say to break the data into three sections:

Training (50%)
Validation (25%)
Testing (25%)

Where the model is built on the training set, the prediction errors are calculated using the validation set, and the test set is used to assess the generalization error of the final model. This test set should be locked away until the model calibration process is finished to prevent underestimation of the true model error.

Hastie, T.; Tibshirani, R. & Friedman, J. The Elements of Statistical Learning: Data Mining, Inference and Prediction Springer Science+Business Media, Inc., 2009
Comment: Consider hyperparameters (such as the lamda used for regularization, the sigma used in the kernel function of a SVM, or the number of hidden layers and neurons per layer in a neural network) as separate from the base parameters of the algorithm. You set parameters during training, tune hyperparameters in validation, and avoid any tuning based on test. A key goal of finding the right hyperparameters is to find the right balance between overfitting and underfitting (variance and bias, respectively).
Comment: which data is used to calculate tuining parameters?
Comment: If I understand them properly, the validation set is used to calibrate the tuning parameters.


Markov Chain for system with failure and repair

Question: I am solving the below problem, and facing a few doubts regarding my approach.
Consider a system with two components. We observe the state of the system every hour. A given component operating at time n has probability p of failing before the next observation at time n + 1. A component that was in a failed condition at time n has a probability r of being repaired by time n + 1, independent of how long the component has been in a failed state. The component failures and repairs are mutually independent events. Let $X_n$ be the number of components in operation at time n. The process $\big\{$$X_n$, n = 0, 1, . . .$\big\}$ is a discrete time homogeneous Markov chain with state space $I$ = 0, 1, 2.

Determine its transition probability matrix, and draw the state diagram.
Obtain the steady state probability vector, if it exists.

From my understanding, there are 3 possible states of the system:

All 2 components are working fine
One component has failed and one is working fine
Both components are in the failed state

So I have arrived to the following Markov Chain diagram:

The 2r is because any one system can be repaired if both are in failed state. Using this diagram, I arrived at the below transitional probability matrix:
\begin{bmatrix}
   -2p  &  2p  &  0  \\
   r    &  -(r+p)  &  p \\
   0  &  2r  &  -2r
\end{bmatrix}
Am I thinking in the right direction? And can anybody help me with the second part of the question? To find the steady state probability vector?
Thanks!
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info).
Answer: I think that, your are messing up with the state transition probabilities.
I recommend to you to draw the Markov chain with the probabilities of both jumping to a new state and to staying in the current state. Remember that for each state the probability of staying a leaving the state should sum up to $1$.
For example, in the state $0$ (i.e., no component is working):

The probability of staying is $p_{00}=(1-r)^2$, that is both components failed to be repaired.
The probability of jumping to state $1$ (one components is working) is $p_{01}=2\cdot r(1-r)$, that is, one of the components is repaired and the other is not (note the 2, that accounts for the fact that either of the components can be repaired/no repaired).
The probability of jumping to state $2$ (two components are working) from state $0$ is $p_{02}=r^2$ that is, both components are repaired.
If you sum up those probabilities you get $r^2 +1+r^2 -2r +2r -2r^2=1$
Comment: Thanks a lot! I can understand now the Markov Chain. But how do we translate this chain in to computing the steady state probability vector?
Comment: @user2774555 to find the steady state vector you have to solve the following equations: $\pi P =\pi$ and $\sum \pi=1$. Where, $P$ is the transition matrix, and $\pi$ the steady state vector. The constrain $\sum \pi=1$ is to ensure that $\pi$ is a probability vector. This is a system of linear equations and, in your case, can be solved by hand easily. Clearly the seteady state will depend on the value of $r$ and $p$.


Como fazer 2 insert ao mesmo tempo com PHP no Banco de Dados MYSQL?

Question: Banco de Dados:
DROP DATABASE IF EXISTS mydb;
CREATE DATABASE IF NOT EXISTS mydb;

USE mydb;

CREATE TABLE clientes (
  cod_clientes INT UNSIGNED NOT NULL AUTO_INCREMENT,
  nome VARCHAR (20) NOT NULL,
  PRIMARY KEY (cod_clientes)
) ENGINE = innodb;

CREATE TABLE erros(
  cod_erros INT UNSIGNED NOT NULL AUTO_INCREMENT,
  nome_erro VARCHAR (150) NOT NULL,
  solucao VARCHAR (255) NOT NULL,
  data_ocorrencia DATE,
  sistema VARCHAR (30) NOT NULL,
  PRIMARY KEY (cod_erros)
  ) ENGINE = innodb;

CREATE TABLE funcionarios (
  cod_funcionarios INT UNSIGNED NOT NULL AUTO_INCREMENT,
  login VARCHAR(15) NOT NULL,
  email VARCHAR(50) NOT NULL,
  senha VARCHAR(15) NOT NULL,
  cpf VARCHAR (11) NOT NULL UNIQUE,
  PRIMARY KEY (cod_funcionarios),
  Fk_Clientes INT UNSIGNED,
  Fk_Erros INT UNSIGNED,
  FOREIGN KEY Fk_Clientes (Fk_Clientes) REFERENCES clientes (cod_clientes) ON UPDATE CASCADE ON DELETE RESTRICT,
  FOREIGN KEY Fk_Erros (Fk_erros) REFERENCES erros (cod_erros) ON UPDATE CASCADE ON DELETE RESTRICT
  ) ENGINE = innodb;

View:
CREATE VIEW VIEW_LISTA_ERROS AS SELECT nome AS Cliente,
nome_erro AS Erro, solucao AS Solucao,
data_ocorrencia AS Data, sistema AS Sistema
FROM  erros, clientes;

select *from VIEW_LISTA_ERROS;

Parte do código do PHP onde estou tentando o Insert:
if ($row == 0) {
    $query = "insert into erros(nome_erro,solucao,data_ocorrencia,sistema)
    values('{$nome_erro}', ('{$solucao}'), ('{$data}'), '{$sistema}')";

    $query2 = "insert into clientes(nome)
    values('{$nome_cliente}'";

    mysqli_query(conexao(), $query);

    mysqli_query(conexao(), $query2);

    header('location: paginaConsulta.php');
  }
}

Comment: a resposta te ajudou? Se sim, procure marcá-la para ajudar outros colegas.
Answer: Boa tarde, mude a ordem da execução assim:
if ($row == 0) {
    $query = "insert into erros(nome_erro,solucao,data_ocorrencia,sistema)
    values('{$nome_erro}', ('{$solucao}'), ('{$data}'), '{$sistema}')";
    mysqli_query(conexao(), $query);

    $query2 = "insert into clientes(nome)
    values('{$nome_cliente}'";
    mysqli_query(conexao(), $query2);

    header('location: paginaConsulta.php');
  }
}

veja se vai te ajudar
Comment: Ele não está inserindo na tabela "clientes". E quando eu puxo a view, ele traz todos os outros dados que eu cadastrei, menos o cliente novo cadastrado. Ou seja, só está cadastrando os dados da tabela erros. Acredito que eu teria que fazer uma prociedure para isso, mas n sei como faz no php, etc.


Regarding age of a player in the the ICC Under 19 World Cup

Question: What is the minimum age for a player to play the ICC Under 19 World Cup? I have tried but cannot know it from any one.
Answer: In this document, there is no where mentioned minimum age limitation so it can be smoothly assumed that there is no minimum age limit
Answer: There is no limit for minimum age. If a young player is good enough he can make into the team.
Comment: Could you please add a reference for this?
Comment: I don't think he'll find a reference - under 19 means under 19. By definition there is no minimum.
Comment: yes, there is no minimum, as the rule for age during 2014 u19 WC was the player should be born on or after september 1, 1994. "NO" mentioning of before.  Afghanistan's Shahidullah became that edition's youngest player at an age of 15.6 years.


Validar campos com javascript no navegador Safari

Question: Estou com problemas ao tentar validar campos de formulário, via Javascript, no navegador Safari.
O código HTML:

            X

            <form action="#" method="post" name="remarcar-cancelar" id="remarcar-cancelar">

                    Por favor nos informe o motivo:
                    Motivo:
                    <select name="motivoCancelamento" id="motivoCancelamento" class="combobox-motivo" required="required">
                        <option value=""> </option>
                        <option value="viagem">Viagem</option>
                        <option value="outros">Outros Motivos</option>
                    </select>

                    <button type="submit" name="remarcar" value="remarcar" id="remarcacao-submit"
                    onclick="return validaMotivoSituacaoSubmit();">Desejo Remarcar</button>

            </form>

Que no botão chama a função JS:

As validações funcionam perfeitamente nos navegadores IE, Firefox, Chrome. Porém no Safari, a validação não funciona e caso o usuário não selecione nenhum motivo, envia parâmetro vazio ao servlet.
Alguém tem alguma dica?
Answer: Experimenta fechar o script assim:
HTML:

            X

            <form action="#" method="post" name="remarcar-cancelar" id="remarcar-cancelar">

                    Por favor nos informe o motivo:
                    Motivo:
                    <select name="motivoCancelamento" id="motivoCancelamento" class="combobox-motivo" required="required">
                        <option value=""> </option>
                        <option value="viagem">Viagem</option>
                        <option value="outros">Outros Motivos</option>
                    </select>

                    <button type="submit" name="remarcar" value="remarcar" id="remarcacao-submit"
                    onclick="validaMotivoSituacaoSubmit();">Desejo Remarcar</button>

            </form>

Script:
var validaMotivoSituacaoSubmit = (function () {
    if (document.getElementById("motivoCancelamento").selectedIndex === 0) {
        alert("Escolha uma opção!");
        return false;
    } else {
    var frm = document.forms["remarcar-cancelar"];
        frm.setAttribute("action", "MSAGEN");
        frm.submit();
        return true;
    }
});

Comment: Dessa maneira continua não funcionando no Safari, somente.


Inverse Laplace Transform of zero

Question: How to prove that the inverse Laplace Transform of zero is zero itself?
$$\mathscr{L}^{-1}\{0\}=0$$
I know that the inverse Laplace Transform of a constant is Dirac's Delta. But I think that that applies only to positive constants.
Thanks
Comment: for any constant $ L^{-1}{C}= C\delta (x) $ if $ c=0 $ we have $0 \delta (t) =0 $ except for the case $ t=0 $
Answer: If $\mathcal{L}(f) = F$, then $\mathcal{L}^{-1}(F) =f$. $\mathcal{L}(0) = 0$ because $\mathcal{L}$ is a linear operator.  Or you can actually compute $\mathcal{L}(0)$ using the definition.

Inverse Laplace Transform of zero


Error about MariaDB when I am using Mysql, discord.py

Question: I am trying to make a command for my bot, in which when I put !p {text}, the text is inserted into the database, I am using Mysql, and the bot turns on, but when I use the command it throws the following error.
<code>discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s)' at line 1
</code>
This is the cmd
<code>@client.command()
async def p(ctx, *, nam: str = None):
    sql = 'INSERT INTO users (name) VALUES (%s)'
    cursor.execute(sql, (nam))
    await ctx.send(f"inserted {nam}")
</code>
Answer: Look at this https://aiosqlite.omnilib.dev/en/stable/api.html
You should really be using asynchronous coding.
Here is an example:
<code>    async with aiosqlite.connect('database_name') as db:
        print("Connection Opened")
        async with db.execute('SELECT object FROM object_table WHERE object_value = ?', (object_value)) as cursor:
            value = await cursor.fetchone()
            value = list(value)
            value = value[0]
        value += 1
        await db.execute("UPDATE object_table SET object = ? WHERE object_value = ?", (value, object_value))
        await db.commit()
    print("Connection Closed")
</code>


Double tennis serve hits opponent purposely

Question: From the video Jelena Ostapenko hits Alize Cornet with a serve and wins point! | Wimbledon 2019, we can see that the serve has given a point. I wonder if they revenge back by serving the tennis ball back by hitting the player, and make the whole game like dodgeball. What would happen after all?
Comment: https://sports.stackexchange.com/questions/15345/are-there-any-rules-in-tennis-regarding-deliberately-aiming-the-ball-at-the-play
Answer: Hitting the opponent/ball kid/empire intentionally is unsportsmanlike conduct and can get one anywhere from a  warning to being disqualified. BUT, deciding whether it was intentional is up to the chair empire . A one-off occurrence is highly unlikely to be judged intentional
Comment: Too small to edit: of / off


Making multiple columns into a row in bigquery

Question: I have a table with below data in bigqyery
Qualification_No 2019.2 2019.1 2018.4
100/1802/5        10     20    30
100/1811/6        15     23    10

I want the data to be like below
Qualification_No No_of_certification
100/1802/5         10
100/1802/5         20
100/1802/5         30
100/1811/6         15
100/1811/6         23
100/1811/6         10

Please help to write a query for this.
Answer: You need to use UNION ALL
select `Qualification_No`, `2019.2` as no from table
union all
select `Qualification_No`, `2019.1` as no from table
union all
select `Qualification_No`, `2018.4` as no from table

Answer: Below is for BigQuery Standard SQL
#standardSQL
WITH `project.dataset.table` AS (
  SELECT '100/1802/5' Qualification_No, 10 col_2019_2, 20 col_2019_1, 30 col_2018_4 UNION ALL
  SELECT '100/1811/6', 15, 23, 10
)
SELECT Qualification_No, No_of_certification
FROM `project.dataset.table`,
UNNEST([col_2019_2, col_2019_1, col_2018_4]) No_of_certification

with result
Row Qualification_No    No_of_certification
1   100/1802/5          10
2   100/1802/5          20
3   100/1802/5          30
4   100/1811/6          15
5   100/1811/6          23
6   100/1811/6          10


Override abstract method, but keep method abstract?

Question: I want to override an abstract method, but keep it abstract so derived classes are required to implement it themselves.
public abstract class ComponentController
{
    public abstract void CreateCustomColumns();
}

public abstract class ClientComponentController : ComponentController
{
    public override void CreateCustomColumns()
    {
        // All grids to do with clients should show these columns.
        Grid.AddColumn("Client" ...
        Grid.AddColumn("ClientLocation" ...
        Grid.AddColumn("ClientPhoto" ...
    }
}

public class ClientInvoicesComponentController : ClientComponentController
{
    public override void CreateCustomColumns()
    {
        base.CreateCustomColumns();
        // On top of the generic columns, I also want to show these.
        Grid.AddColumn("InvoiceNumber" ...
        Grid.AddColumn("InvoiceDate" ...
    }
}

public class ClientCommunicationsComponentController : ClientComponentController
{
    public override void CreateCustomColumns()
    {
        base.CreateCustomColumns();
        // On top of the generic columns, I also want to show these.
        Grid.AddColumn("CommunicationDate" ...
        Grid.AddColumn("CommunicationType" ...
    }
}

In this code, ClientInvoicesComponentController is not required to implement CreateCustomColumns() because this is not allowed:
public abstract class ClientComponentController : ComponentController
{
    public abstract override void CreateCustomColumns()
    {
        Grid.AddColumn("Client" ...
        Grid.AddColumn("ClientLocation" ...
        Grid.AddColumn("ClientPhoto" ...
    }
}

--> "Abstract method cannot declare a body"

So, how can I override CreateCustomColumns() in ClientComponentController, but still force it to be overridden again in derived classes like ClientInvoicesComponentController?
Of course it still CAN be overridden anyway, but there is nothing to indicate to the developer that it MUST be overridden... which is my aim.
-Brendan
Comment: I swear this question was asked just a while before. Aaanyways: this is not possible, just make your shared implementation a different method, or use the template method pattern. Clearly if nobody can ever  directly call the implementation `B.A()`, there's no point for it to be an override of a `public abstract` method.
Comment: It might help if you explain a little of exactly what you are trying to do. It looks from here like you are trying to provide a *half-implementation* in class B that derived classes must override but can choose whether to use the base or not, which is quite confusing IMHO. It would really help to see a use-case.
Comment: I've added the use case to the post, if it helps.
Comment: @BrendanHill Near as I can tell there's nothing this would solve that moving the implementation of `ClientComponentController` to a nonabstract protected method wouldn't do. I also don't see much of a reason why the overrides would need to call the base method - it seems that your design is that overriding classes *add* new columns to the grid, so you might as well just always call the base implementation from a constructor.
Comment: @BrendanHill And if you want the overriding classes to have control over whether or not the base class' columns get added or not, you can always expose a collection of column definitions and make this manipulation explicit instead of having it be an artefact of the inheritance chain.
Comment: @BrendanHill Last, but not least, you run into the problem where every override **must** call the base implementation. This is kind of error prone, and C# offers a better way to do this - events. I'd create a protected event called `CreatingColumns` where the event object passes a collection of column definitions to all the listeners. Then child classes may register an event handler in the constructor, or they might not, and this event handler may modify the collection as it sees fit. (The constructor is special in that a base implementation is *always* called.)
Comment: Hi millimoose, sequence of events problems prevent me from triggering the code in the constructor of the intermediate class unfortunately.

I agree though that expecting the derived classes to religiously call base.CreateCustomColumns() is error prone so perhaps my idea is flawed to begin with.
Answer: In a word: Not.
A method being abstract means that it is declared but not defined. Being defined but abstract does not really make sense in this context, so it is not possible.
I would also very much like to know your use case. If there is some behaviour you want subclasses to inherit, but also add their own functionality, you could so something like this:
public abstract class BaseClass
{
    public void DoSomething()
    {
        // Base class behaviour goes here.
        DoSomethingInternal();
    }

    protected abstract void DoSomethingInternal();
}

public class SubClass : BaseClass
{
    protected override void DoSomethingInternal()
    {
        // Sub class behaviour goes here.
    }
}

Comment: Thanks Jan, I suspected as much. I have updated the post with a use case FYI, in case you have any further ideas.
Answer: In this case, I think it would be better to divide your logic into 2 methods, one method you play with and the other method your users play with. Assuming the "CreateCustomColumns" method is the name you want your users to override, you create another method, say "CreateCustomColumnsCore", for yourself. The classes may look like this:
public abstract class ComponentController
{
    protected abstract void CreateCustomColumnsCore();
}

public abstract class ClientComponentController : ComponentController
{
    protected override void CreateCustomColumnsCore()
    {
        // your code here

        CreateCustomColumns();  // call users' implementation
    }

    public abstract void CreateCustomColumns();
}

public class ClientInvoicesComponentController: ClientComponentController
{
    public override void CreateCustomColumns()
    {
        // user must implement this method.
    }
}

Users can still override your CreateCustomColumnsCore method, this could be a feature or a bug based on if you can permit users to do this.
Comment: Thanks Ricky, unfortunately there are "sequence of events" problems which prevent this from being an option, ie. CreateCustomColumns() must be triggered as a specific point in the sequence, rather than the constructor.
Comment: Sorry, that comment was intended for the responses above.

Your suggested option could work as well, except that many classes inherit from the base ComponentController and override CreateCustomColumns() directly. This solution would bring inconsistency between areas as to which needed to be overridden.
Comment: Thanks Ricky - I went with your suggestion in the end, and accepted the minor inconsistency across the program.
Comment: I don't think this is sort of inconsistent. These 2 methods are for 2 different purpose in your case. Alternatively you can keep the method name consistent, but you need to ask your users not to forget calling your base method. I'm not sure if there's a second better choice.
Comment: On the other hand, I don't think you really need to force your users to call your base method because they must do, otherwise your users wouldn't get the correct output.


Blocks in a given numeric vector

Question: Given a sequence of integers:
1,1,2,3,1,3,4,5,6,2,2,2,7.
It is required to report the no. of occurrences of each integer {1,2,3,4,5,6,7} but block-wise. Block-wise means an integer occurring in the sequence in non-contiguous positions should be treated in different blocks.
Required output for the given sequence:

1->2
2->1
3->1
1->1
3->1
4->1
5->1
6->1
2->3
7->1
Comment: Do you have a question? If so, can you state what it is?
Comment: try ... `?rle` ...
Answer: You can use the function rle():
x = c(1,1,2,3,1,3,4,5,6,2,2,2,7)
(t = rle(x))

which returns
> x = c(1,1,2,3,1,3,4,5,6,2,2,2,7)
> (t = rle(x))
Run Length Encoding
 lengths: int [1:10] 2 1 1 1 1 1 1 1 3 1
 values : num [1:10] 1 2 3 1 3 4 5 6 2 7

Blocks in a given numeric vector


Probability of relations in a network

Question: Imagine, i have a random graph with $n$ nodes representing people. Between every two nodes there is an edge representing friendship with probability $p_2$. These edges are independently generated, so I expect there to be $\binom{n}{2}p_2$ friends. Now, imagine, I count (observe) the number of times that 3 people are all friends of each other in this world: $\binom{n}{3} p_3$. Therefor, I expect the probability of three random people being friends to be $p_3$. (probabilities $p_2, p_3 \in [0..1]$)
I'm trying to calculate the probability that any 4 people in my world are all friends with each other. Without knowing $p_3$ I would estimate the probability to be $p_2^6$. But obviously knowing $p_3$ influences the probability. For example if $\frac{p_3}{p_2}$ increases, I expect the friendships to be denser and thus more 4 people will form groups. I have trouble however finding a formula to express this probability, because the probabilities that the different subgroups of 3 people are friends are not independent. And if I take four random people the probability that at least 3 subgroups of three people are friends is the same as that at least 4 subgroups of three people are friends.
Could you provide any advice on how one typically calculates such a problem or what to search for? By what factor does $\frac{p_3}{p_2}$ increase the probability of a third connecting edge in presence of two edges? I would assume one would somehow express this using conditional probabilities, although I can't seem to figure out exactly how.
Comment: The meaning of your notation is obscure. Presumably "$p$" by itself means "probability of"; evidently the "$p_i$" are numbers in the range $[0,1]$; and likely the value of "$\text{friends}$" is logical. But how are these related to "people"?  Exactly how are they "generated"?  Due to this vagueness, by the time one gets to the second paragraph your post is unintelligible. Could you edit it to include explanations of the notation and to clarify your random generation process?
Comment: @whuber You're absolutely right, I hope it is clearer now?
Comment: It is clearer, but I should point out that you appear to move back and forth between probabilities, frequencies, and estimates without distinguishing them. This could be confusing you and it likely will confuse your readers, too. You might try explaining things in words. For instance, are you thinking of people as $n$ nodes of a graph and "friends" as *independently* generated edges, each with probability $p_2$? Or is $p_2$ the *observed relative frequency* of edges in a particular graph? Such English descriptions can help resolve the ambiguities of your notation and clarify your question.
Comment: @whuber I tried to clarify the issues you mentioned now
Comment: Thanks. You still seem to confuse probabilities with observed frequencies. If I'm interpreting this correctly, then $p_2$ and $n$ ought to completely determine the *probabilities* of three, four, ..., etc. people being friends, so isn't your question simply what are the formulas for them?
Comment: @whuber Yes, but the complication is the observation that there are $\binom{n}{3}p_3$ triangles. Therefor the probability of three people being friends is not $p_2^3$ but $p_3$ and this will have implications on the probability that 4 people are all friends.
Answer: The answer to this is simple:
For $n$ nodes with probability $p$ of a connecting edge, the probabilty $p_n$ that a given group of all selected nodes have mutual connecting edges is:
$p_n = p^ \frac{n!}{2(n-2)!}$
That is, the combined probability that the required number of unique edges required occur concurrently.
To illustrate:
for $n = 2$:
$p_n = p_{12}$

for $n = 3$:
$p_n = (p_{12})(p_{13})(p_{23})$

for $n = 4$:
$p_n = (p_{12})(p_{13})(p_{14})(p_{23})(p_{24})(p_{34})$

As the probability of any connecting edge has been defined as $p$, there is no need to further delimit the probability of any two specific nodes having a connecting edge.
Therefore:
for $n = 2$:
$p_n = p^1$            (identity)
for $n = 3$:
$p_n = p^3$
for $n = 4$:
$p_n = p^6$
The probability of an edge occuring between two nodes is not affected by whether one of the nodes has other connecting edges.
Mutual Inclusion Factor
If, however, you're looking for a probability $p_n$ given a conditional $p(s)$ that is dependent on the number of shared other connections $s$:
$p(s)$ = probability of a shared edge given $s$ mutual connections to other nodes
To illustrate:
for $n = 2$ and $s_{12} = 2$:
$p_n = p(s_{12})$

for $n = 3$:

$p_n = (p(s_{12}))(p(s_{13}))(p(s_{23}))$
for $n = 4$:
$p_n = (p(s_{12}))(p(s_{13}))(p(s_{14}))(p(s_{23}))(p(s_{24}))(p(s_{34}))$
etc.
$p(s)$ values would have to be determined through an analysis of your particular network- (what is the probability of two nodes sharing an edge given that they share connections to $s$ other nodes?) as would $p$ in the original case.

Probability of relations in a network


What is the real necessity of Apple's Reachability framework?

Question: I have read up on the Reachability framework and am still confused why the definition of a host is being reachable is "when a data packet... can leave the local device".
If reachability returns "yes" then it seems that I still need to try and make a socket connection and until that actually connects I do not really know my host is up. Why doesn't Reachability use a Ping to get a better idea of whether the host is actually up? And what is the need of this framework in the first place?
My guess is these two, but if anyone knows any other reasons to use the Reachability framework please let me know.
1) Reachability gives a callback which gives instant notification when the internet comes back up. When this occurs a socket connection can be immediately attempted. However in 99% of applications it seems acceptable to just attempt a socket connection every few seconds, or worst case just try to make the connection when a user does a certain action. Granted, this is not an ideal solution but I don't see why the Reachability framework would ever be really necessary for this reason.
2) Even in the case where a socket connection has been made to the server, Reachability gives an important bit of information about whether the network is G3/WiFi. I think this is the only time Reachability is really necessary because it allows optimization of behavior according to network type.
Comment: Well 1) it lets most developers who aren't so focused on socket connections (mostly WebViews) gracefully handle a lack of Internet connection.  And 2) if you don't like it, fork it and make your own.
Comment: But WebViews also have a mechanism for when the site can't be reached, correct?
Answer: Reachability is actually quite useful: Given your case (1), you forget that it gives you notifications on both network up and down events. Meaning you can set the callback to handle events such as losing network connectivity (which happens more than you would like on both WiFi and 3G).
Additionally, testing a connection using a socket is not that straightforward; Socket operations are , by default, blocking, and though you can use asynchronous operations (or threads), doing so involves writing code. Not to mention trying DNS when the network is down, and other such issues. By setting a reachability target using the framework, you can alleviate the need to handle all sorts of issues like these yourself, and simply wait for that callback.
Hope this helps,
TG


Compact operator on a hilbert space.

Question:
Possible Duplicate:
A compact operator is completely continuous.

I came across this question in a book, it is an exercise, I can't prove it. Can someone please help me.
If $X$ and $Y$ are Banach spaces, we have to prove that a compact linear operator is completely continuous.
 A mapping $T \colon X \to Y$ is called completely continuous, if it maps a weakly convergent sequence in $X$ to a strongly convergent sequence in
$Y$ , i.e., $x_n\underset{n\to +\infty}\rightharpoonup x$  implies $\lVert Tx_n-
Tx\rVert_Y\to 0$.
Comment: So... johnathan's homework can be found verbatim in carla's book? :) which book?
Comment: A study guide to functional analysis by R. K. Chopra.
Comment: @t.b. ping on behalf of carla.
Answer: Suppose not. Then there is some sequence $(x_n)$ in $X$ with $x_n \rightharpoonup x$ but $Tx_n \not\to Tx$. That is, there is some $\epsilon > 0$ such that $\|Tx_{n_j} - Tx\| \ge \epsilon$ for some subsequence $(x_{n_j})$. As $(x_{n_j})$ is bounded and $T$ is compact, some subsequence converges in $Y$, say $Tx_{n_{j_k}} \to y$. As $T$ is norm-to-norm continuous, it is weak-to-weak continuous, hence $Tx_{n_{j_k}} \rightharpoonup Tx$. Weak limits are unique, so $Tx = y$, that is $Tx_{n_{j_k}} \to Tx$, contradicting the choice of $(x_{n_j})$.
Hence $T$ is completely continuous.

Compact operator on a hilbert space.


Commerce Kickstart Review Overrides Error

Question: I want to upgrade Commerce Kickstart (commerce_kickstart-7.x-2.53) to the latest 2.54. Following the upgrade instructions I went to the Structure Features menu to check for overrides and found these are overriden.
Commerce Kickstart Blog
Commerce Kickstart Lite Product
Commerce Kickstart Merchandising
Commerce Kickstart Slideshow
Commerce Kickstart User

But when I go to Review Overrides, I get these errors.
Notice: Array to string conversion in features_override_features_export_render_addition() (line 428 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/features_override/features_override.export.inc).
Notice: Array to string conversion in features_override_features_export_render_addition() (line 428 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/features_override/features_override.export.inc).
Error: Call to a member function stateVariables() on string in RulesPlugin->availableVariables() (line 740 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/rules/includes/rules.core.inc).

First, is there a fix for these errors?
If not, is there any way to know what overrides are actually in place?
In any case, can I proceed with the Commerce Kickstart (commerce_kickstart-7.x-2.54) upgrade?

FYI: Running Drupal 7.58 and PHP Version 7.1.16
Thanks
Comment: Workaround is to click on the feature name and it lists all settings for that feature, then Review Overrides gives changes for that feature so I have been able to print the list of changes for each feature.
Answer: Are you sure those modules are compatible with PHP 7? We haven't tested nor do we recommend running Commerce Kickstart 2.x in PHP 7 as far as I know.


Por que meu cancelAnimationFrame() não esta funcionado no JavaScript?

Question: window.onload = function(){
class Objeto{
  constructor(){
    this.x = 10;
    this.y = 10;
    this.velY = 2;
  }
  dObjeto(){
    ctx.beginPath();
    ctx.rect(10,this.y,100,100);
    ctx.closePath();
    ctx.fill();
  }

  stop(){
    cancelAnimationFrame(id);
  }
  anima(){
    ctx.clearRect(0,0,canvas.width, canvas.height);
    objeto.y += objeto.velY;
    objeto.dObjeto();
    //Eu queria que quando alcançasse o valor máximo ele parace com o método stop()
    if(objeto.y + objeto.velY > canvas.height || objeto.y + objeto.velY < 0){
      objeto.velY = -objeto.velY;
      objeto.stop();
    }
    id = requestAnimationFrame(objeto.anima);
  }
}

//Eventos
//Função para mecher na dimenssão da canvas
function canvasT(){
  canvas.width = 700;
  canvas.height = 450;
  canvas.style.border = 'solid';
}
canvasT();
var id;
var ctx = document.getElementById('canvas').getContext('2d');
var objeto = new Objeto();
objeto.dObjeto();
objeto.anima();
window.addEventListener('keydown', objeto.pula, false);
//So funciona a cancelAnimationFrame() se eu apertar o click evento abaixo
window.addEventListener('click', objeto.stop, false);
}

Answer: Coloque um return; após chamar objeto.stop(); dentro do anima(), senão o código continuará na próxima linha id = requestAnimationFrame(objeto.anima); que continua a animação:

window.onload = function(){
class Objeto{
  constructor(){
    this.x = 10;
    this.y = 10;
    this.velY = 2;
  }
  dObjeto(){
    ctx.beginPath();
    ctx.rect(10,this.y,100,100);
    ctx.closePath();
    ctx.fill();
  }

  stop(){
    cancelAnimationFrame(id);
  }
  anima(){
    ctx.clearRect(0,0,canvas.width, canvas.height);
    objeto.y += objeto.velY;
    objeto.dObjeto();
    //Eu queria que quando alcançasse o valor máximo ele parace com o método stop()
    if(objeto.y + objeto.velY > canvas.height || objeto.y + objeto.velY < 0){
      objeto.velY = -objeto.velY;
      objeto.stop();
      console.log("PAROU!");
      return;
    }
    id = requestAnimationFrame(objeto.anima);
  }
}

//Eventos
//Função para mecher na dimenssão da canvas
function canvasT(){
  canvas.width = 700;
  canvas.height = 450;
  canvas.style.border = 'solid';
}
canvasT();
var id;
var ctx = document.getElementById('canvas').getContext('2d');
var objeto = new Objeto();
objeto.dObjeto();
objeto.anima();
window.addEventListener('keydown', objeto.pula, false);
//So funciona a cancelAnimationFrame() se eu apertar o click evento abaixo
window.addEventListener('click', objeto.stop, false);
}
<canvas id="canvas"></canvas>


Dynamics of matrices over finite field and Similarity of matrices

Question: Consider a set $M$ of all possible square matrices over a finite field $F_p$.  Now consider a map $f_A(x)=A.x$ where $x$ $\in$ $M$ and also the matrix $A$ is a member of $M$. It is needless to mention that the set M forms a vector space over field itself with the module p addition and modulo p scalar multiplication. So the map $f_A$ is linear.
Consider a dynamical system $X_{t+1}=f_A(X_t)$. Suppose there is an orbit of a vector $u$ $\in$ $M$ is $A.u$, $A^2.u$...$A^k.u$.... Let $v=Pu$ where $P$ is another matrix from the set M. So the vector v is generated by a linear operator $P$.
Question is: Is it possible to derive a matrix B which is ''similar'' to the matrix A such that the orbit of the vector $v$ with respect to the map $f_B$ on $M$ is $B.v$, $B^2.v$...$B^k.v...$ ?
Comment: The trajectory of $v$ under $f_B$ is $v,Bv,B^2v,\cdots$ no matter what $B$ is, no? (I will avoid the word "orbit," since that could suggest a matrix is invertible, as per group actions.)
Comment: Yes, not necessary B to be invertible.
Comment: But isn't the trajectory of $v$ under $f_B$ necessarily $v,Bv,B^2v,\cdots$ no matter what? It doesn't make sense to ask to "derive" a $B$ for which it works for a specific $v$($=Pu$), if it works for all $B$ and $v$.
Comment: B needs to be similar to A.
Comment: Do you understand my comment?
Comment: In the question there is no condition linking $B$ to $A$. For every $B$ it holds that the orbit of $V$ is $Bv$, $B^2v$, ...
Comment: B needs to be similar to A. Is it not a condition?
Comment: So by "similar", I don't think you mean the formal definition of "similar", right? (Matrices $M_1$ and $M_2$ are similar if $M_2 = VM_1V^{-1}$ for some $V$.) You mean "the behavior is the same"? Perhaps the orbit has the same size? You won't get a very good answer unless you more clearly define what similar means.
Comment: Yes, I mean formal definition of Similar matrices.
Answer: You require $Bv = BPu = Au$ and $B^2 v = B^2 Pu = A^2 u$.  This requires $B^2Pu = BAu = A^2u$.  So $BP$ has all the same eigenvalues as $A$ and also $B^2P$ has all the same eigenvalues as $A^2$.  These together imply $B$ has the same eigenvalues as $A$ and $P$ has only the repeated eigenvalue $1$ (and is orthogonal).  So your $B$ only exists if $P$ is an orthonormal rotation of the coordinates.


alert is not working due to clicking on prevent checkbox

Question: I am using google chrome as a browser and I clicked on checkbox Prevent this type of message from next time. Now alert("Hi..") is not showing. How to activate this please help me.
Answer: close your browser, and re-access the page. It will auto start alerting.
Comment: Thanx actually i am new so i didn't know.


Erro ao tentar Acessar WebService

Question: Estou com o seguinte problema,tenho um WebService asmx, postado em um IIS,com a configuração de autenticação setada como Anônima,porem quando tento acessar o mesmo aparece o seguinte erro:

Precisso conseguir acessar este WebService para efetuar alguns testes.
Agradeço desde ja.
Comment: Libera o CORS da tua aplicação e desativa a autenticação. Esse problema também pode ser de acesso as pastas no seu servidor.
Comment: Seu webservice é um asmx. wcf ou uma api rest?
Comment: @LeandroAngelo este se trata de um asmx.
Comment: Acessa ele com o caminho completo até o .asmx e adiciona um ?wsdl no final
Comment: Acabei de testar e necessitava o acesso ao caminho completo obrigado pela ajuda de qualquer forma
Comment: Esse endereço é só para esse webservice ou tem um asmx? você pode adicionar esse arquivo como default no IIS.
Comment: Sim esse endereço é exclusivo para este WebService, se eu adicionar como default ele o redireciona ?
Comment: @VictorAugusto Veja a resposta abaixo.
Answer: Por padrão o IIS não possui a extensão .asmx na lista de documentos padrão do website, no seu caso, por não haver nenhum default como última alternativa ele vai tentar exibir a lista de documentos do diretório. Como esse recurso por padrão não é habilitado você recebe a mensagem de erro apresentada em sua pergunta.
Para acessar o seu serviço você deve é necessário utilizar o caminho completo do seu asmx.
Outra alternativa, muito incomum, mas caso esse endereço seja exclusivo para prover esse webservice ou que seja sua principal função.  É adicioná-lo na lista de documentos padrão seguindo os passos ilustrados abaixo.
Porém, é sempre recomendado fornecer o caminho completo do arquivo, pois muitos programas precisam acessar o endpoint com a extensão .asmx mais a query ?wsdl para conseguir realizar o mapeamento dos endpoints e refletir a estrutura de objetos dos seus contratos.
Caso queria deixar esse WS como defult do seu site,  É adicioná-lo na lista de documentos padrão seguindo os passos ilustrados abaixo.

Caso não tenha acesso direto ao Gerenciador do IIS, você pode tentar passar a instrução em seu Web.config
 <system.webServer>
     <defaultDocument>
            <files>
                <clear />
                <add value="nome_do_seuWS.asmx"/>
            </files>
        </defaultDocument>
    </system.webServer>

Comment: Agora ficou claro a ocorrência do erro Leandro, vou definir o WS como default desse site para testes.Obrigado pelo esclarecimento ,Abs

Erro ao tentar Acessar WebService


Simple way to send mail from Docker container?

Question: I have a backup script that runs inside a Docker container and I would like it to send me an email when disk usage gets low.
Here's the script:
<code>#!/bin/bash
CURRENT=$(df /data | grep / | awk '{ print $5}' | sed 's/%//g')
THRESHOLD=90

echo "$CURRENT"

if [ "$CURRENT" -gt "$THRESHOLD" ] ; then
    echo "Low Disk Space Alert: ${CURRENT}% used"
  mail -s 'Disk Space Alert' email@example.com << EOF
Backup server remaining free space is critically low. Used: $CURRENT%
EOF
fi
</code>
The problem is that I can't manage to get mail to work inside the container. Here's my Docker file:
<code>FROM ubuntu:latest
MAINTAINER firstname.lastname@example.com
ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update && \
  apt-get install -y postfix && \
  apt-get install -y mailutils && \
  apt-get clean
ADD rootfs /
CMD /disk-alert.sh
</code>
I've tried a few things but the best I could do is get the mail command to complete without error (though I didn't receive anything to my email).
Is there a simple way to configure my container to be able to send mail? I don't care if the mail goes to spam as long as I receive it.
Answer: As Jason already mentioned, I think it is indeed cleaner to separate your MTA and backup container.
I ran into this problem some time ago (although I tried to send mail from PHP instead of bash), and I discovered the exim-sender container, which is basically a simple container that acts as an outgoing SMTP server.
Why not link your backup container to such an SMTP container? If you then use ssmtp, you can send mails through the SMTP container. Or you can just use another (external) SMTP server if you prefer.
Answer: Consider sending an email from something like Amazon SES or MailGun or any other HTTP-based mail API rather than adding an entire MTA to your container.
Or make an API call to a alerting system such as OpsGenie or PagerDuty for it.


Related Rates Ladder

Question: When a ladder is falling, why doesn't the top of the ladder fall at the same speed as the bottom of the ladder? I understand how one can solve the derivative using $x^2+y^2=z^2$, but I don't really understand how to intuitively think about this.
Comment: How exactly does a ladder "fall"?  Does it fall as a vertical translation, or does it rotate (with the bottom end of the ladder fixed)?  If the notion of a ladder falling cannot be clear to you, Readers will have to guess what is meant (likely in vain).
Answer: Consider a ladder leaning against a wall such that $l-b>h$, where

$h$ is the height at which the ladder meets the wall,
$b$ is the distance from the base of the ladder to the wall, and
$l$ is the actual length of the ladder.

Note that this is equivalent to $b+h<l$, and this will hold whenever the ladder is neither fully vertical or fully horizontal. (Why? If $x, y>0$, then $(x+y)^2=x^2+y^2+2xy>x^2+y^2$; now use the Pythagorean theorem ...)
Now let's think about what happens as the ladder slides down the wall. From the time it starts sliding to the time it stops (= lies fully horizontal), the base has to travel a distance of $l-b$ along the ground, but the top of the ladder will only travel a distance of $h$ along the wall. So intuitively, we should expect the top of the ladder to move down the wall more slowly than the base of the ladder moves along the ground because the base has further to go in the same amount of time.
Answer: What makes you think that the top of a ladder doesn't fall at the same rate as the bottom?  If you carry a 20 ft ladder to the top of a 120 ft high building and drop the ladder off, the "top" and "bottom" of the ladder will fall at the same speed.  Or are you thinking of the case where the ladder is leaned up against a wall, the top starts sliding down the wall while the bottom moves away from the wall?  Of course, in that case,  the bottom isn't "falling" at all!
Are you actually asking "when the top of a ladder slides down a wall and the bottom slides away from the wall, does the top of the ladder slide down at the same rate at which the botton slides away from the wall?
If that is the case, suppose a ladder, of length L, is leaning up against a wall with its top at height h.  In that case, by the "Pythagorean theorem", the base of the ladder is at distance $x= \sqrt{L^2- h^2}$.  Squaring both sides, $x^2= L^2- h^2$.  Differentiating with respect to time, t, we have $2x\frac{dx}{dt}= -2h\frac{dh}{dt}$ or $x\frac{dx}{dt}= -h\frac{dh}{dt}$.  $-\frac{dh}{dt}$ is the rate at which the top is sliding down the wall (so negative) and $\frac{dx}{dt}$ is the rate at which the bottom is sliding away from the wall.  We can write $x\frac{dx}{dt}= -h\frac{dh}{dt}$ as $\frac{\frac{dx}{dt}}{\frac{dh}{dt}}= -\frac{h}{x}$.  The two rates (ignoring the negative sign) are the same only when x= h- that is, when the ladder is at a 45 degree angle.
Comment: Yes, I meant: when the top of a ladder slides down a wall and the bottom slides away from the wall, does the top of the ladder slide down at the same rate at which the botton slides away from the wall

Related Rates Ladder


For a 16bit floating point texture format such as SurfaceFormat.Rgba64 what is the range after the floating point?

Question: When rendering in HLSL using SurfaceFormat.Rgba64 I only have a range of [0, 1].  To work around this I wish to use the entire (not sure of the correct terminology?) range of numbers after the floating point.
I can do this by using two constants to shift the numbers to the left (16BIT_MULTIPLIER) and right (16BIT_INVMULTIPLIER)
16BIT_MULTIPLIER = 1000
16BIT_INVMULTIPLIER = 1 / 16BIT_MULTIPLIER

What is the maximum amount I can shift the numbers to the right and maintain correct precision?  In other words what is the maximum value 16BIT_MULTIPLIER can be?
Answer: In a standard 32-bit IEEE 754 floating-point value, the maximum ratio between the most significant bit in a number and its least significant bit is 223. This is because the floating-point encoding has 24 bits (including an "implicit bit") for the significand (or fraction). So the highest bit may be 223 while the lowest bit is 20 (1), or the highest bit may be 212 while the lowest bit is 2-11, for examples. In your case, you may wish to use a highest bit of 2-1 with a lowest bit of 2-24. You tell us the range you are mapping to ([0, 1]) but not the range you are mapping from, so we cannot tell you the scaling factor to use.
If you are mapping from unsigned 16-bit numbers, with a range of [0, 65536), you could use a scaling factor of 1/65536. (In many languages, you would write 1./65536 to get a floating-point constant; 1/65536 would be an integer expression that evaluates to zero.) This scaling would map all your numbers into the target range with available precision "below" the numbers, but it would not leave any margin for adding numbers or other operations that increase magnitude. If you want to leave room for more arithmetic while keeping results in the interval [0, 1], then you need a larger ratio (smaller scaling factor).
You should use powers of two for the scaling factor. Multiplying by powers of two has no rounding error in binary floating point. Multiplying by powers of ten or their inverses (which are necessarily approximate since inverses of powers of ten cannot be exactly represented in binary floating point) usually cause rounding errors.
In a standard 64-bit IEEE floating-point value, the maximum ratio is 252.
You ask what the maximum value 16BIT_MULTIPLIER can be, but it is unlikely this is what you actually want. You can make 16BIT_MULTIPLIER as large as you like until the low bits of the numbers reach 2-149. At that point, you reach the end of the exponent range (2-126 for the high bit), and bits with smaller values cannot be represented (in 32-bit floating point).
Comment: Excellent answer, thank you.  Could you please elaborate on the following?  **This scaling would map all your numbers into the target range with available precision "below" the numbers, but it would not leave any margin for adding numbers or other operations that increase magnitude. If you want to leave room for more arithmetic while keeping results in the interval [0, 1], then you need a larger ratio (smaller scaling factor).**
Comment: If you map numbers in [0, 65536) by multiplying by 1/65536, then numbers like, say, 57344 and 49152, are mapped to .875 and .75. If that is your final result to be passed to the renderer that requires numbers in [0, 1], then fine. But if you are going to do more arithmetic, such as adding these numbers, you will get things outside the interval, like 1.625. In that case, if you want final results to stay inside the interval, you have to plan based on what calculations you will perform. If you are not going to do more arithmetic, then use this scaling. The numbers will have 24 bits of precision.


Smooth Streaming Player - Multi Audio Track - H.264 SmoothStreams

Question: I am trying develop a silverlight player based on SmoothStreamingMediaElement.
For Ref:
SSME:SmoothStreamingMediaElement Grid.Row="2" x:Name="medSmooth" AutoPlay="True" MinWidth="320" MinHeight="240""
Now the Source Smooth Streams are encoded using H.264 video codec and AAC as Audio codec.
I found at below URL, that audiostreamindex and audiostreamcount properties are for WMV type only and that killed my only left hope.
http://msdn.microsoft.com/en-us/library/microsoft.web.media.smoothstreaming.smoothstreamingmediaelement_properties(v=vs.90).aspx
Can any body help me on How I can detect the currently playing language in video, and then I want to put an event handler or "Users action of changing language", once that event i s fired, I want to change the currently playing audio track to the selected one.
Comment: BTW I was able to parse and find out the available list of language tracks available in source manifest file-
Comment: If S.Type = Windows.Media.MediaStreamType.Audio Then
                    ' languages.Add(count.ToString, S.Attributes("Name"))
                    'listLanguages.Add(S.Attributes("Name")
                    Language = New Language()
                    Language.LanguageId = count
                    Language.LanguageName = S.Attributes("Name").ToString
                    listLanguages.Add(Language)
                    count = count + 1
                End If
Comment: Basically I was hoping to create something like this -. http://player.smooth.vertigo.com/ , Try with source video as http://ecn.channel9.msdn.com/o9/content/smf/smoothcontent/elephantsdream/Elephants_Dream_1024-h264-st-aac.ism/manifest
Answer: I suggest to use Silverlight Media Framework, it really simplifies development of video applications. You can download its source code here: http://smf.codeplex.com/downloads/get/386528.
However, you can do some things without framework

How I can detect the currently playing language in video

Here is the code:
var currentSegment = mediaElement.ManifestInfo.Segments[mediaElement.CurrentSegmentIndex.Value];
var currentAudioStream = currentSegment.SelectedStreams.Where(i => i.Type == MediaStreamType.Audio).FirstOrDefault()

I want to change the currently playing audio track to the selected one

Something like this:
foreach (var segment in mediaElement.ManifestInfo.Segments)
{
    var newStreams = new List<StreamInfo>();
    // use current video streams
    var selectedVideoStreams = segment.SelectedStreams.Where(i => i.Type != MediaStreamType.Audio).ToList();
    newStreams.AddRange(selectedVideoStreams);
    // add a new audio stream
    newStreams.Add(newAudioStream);
    // replace old streams by new ones
    segment.SelectStreamsAsync(newStreams);
}

Comment: Cool! This method works for me, contrary to the solution with setting `AudioStreamIndex` property, described [here](http://www.w3.org/WAI/GL/WCAG20-TECHS/SL1.html). Btw, `AudioStreamCount` always returns `1` for me, even if there are multiple audio streams.
Answer: If you are using SMF, here is the easiest solution:
private CustomPlayer SetAudioStreamLanguage(string languageCode)
{
    const string languageAttributeKey = "Language";

    if (AvailableAudioStreams.Count() < 2) return this;

    var languageCode = new CultureInfo(languageCode).ThreeLetterISOLanguageName();
    if (languageCode == null)
    {
        throw new Exception(string.Format("Audio stream language code {0} cannot be converted to three-letter ISO language code.", languageCode));
    }

    StreamMetadata newAudioStream =
        AvailableAudioStreams.FirstOrDefault(
            s =>
                s.Attributes.ContainsKey(languageAttributeKey) &&
                s.Attributes[languageAttributeKey].Equals(languageCode, StringComparison.InvariantCultureIgnoreCase));

    if (newAudioStream == null) return this;

    SelectedAudioStream = newAudioStream;
    return this;
}

This method should be called after MediaOpened event has been fired.
NOTE: CultureInfo.ThreeLetterISOLanguageName() method does not exist in Silverlight. You can find it's sample implementation in this answer.


iOS 10 Swift and best practices for defining the UI

Question: I'm working on an iOS app in Swift. The other app I created was one I did in Objective C and release around this time in 2014. Storyboards seem to have made UI stuff both easier and more complicated at the same time, so I'm trying to figure out current best practice in terms of view development.
Size classes and constraints seem like almost a necessary timesaver at this point for multiple screen sizes. Back in 2014, this was less the case, and programmatically keeping track of UI layouts as CGRect code made programmatically mucking with UI layout much simpler and better for code reuse vs creating a whole new view controller for just adding new UI elements to much the same view. Doing the same thing with constraint code seems less appealing, but also necessary if I want more code reuse there.
So I'm wondering what the current practice is here as I'm just thinking in terms of code reuse. Programmatic constraints just seem less elegant than storyboard defined ones, but I'm not sure they're the end all be all for UI code since they seem problematic for programmatically updating the UI on the fly.
Is the best strategy at this point to enclose everything in layout preserving superviews and keep most of this storyboard centric or would it still make sense to do swift programmatic code for these layouts since I'd have to for iPad and iPhone specific changes anyway? On that subject would it still make sense to split drastically different UIs into multiple storyboards (e.g. 2 different iPad and iPhone storyboards as that was a default at one point)?
Thanks in advance for answers to this. Device specific stuff just seems to not always be code reuse, but I just want reuse to be relatively simple I guess. Otherwise I'm just creating more swift classes than I strictly need.
Answer: This is inherently opinion based. Everything from no Interface Builder to only StoryBoards is likely being used in production applications, and you can make just about anything work.
My personal tendency is to use Storyboards for everything other than TableView/CollectionView cells. I find it removes almost all interface boilerplate code from my classes and makes it so I only need to handle the interface between my ViewControllers. Here are the guidelines I generally try and follow: (again...opinion)

Use multiple storyboards organized in a useful way:

Large storyboard become hard to maintain and performance while editing suffers noticeably. We have the option to use StoryboardReferences, so might as well use them.

The more Scenes and ViewControllers, the better. (within reason)

This makes things more maintainable and re-usable. E.g. a header that could be used in multiple Scenes. It can be a bit annoying to have to use containerVCs and deal with segues everywhere, but I rarely regret separating something into it's own ViewController.

Don't use separate interface files for different sizes.

It's more code to maintain and will force you to swap ViewControllers in-out if you want to support resizing on iPad (or any future devices). Not to mention going forward it's clear Apple is assuming you're using size classes rather than swapping ViewControllers and is clearly where the future is headed in Apple platforms development

When you need animations, try and narrow it down to changing a single constraint.constant

This greatly simplifies your code and usually avoids having to deal with size-classes anywhere other than the storyboards. It's not always possible for complicated animations, but you can do a surprising amount if you're willing to mess around. It makes it possible to narrow down a toggling action to 2 lines of code, which is quite nice. Using StackViews can also help with this a lot.
The other thing to focus on is avoiding as much of the stringly-typed nature of IB as possible. This is much easier in Swift and there are some decent solutions using string-backed enums and extensions, but specifics are probably out of the scope of this question.


How can I serve static files with nginx but use a slightly different url for tornado?

Question: I have a directory structure I want to serve, that contains files as binary and some meta-information about them as json. for some directories, I need to compute some things on the fly and serve that. I want to compute and serve that information using tornado.
Here is an example:
> ls /manufacturers/*
  audi/
  audi.json
  mercedes/
  mercedes.json

> wget http://localhost/manufactures/audi.json
  returns the json file using nginx static serving
> wget http://localhost/?diesel
  returns a json file with manufactures that
  create cars with diesel engines computed by and using tornado

Answer: You can check with nginx whether ?diesel is being called by looking for $arg_diesel in the location = / block.
location = / {

    if ( $arg_diesel ) {
        proxy_pass http://tornado;
    }

}

location = / is not the same as the location /. location = / will only be called for requests that aren't in a folder such /?diesel, but not /somepath/?diesel whereas the location / will match everything.
Documentation: http://nginx.org/r/location
Answer: If your use-case is "serve static files if they exist, otherwise send everything to tornado", you can do that with try_files:
upstream upstream_tornado {
    server http://127.0.0.1:8080;
    # ...or wherever
}
server {
    listen 80;
    server_name localhost;
    root /path/to/wherever;

    try_files  $uri @tornado;

    location @tornado {
        proxy_pass http://upstream_tornado;
        # Other proxy stuff e.g. proxy_set_header
    }
}

Comment: Using this right now. Works like a charm.


nginx cache images generated by backend

Question: My application generates dynamic content and I try to cache them using browser cache. So If I try to add to my server block the following:
location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 365d;
}

Nginx no longer pass the request to the backend to generate the assets and it ends up with http status code 404
Instead, adding those 2 following conditions could solve my problem (taken from this question):
location / {
    if ($upstream_http_content_type ~ "(image/jpeg)|(image/png)|(image/gif)|(image/svg+xml)|(text/css)|(text/javascript)|(application/javascript)") {
      expires 90d;
    }

    if ($sent_http_content_type ~ "(image/jpeg)|(image/png)|(image/gif)|(image/svg+xml)|(text/css)|(text/javascript)|(application/javascript)") {
      expires 90d;
    }
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /site.php/$1 last;
}

location ~ ^/(site|site_dev|admin|admin_dev)\.php(/|$) {
    # it's PHP that generates some of my assets
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS on;
}

The problem is that I can't see in the http response headers any date that indicates that it's working and images will be served from browser cache for 90 days.
What am I missing ?
Answer: As you generate the HTTP response in your PHP application you should look also at your application regarding the response headers. Browser caching is only a HTTP response header issue. So if your application provides proper headers your web server will serve them and your browser will cache the result.
However you can overwrite this behavior in the web server. But it's never a good idea to do this on web server level. Here you have only URL and request headers to decide if a response should be cached or not. Your application has usually more details to make better decisions.
For the best approach fix your PHP code by sending proper caching headers:
<?php
...
header('Cache-Control: max-age='.90*24*3600);

For the alternate approach you can (but you should not) use this in the Nginx config to overwrite the web app's response:
location ~ ^/(site|site_dev|admin|admin_dev)\.php(/|$) {
    # it's PHP that generates some of my assets
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS on;

    # hide response header sent by PHP
    fastcgi_hide_header Cache-Control;
    fastcgi_hide_header Expires;
    # set Cache-Control response for client
    expires 90d;
}

A better way would be caching on web server level. Here you can configure exceptions and be able to react to special cases like a "Set-Cookie" header in the HTTP response.
By the way new visitors will get an advantage of fast delivery as well. Browser based caching does not help first time visitors.
location ~ ^/(site|site_dev|admin|admin_dev)\.php(/|$) {
    # it's PHP that generates some of my assets
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS on;

    # activate caching (you must define a cache storage for phpfpm)
    fastcgi_cache          phpfpm;
    # enable caching for 90 days for responses with HTTP status 200
    fastcgi_cache_valid    200 90d;
    # allow headers from PHP to client
    fastcgi_pass_header    Set-Cookie;
    fastcgi_pass_header    Cookie;
    # ignore headers from PHP to client
    fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
    # remove headers from PHP to client
    fastcgi_hide_header    Cache-Control;
    fastcgi_hide_header    Expires;
    # don't save in cache
    fastcgi_no_cache       $cookie_PHPSESSID;
    # don't serve from cache
    fastcgi_cache_bypass   $cookie_PHPSESSID;
}

Please take care that this is only a recommendation based on standard settings. It may vary in your setup.

nginx cache images generated by backend


dnf - cannot install the best candidate for the job

Question: I just installed CentOS8...
$ cat /etc/redhat-release
CentOS Linux release 8.0.1905 (Core)
$

... and now trying to follow Get Docker Engine - Community for CentOS | Docker Documentation, yet running into following error:
$ sudo dnf install -y yum-utils   device-mapper-persistent-data   lvm2
Last metadata expiration check: 0:01:25 ago on Thu 31 Oct 2019 03:00:18 PM EDT.
Package device-mapper-persistent-data-0.7.6-1.el8.x86_64 is already installed.
Package lvm2-8:2.03.02-6.el8.x86_64 is already installed.
Dependencies resolved.
=========================================================================================================
 Package                  Arch                  Version                      Repository             Size
=========================================================================================================
Installing:
 dnf-utils                noarch                126.96.36.199-3.el8                BaseOS                 62 k

Transaction Summary
=========================================================================================================
Install  1 Package

Total download size: 62 k
Installed size: 18 k
Downloading Packages:
dnf-utils-188.8.131.52-3.el8.noarch.rpm                                        59 kB/s |  62 kB     00:01
---------------------------------------------------------------------------------------------------------
Total                                                                     28 kB/s |  62 kB     00:02
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                1/1
  Installing       : dnf-utils-126.96.36.199-3.el8.noarch                                                  1/1
  Running scriptlet: dnf-utils-18.104.22.168-3.el8.noarch                                                  1/1
  Verifying        : dnf-utils-126.96.36.199-3.el8.noarch                                                  1/1

Installed:
  dnf-utils-22.214.171.124-3.el8.noarch

Complete!
$ sudo yum-config-manager \
>     --add-repo \
>     https://download.docker.com/linux/centos/docker-ce.repo
Adding repo from: https://download.docker.com/linux/centos/docker-ce.repo
$ sudo yum-config-manager --enable docker-ce-nightly
$ sudo yum-config-manager --disable docker-ce-nightly
$ sudo yum install docker-ce docker-ce-cli containerd.io
CentOS-8 - AppStream                                                     2.0 kB/s | 4.3 kB     00:02
CentOS-8 - Base                                                          1.7 kB/s | 3.9 kB     00:02
CentOS-8 - Extras                                                        736  B/s | 1.5 kB     00:02
Docker CE Stable - x86_64                                                9.4 kB/s |  20 kB     00:02
Error:
 Problem: package docker-ce-3:19.03.4-3.el7.x86_64 requires containerd.io >= 1.2.2-3, but none of the providers can be installed
  - cannot install the best candidate for the job
  - package containerd.io-1.2.10-3.2.el7.x86_64 is excluded
  - package containerd.io-1.2.2-3.3.el7.x86_64 is excluded
  - package containerd.io-1.2.2-3.el7.x86_64 is excluded
  - package containerd.io-1.2.4-3.1.el7.x86_64 is excluded
  - package containerd.io-1.2.5-3.1.el7.x86_64 is excluded
  - package containerd.io-1.2.6-3.3.el7.x86_64 is excluded
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)
$

Please advise.
Answer: try to:
dnf install https://download.docker.com/linux/centos/7/x86_64/stable/Packages/containerd.io-1.2.6-3.3.el7.x86_64.rpm
for more detail, you can read this blog entry.
Answer: This is indeed a very strange problem. disabling Appstream repository helped for me, but I still don't quite understand what happened:
dnf --disablerepo=AppStream install docker-ce


Sending smtp email using mail()

Question: I have installed and configured https://www.drupal.org/project/smtp module
sending test email works fine, but when sending email with code nothing is sent and also no log in drupal (I have enabled debugging)
<code>    $ownerEmail = 'firstname.lastname@example.com';
    $subject = 'update';
    $msg = 'You case has been updates';
    mail($ownerEmail,$subject,$msg);
</code>
Answer: mail() is a PHP function, that will never use SMTP.
You need to use the drupal mail manager and its mail function. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Mail%21MailManager.php/function/MailManager%3A%3Amail/8.4.x and the example code ther.
Comment: According to the module mentioned in the question, it bypass the mail() and use smtp!
Comment: *If* you use the actual drupal mail API yes. It can't bypass anything if you call mail() yourself, that's not possible.

Sending smtp email using mail()


Is the number $0.1234567891011121314\ldots$ a rational or irrational number?

Question:
Is the number $0.1234567891011121314\ldots$ a rational or irrational number?

The number has a very clear pattern but however in order for the number to be a rational number it would have to be written as a/b.  The normal tricks of writing it as an equation and solving
$3.3333333... = x \\
10*3.333333 = 10x\\
33.333333 = 10x\\
30 + x = 10x\\
30=9x\\
x=30/9 \\= 10/3$
does not seem to work here
Comment: If it were rational, then it would eventually repeat.  Since it does not repeat, it is irrational.
Comment: It's not hard to show that if $x$ is rational, its pattern of decimal digits must eventually hit a **repeating** pattern. Your number has a clear pattern. Does it ever start repeating?
Comment: Some number theory books have dealt with this.  Just search on the web
Comment: Clearly, this has the sequence $12$ somewhere in its decimal expansion. It also has $112$ somewhere, and it has $1112$ somewhere, and it has $11112$ somewhere… Can you see why no rational number can have this property?
Comment: In fact, can you prove that, if $\mathbf a$ is _any_ sequence of digits (for example, $\mathbf a=13427$), then $\mathbb a$ appears somewhere in the decimal expansion of your number?
Comment: I voted to reopen this question by mistake. I will vote to close (as duplicate) if it gets reopened.
Answer: The Champernowne constant
$$C = 0.12345678910111213141516\dots$$
is a transcendental real number, so it is also irrational.
Answer: This is the Champernowne constant in base 10, which is in fact transcendental.
In order to be capable to write it as a fraction, you would need to have a repeating block of digits. Evidently, there does not exist such a repeating block, and thus it is irrational.


Elastic Scattering angle

Question: I was reading Introduction to Nuclear Physics by Krane and stumbled on the following (page 47):
In Elastic scattering, the initial electron wave function is of the form $e^{i k_i r}$ (free particle of momentum $p_i = \hbar k_i$). The scattered electron can also be regarded as a free particle of momentum $p_f = \hbar k_f$ and wave function $e^{i k_f r}$.
The interaction $V(r)$ converts the initial wave into the scattered wave; the probability for the transition will be proportional to the square of the following quantity:
$$F(q) = \int V(r) e^{iqr}dv$$
Plugging both Coulomb's potential and charge-per-unit-volume into $F(q)$:
$$F(q) = \int  e^{iqr'} \rho(r') dv'$$
Normalizing and knowing that $\rho(r')$ just depends on $r'$ (and not on $\theta'$ nor $\phi'$) we get:
$$F(q) = \frac{4\pi}{q}\int  r' sin (qr') \rho(r') dr'$$
Where $q = k_i - k_f$. The scattering is elastic, so momentum is conserved ($p_i = p_f$) and $q$ is merely a function of the scattering angle $\alpha$ between $p_i$ and $p_f$.
Now a bit of vector manipulation shows:
$$q = \frac{2p}{\hbar}sin(\frac{\alpha}{2})$$
I do not know how to get the last expression
Answer: Just draw a diagram of two vectors of length $p$ with angle $\alpha$ between them, and find the difference of the vectors.

Elastic Scattering angle


how to add array of HKQuantityType for health kit authorization

Question: How can I add a second HKQuantityType to my health kit authorization?
I would like to add both the heart rate and the energy burned, as the array of QuantityTypes. When I add both of these types in the line ' let dataTypes = Set(arrayLiteral: quantityTypes)' instead of quantity type, as an array, I am getting an error "cannot convert value of HKQuantityType to expected argument type []
I am a beginner, I think I am not formatting the array correctly.
<code>  guard let heartRateQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned) else {
        // displayNotAllowed()
        return
    }

    guard let calorieQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned) else {
       // displayNotAllowed()
        return
    }

    let quantityTypes = [calorieQuantityType, heartRateQuantityType]
    let dataTypes = Set(arrayLiteral: quantityTypes)
    healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypes) { (success, error) -> Void in
        if success == false {
            //    self.displayNotAllowed()
        }
    }
</code>
Answer: you are setting the array to a Set then requesting authorisation. Instead add calorieQuantityType and heartRateQuantityType to the SET directly
<code>//delete this let quantityTypes = [calorieQuantityType, heartRateQuantityType]
let dataTypes = Set([calorieQuantityType, heartRateQuantityType])
healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypes) { (success, error) -> Void in
    if success == false {
        //    self.displayNotAllowed()
    }
}
</code>