What will happen to Linux pipe() if one end closes before other

Question: I doing Inter process communication via pipe() syscall. The child writes to one end and parent is supposed to read other end of pipe.
The parent before starting to read, waitpid() for the child to finish completion. If child exited with non-zero return value -- then it indicates that child had errors. So parent simply closes the pipe descriptor and moves on without reading.
Do u think this will work in case of successful completion of child. The parent is effectively reaping the child before reading the pipe? If yes, then what will happen to data that is in transit? The OS will take care of data safely reaching the parent end?
Answer: Parent process opens a pipe. Two pointers in the PDT will point to the pipe. One to the writing and one to the reading.
Whenever a child process is created using fork, the PDT is duplicated. Hence, the child process will have its own pointers in PDT pointing to the PIPE.
At first, the pipe is empty, if parent process tries to read, it will block.
And you will never create a child process. This will end up in a deadlock.
If you close the writing end before reading, you won't have deadlock, but then the child process won't be able to write to the pipe (read above why).
So this should be your flow:
<code>1. Parent process creates pipe
2. fork()
3. in parent process you close the writing end
4. in child process you close the reading end
5. read/write to pipe.
</code>


View Title does not filter correctly by userid

Question: I'm very new to Drupal and trying to learn how to create a view that is filtered by userid, then by whether or not it's been published. I've created a content type of "Lists" and have a link on the home page called "My Lists." When the user clicks the link, it should open a view (and I have it set up as a page) and the title of the "page" should be "My Lists" and show each set of lists the user has. I.e., the user could have a list for their favorite movies, and another for their favorite books. Both lists should be shown UNDER the title of "My Lists" and the user would then click on which list they want to view or update.
What is happening though, is that somehow I got the Title "Booklists for " & "User" name in the title so it shows up as the main title for ALL lists instead of the correct title of "My Lists." I've gone to my Administration menu: Home » Administration » Structure » Views and under Views I have it set up as a Page. The Display name: Page - My Lists. The Title = Title: View My Lists. Now, when I scroll all the way to the bottom of the View My Lists (Content) it has a section for the Title with a little gear wheel icon that you're supposed to click on to change the Title. I've done that and the Page - My Lists: The title of this view dialog box comes up. I've changed the title in that section to "View My Lists" and set it to save for all displays. Then , it goes back to the Title and in the box showing for the title (that I just changed) it STILL shows "Booklist for Ayliea" when it SHOULD say "View My Lists."
It isn't changing the title.
Comment: Where did you set "Booklists for " & "User" name? Is it the title of a piece of content? Did you set the path settings to your menu item?
Comment: I set the booklist & username here: Home » Administration » Structure » Views at the bottom of the page for this there is a place to set the title and I tried to set it to "My Lists" but instead of displaying that in the title for the "page" View, it displays the previous "Booklist" for the userid. I never actually set any code. That's why I'm confused. If I did set it - I sure can't find where I set it now! I've been all through the Veiw properties and can not find any other place where the title for the View "Page" is set.
Answer: Ok, i guess this is difficult to solve from here. First you should check the following settings in your view.

Display name (how your Page-View is named, for administrative purposes, will not affect the frontend)
Title (this is the name of your view at the frontend, it can be overridden with contextual filters)
Path (this is the URL of your view)
This is the Title of your menu-item.

If this is all in order, you probably have overriden your view-title with a contextual filter.
Check these settings:
Comment: Thanks Volker. In the "Configure contextual filter: Content: Author uid", I have that set to "All Displays" - so if I'm understanding this correctly (and I definitely may not be understanding it!) this should NOT over-ride what the Title is set to. I have the section for "When the filter value is NOT in the URL" I have that set to "Provide default value" and "User ID from logged in user" So it should NOT be showing "Book Lists" on any one else's Lists view - only if the user has created on for themselves. I'm very confused. I am so new to using Drupal. Are there any tutorials for this?


activar as borders quando o checkbox esta activo

Question: Estou a tentar activar as bordas de uma caixa quando o checkbox é selecionado mas não está a funcionar.

.radio input[type="radio"]:checked+.border {
  border: 3px solid #f70024 !important;
}

    <input id="Vodafone" name="73_answer" type="radio" value="Vodafone">
    Stack Overflow em Português

Comment: Por favor, traduza sua pergunta, este é o Stackoverflow em **português**.
Comment: peço desculpa mas tinha ideia que estava na versão inglesa, de qualquer forma já traduzi.
Comment: ativar as bordas de que caixa?
Answer:

.border {
    display:block;
    width:200px;
    height:100px;
    background-color:grey;
    position: relative;
}
label {
    width: 100%;
    height: 100%;
    display: block;
}
img{
  margin-left: 20px;
}

input[type="radio"] {
    position: absolute;
}

input[type="radio"]:checked + label {
    border: red 1px solid;
}

        <input id="vodafone" name="radio-group1" type="radio" />

Answer: Compatibilidade: Google Chrome, Safari, Microsoft Edge.
CSS

input[type="radio"] {
  height: 1.2em;
  width: 1.2em;
  vertical-align: middle;
  margin: 0 0.4em 0.4em 0;
  border: 1px solid rgba(0, 0, 0, 0.3);
  -webkit-appearance: none;
  -webkit-transition: box-shadow 200ms;
}

input[type="radio"] {
  -webkit-border-radius:100%;
   border-radius:100%;
}

/* input checked */
input[type="radio"]:checked {
  border-color:#f70024;
  border-width:3px;
}

input[type="radio"]:checked:before {
  display: block;
  height: 0.3em;
  width: 0.3em;
  position: relative;
  left: 0.2em;
  top: 0.2em;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 100%;
  content: '';
}

    <input id="Vodafone" name="73_answer" type="radio" value="Vodafone">


Binary classification with imbalanced classes

Question: I have a manufacture dataset of 65 million rows corresponding to 65 millions distinct items.
Out of those 65 millions, I have 60,000 of them that failed a certain test, thus I have very imbalanced classes.
I have about 200 to 300 variables/features that describe them that are both categorical (2 levels or more) and numerical.
So

y = failed items = 1 or 0 (binary)
X = $X_1$ ... $X_{300}$ (categorical and numeric).

What is the proper methodology or model to use to root cause the important variables that contribute to the failed items? In other words, how to I identify the top variables that may be responsible for the failure?
Answer: Logistic regression would be an easy way of doing this. With 60'000 events out of 65'000'000 measurements, you have abundant data for the 300 predictors. However, datasets this large always make me wonder whether all units (the rows) are independent. Without more details about your data I dare not make assumptions about this.
Additionally, if you are interested in seeing which of your variables has the largest effect size, you might want to standardize the predictor variables and compare the effect per standard deviation.
Answer: Either way you should transform your categorical variables into dummy ones(and consider multicollinearity).
I agree with previous answer observation on possible non-independence between samples(items). If you have a reason to believe this is the case, many methods wont apply.
If you think that such issue does not exist i would go with a simple Chi-Squared test to examine each variable separately, and a logistic regression for cross variables effects.
Answer: You do not have to use all of the 65 million data points. You can take a sample, and apply a set of your favorite tools and then see if the model generalizes to dropped data. This increases your options for the method a lot.
MCA-to normalize the data. https://en.wikipedia.org/wiki/Multiple_correspondence_analysis It's like PCA, but with nominal variables.
Failing is seldom always the same. You may want to look if there is many clusters within those 60,000 failures.


Difference between cross-validation and back propagation

Question: sorry if this is a dumb question. I want to know what the difference is? Mainly what how they're objectives differ from each other?
I know that in cross validation you divide the training set into equal parts and use one as a test set.
Back propagation means that the output is sent in reverse of sorts to recalculate the weights of the neural network.
But wouldn't they achieve the same thing? Is it that cross-validation deals with the actual output against future data, while back propagation is for weight optimization?
Answer: Cross validation implies that the data is compared with a subset of the data (or, less frequently, an external data source). In this regard, it is a "replication" within the data, but with more room for uncertainty. The original idea is to test for consistency - does the inference from the data hold also for smaller parts? In machine learning, the result is improved accuracy.
Back propagation is originally a phenomenon observed in real neurons, due to the mechanics of the axon membrane. However, it has a very specific meaning in computational neuroscience:

The procedure repeatedly adjusts the weights of the connections in the network so as to minimize a measure of the difference between the actual output vector of the net and the desired output vector. As a result of the weight adjustments, internal 'hidden' units which are not part of the input or output come to represent important features of the task domain, and the regularities in the task are captured by the interactions of these units.
Rumelhart, Hinton & Williams (1986). [Abstract] Learning representations by back-propagating errors, Nature, 323, 533-536. doi: 10.1038/323533a0 http://www.nature.com/nature/journal/v323/n6088/abs/323533a0.html
Answer:
Is it that cross-validation deals with the actual output against future data, while back propagation is for weight optimization?

Yes, cross validation is meant to assess if your model performs well on data that was not used to build it.
Backpropagation in neural networks is an iterative method by which you train/optimize weights to improve classification or regression accuracy.
Answer: This is not a dumb question, and a good question to ask.
Neural network learns from the data that is provided while the training is happening. A portion of data is not used in the training process and kept for the later stage called the validation/test stage. The idea behind is that, normally in the neural network, a complete learning process would include a feed forward and eventually a backword propagation, where the neural network validates if learning is done right and if not it adjusts the weights accordingly. After this complete cycle, the weights are ready for the prediction and the final output from the model. In validation phase, the actual trained model is tested and validated on the trained model to see if the model really learned well. Since the validation data is unseen by the neural network model and hence the hypothesis should output a minimized error. In this scenario we can call the model is near to perfect model and we have verified that with the unseen data.
Now a point to be noted is, there is no adjustment of the weights in this later process and no backward prop. So we can also call it as a half cycle of neural network learning process. And hence the term Backward Propagation vs Cross Validation.  Hope it helps, let me know if any question.


Significance test for the difference of two correlation coefficients

Question: Okay, I have two different data sets, A and B, both of which correspond to a third data set, C.  I have run least-squares regression on both A with C and B with C.  The correlation coefficient of A with C is 72.9%, compared to 66.5% for B with C.  How do I know or how do I test that that 6.5% difference is significant?
Comment: If I type  into Google, the first link is: http://www.quantitativeskills.com/sisa/statistics/corrhlp.htm

Which provides a link to a web page that does the calculation for you.

The references at the bottom of the page provide the formulas that are used (and I imagine that some of the other links from that search will give you the formulas too.)
Answer: Correlation coefficients aren't expressed in percentages, except maybe when squared to represent a shared percentage of variance. It also sounds as though you're referring to three variables within one dataset. If so, you're looking to test the difference of dependent correlations. Jeromy Anglim's blog has some useful links on this. Steiger's Z-test is described in Cal Garbin's "Bivariate Correlation Comparisons (PDF), which I'll paraphrase as a four-step calculation:
$$rm^2=\frac{\big(r_{AC}^2+r_{BC}^2\big)}{2}\\f=\frac{1-r_{AB}}{2(1-rm^2)}\\h=\frac{1-(f\cdot rm^2)}{1-rm^2}\\Z_\text{difference}=(Z_{AC}-Z_{BC})\cdot\frac{\sqrt{N-3}}{\sqrt{2(1-r_{AB})h}}$$
You can find the p value of Zdifference very easily – it's from the z distribution!
If all this is a pain (it is), you can use the paired.r function in the psych package in r as described on another of Jeromy's blog posts (linked in the previous). All you'll need are the three bivariate correlations and the total number of cases (trios of observations for each variable).
Comment: Additionally, if your data sets are not normally distributed, then a bootstrap method may be more robust than a correction based simply on the correlation between A and B and the number of points. See [Wilcox 2009](http://www.tandfonline.com/doi/abs/10.1080/03610910903289151).


Is this construction already a contradiction

Question: Let's say we have $\ell^p$ for $p>2$ and $\ell^2 \subsetneq \ell^p$. Let $U$ be a closed subspace of $\ell^2$. Is it possible that $U$ is isomorphic to $\ell^p$ as a Banach space?- I hardly think so. I already know that if $U$ was a closed subspace of $\ell^p$ it cannot be isomorphic to $\ell^2$ by Pitt's theorem, but this one looks even easier, but I cannot prove it though.
Comment: It follows from a more general version of Pitt's Theorem, c.f. Kalton and Albiac's text [page 32](http://books.google.com/books?id=FkjCulO5xg0C&pg=PA32&source=gbs_toc_r&cad=3#v=onepage&q&f=false), that no infinite dimensional subspace of $\ell_p$ is isomorphic to a subspace of $\ell_q$ if $p\ne q$, $1\le p,q<\infty$.
Comment: If you have an isomorphism from $U$ to a subspace of $\ell_p$, its inverse is a bounded operator from a closed subspace of $\ell_p$ to $\ell_2$.
Comment: @DavidMitra but in your theorem they look at closed subspaces of $\ell^p$ and not of $\ell^2$. Apparently, it is the other way around.
Answer: Any bounded linear operator from $l^2$ to $l^p$, is compact, and thus cannot be an isomorphism, so no isomorphism can exist between them. So they cannot be Isomorphic.
Let us try to make one, let $L:U\to l^p$ defined by $L_x(y)=\sum_nx_ny_n$, for $x\in U,y\in l^p$, here $L_x(y)=\langle x,y\rangle_{l^2}$, thus $|L_x(y)|=|\langle x,y\rangle_{l^2}|\leq\|x\|_{l^2}\|y\|_{l^p}$, since $x$ is fixed for each $L_x$, we see that the operator is bounded, and takes values in $\mathbb{R}$ (or $\mathbb{C}$), which is finite dimensional, so the operator is of finite rank and thus is compact.
Comment: my question was not whether $\ell^2$ and $\ell^p$ are isomorphic. It is whether $\ell^p$ and a subspace of $\ell^2$ can be isomorphic.
Comment: Yep, edited it now
Comment: how do you know that a linear operator needs to have exactly this form?
Comment: reisz representation theorem
Comment: this is for hilbert spaces, not for $\ell^p$.
Comment: also, basically this holds and says that $l^2$ is not isomorphic to  $l^p$, and since $l^2\subsetneq l^p$, it holds for the smaller subset $U$.
Comment: I know, but since we are going from $l^2$, which is a hilbert space, we can use it.
Comment: Riesz representation theorem says $\ell^2 $' is isometrically isomorphic to $\ell^2$. How do we get from this to your map?
Comment: sorry,  your tex went wrong above
Comment: The formal identity from $\ell_2$ to $\ell_3$ is bounded but not compact.
Comment: it also states that a for all elements $x\in H$, $H$ a hilbert space, $x$ induces a linear functional $L_x(y)=\langle x,y\rangle$
Comment: @DavidMitra the identity does not have a finite dimensional range, which is why it is not compact.
Comment: My comment was with regards to your statement "Any bounded linear operator from $\ell^2$ to $\ell^p$, is compact". This is false for $p>2$.
Comment: you are correct, sorry, it holds from $l^p$ to $l^2$.


Knock-on vs batting the ball down

Question: I recently saw a game where a player on the defense knocked down a pass. He was given a yellow card and sent to the sin bin. It looked like the referee said the word 'cynical'. Is there a difference between a knock-on and deliberately knocking the ball down (which is what it appeared happened)? Why does this behavior warrant a yellow card?
Answer: A deliberate knock on is a penalty as opposed to an accidental knock on that results in a scrum. In the case of a defender batting down a pass, the referee has to judge whether they think the defender was actually trying to catch (intercept) the pass or just trying to knock it down to prevent the pass from being completed. The later is a penalty, you have to be trying to catch and control the ball.
As for the yellow card, if this occurred near the defenders try line, or if there was a good chance of a try being scored had the pass been completed (i.e. was going to a winger with no more defenders on the outside) then this constitutes what is sometimes called a 'professional foul'. This is grounds for a yellow card. Essentially if the referee thinks a player deliberately incurs a penalty in order to illegally stop a play that has a good chance of leading to a try a yellow card should be given. This is more typically given for infringements in the ruck, such as lying over the ball to prevent the attacking team from retrieving it, but other circumstances such as the one you describe also fit the description of a professional foul.
The terminology of 'cynical' I haven't heard before, but it is referring to the same concept.
Comment: Cynical sounds plausible as it does hold the right sort of meaning for this context, it's probably more likely than 'sinnable'. The term 'sin bin' is used in Rugby League but not Rugby Union.
Comment: It sounded like he said cynical, although thinking about it now - could it be possible he said sinnable, meaning he was about to send the player to the sin bin? Either way, thanks for the clarification :)
Comment: 'Cynical' is the likely word used.  I've heard cynical foul be used by referees and commentators in Rugby for a professional foul where the player has judged risking a yellow to prevent a likely score to be the best course of action, even against the spirit of the game. +1 for the answer - referees will often award yellow cards for professional fouls in try-scoring situations.
Answer: To extend on the previous answer, a professional foul (i.e. intentionally breaking the rules) should always generate a penalty. So deliberatly knocking on the ball is a professional foul. Yellow cards can also be given for intentionally pulling down a maul, infiringements at the breakdown and others.
As @Bogdanovist mentioned in his answer, a yellow card will be given if the penalty prevented a try. If it was a certain try (no doubt in the referee's mind that it would have been a try) then a penalty try can also be awarded.
Answer: In football, a cynical foul is said when a defending player sticks a leg out intentionally or pulls on an attacker's shirt to prevent him running through on goal. I suppose in terms of rugby, it means he cynically knocked the ball on with the full intention of committing the infringement, knowing full well he was preventing a try. I suppose in both sports, any foul committed intentionally could be classed as being cynical.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Knock-on vs batting the ball down


How to "draw" a ROC curve

Question: I have read this question but it doesn't have any well-explained answer for this case: I understand the ROC curve in overall, but I'm looking for a step-to-step explanation in order to understand how the curve changes when one true-positive becomes false-positive (and so on). For example, how can I draw a ROC curve with this set?. Does the score means the "certainty" for the value given? (for example: for the id == A the is a 0.03 of certainty that the value is active/decoy == a?)
id  score   active/decoy
A   0.03    a
B   0.08    a
C   0.10    d
C   0.11    a
D   0.22    d
E   0.32    a
F   0.35    a
G   0.43    a
H   0.57    a
I   0.61    d
J   0.68    a

Comment: Start with a cutoff of 0.001. If the score is above the cutoff, mark is "d". Otherwise, mark it "a". Determine the sensitivity and 1-specificity. Do it again for a cutoff of 0.002. Do it again for a cutoff...
Comment: Did you read this question? https://stats.stackexchange.com/questions/145566/how-to-calculate-area-under-the-curve-auc-or-the-c-statistic-by-hand Can you be more specific about which part you do not understand?
Answer: Here is a general algorithm I have used in the past to draw ROC

Sort the data by score from lowest to highest
Choose lowest score as the cut-point
Calculate sensitivity and specificity using the cut-point from step 2. Save sensitivity and 1-specificity
Repeat steps 2 and 3 for each unique score from lowest to highest
Create a step plot where the x-axis is 1-specificity and the y-axis is sensitivity

I would recommend re-coding active/decoy as 0/1 for the algorithm

How to "draw" a ROC curve


How do I modify objects within objects using jq while keeping all other objects unchanged?

Question: I have a json object with a collection of additional objects.
Using jq I need to be able to modify some of the objects while keeping the others unchanged.
I keep running into issues where I can get the change, but then all the other objects disappear. Or I make the change but it impacts every other object.
Here is a sample json
{
  "AAAA": {
    "VALUES": {
      "val_1": {
        "key": "A_KEY1"
      },
      "val_2": {
        "key": "A_KEY2"
      }
    }
  },
  "BBBB": {
    "VALUES": {
      "val_a": {
        "key": "KEY1",
        "old": [ 0, 1 ]
      },
      "val_b": {
        "key": "KEY2",
        "old": [ 2, 3 ]
      }
    }
  }
}

What I am looking to get is no change to the AAAA object, however for each value in BBBB.VALUES I want to take the second value from the old array and create a new key value say "new"
{
  "AAAA": {
    "VALUES": {
      "val_1": {
        "key": "A_KEY1"
      },
      "val_2": {
        "key": "A_KEY2"
      }
    }
  },
  "BBBB": {
    "VALUES": {
      "val_a": {
        "key": "KEY1",
        "old": [ 0, 1 ],
        "new": 1
      },
      "val_b": {
        "key": "KEY2",
        "old": [ 2, 3 ],
        "new": 3
      }
    }
  }
}

The array is guaranteed to be two elements long, the array does not need to be modified.
I've tried many incantations of jq and just can't seem to get it to work.
Thanks
Answer: If one understands with_entries/1, an easy-to-read solution is possible:
.BBBB.VALUES
|= with_entries( .value.new = .value.old[1] ) )

Or more briefly:
.BBBB.VALUES
|= with_entries( .value |= (.new = .old[1] ) )

Answer: You can use [ keys[] ] to iterate over the keys under BBBB.VALUES :
jq '(.BBBB.VALUES | . [ keys[] ]) |= .+  { new: .old[1] }' data.json

Answer: Here is a solution which uses map_values
.BBBB.VALUES |= map_values(.new = .old[1])


How many $3$-digit numbers can be formed using the digits $ 2,3,4,5,6,8 $ such that the number contains the digits $5$ and repetitions are allowed?

Question: The solution I have is by counting the complement which gives an answer of $91$. But I think that it should be solved as follows-
Let the $3$-digit number be denoted by $3$ boxes. We can put the digit $5$ in one of the three boxes and we can put fill remaining two boxes with $6$-digits. Hence answer is $6\cdot 6\cdot 3= 108$. Help!
Comment: The second method multiply counts those with more than one five.
Answer: There is a single number with three $5$, there are $3\times 5^2$ numbers with a single $5$, and $3\times 5$ numbers with two $5$. It makes $91$ numbers.
Comment: +1 why the downvote ?
Answer: You are overcounting.
Do not include the permutations of $5$s among themselves. Hence, divide into cases and solve.
The number of ways in which 5 can be filled in the three places is $3$.
For one $5$:
$3\times 5\times 5= 75$ //No repetition problems here.
For two $5$s :
$\dbinom32 \times 5 = 15$
For all $5$s :
Clearly there's only 1 possibility: $555$.
Thus, the required answer is $75+15+1= 91$
Edit:
Numbers over-counted by you:
$ 1)255$
$2)552$
$3)525$
$4)355$
$5)553$
$6)535$
$7)455$
$8)554$
$9)545$
$10)655$
$11)556$
$12)565$
$13)855$
$14)558$
$15)585$
$16)555 $
$17)555$
Hence,you get a difference of $108 -91= 17$ in your answer.
Comment: Thank you! By the way if you can explicitly state what all combinations I overcounted, it would be more helpful.
Comment: @Combinatorics Edited.
Answer: The total numbers that can be formed using these $6$ digits is $6^3$. We find the number of numbers in which there is no $5$. Therefore numbers without the digit $ 5$ is $5^3$. Therefore the numbers with at least one $5$ in the number is $6^3-5^3=91$
Hence answer is $91$
Or you can do it the other way using cases:
1) Number contains only one $5$ and all letters are different:
Number of such numbers = $^5C_2. 3!=60$
2) Numbers with only one $5$ and other letters alike:
Number of such numbers=$^5C_1.\frac {3!}{2!}=15$
3)Numbers with two $5's$ and one other number:
Number of such numbers=$^5C_1.\frac {3!}{2!}=15$
4)Numbers with three $5's= 1$
Hence the total number of numbers satisfying the given condition =$60+15+15+1=91$.
Answer: Take all the possible numbers with $5$
then substract all the numbers without $ 5$
Result: $6^3-5^3=91$
Comment: good one @Isham +1


passing a utf8 encoded string to web service

Question: Can I pass a UTF8 encoded string to a web service?
UPDATED:
Function EncodeToUTF(ByVal toEncode As String) As String
    Dim utf8 As New UTF8Encoding()

    Dim encodedBytes As Byte() = utf8.GetBytes(toEncode)
    Dim returnValue As String = utf8.GetString(encodedBytes)
    returnValue = HttpUtility.UrlEncode(returnValue)
    Return returnValue
End Function

And then decode this on the web server?  The issue is that the XML Web Service parser is striping out CRs from my string.
Then on server side to decode:
Function DecodeFromUTF8(ByVal encodedData As String) As String
    Dim utf8 As New UTF8Encoding()

    Dim returnValue As String = HttpUtility.UrlDecode(encodedData)
    Dim encodedDataAsBytes As Byte() = utf8.GetBytes(returnValue)

    returnValue = utf8.GetString(encodedDataAsBytes)

    Return returnValue
End Function

The returnValue here is still encoded.
Comment: Because you have not decoded it.
Answer: You need to URL encode your string/message. Messages must be URL Encoded before being sent to a webservice as they contain special characters.
Function EncodeToUTF(ByVal toEncode As String) As String
    Dim utf8 As New UTF8Encoding()

    Dim encodedBytes As Byte() = utf8.GetBytes(toEncode)
    Dim returnValue As String = utf8.GetString(encodedBytes)

    '' URL encode your string before pushing it to a web service
    returnValue = HttpUtility.UrlEncode(returnValue)

    Return returnValue
End Function

And, on the other server side, use the following to decode your encoded string:
Dim decodedUrl As String = HttpUtility.UrlDecode(encodedUrl)

Hopefully, this will solve your issue.
Comment: Ok then I guess that I need to do some thing like that on the web server to UrlDecode?
Comment: Didn't work. I'll update the OP with server side decode shortly. UPDATED OP.


The right way to set up master and slave nameservers

Question: I'm wondering about the proper way to set up a master and slave DNS.
I read somewhere that your master DNS server should not have an NS record in your zone file - that's sort of secret and then your slave nameservers have NS records and are listed in the whois record.
Can someone confirm the right way to set up the zone file and whois for master and slave nameservers?
This came up because my slave nameserver complains that my master nameserver is not authority for a domain it definitely is master for a domain where the slave nameserver has an NS record, but it doesn't complain for a domain which does not have an NS record for the slave.
Answer: It's not uncommon for large operators to run a "hidden master" configuration.  This allows them to perform all zone maintenance on that hidden server without the risk of it being inundated by client queries.
The complaints you're seeing from the slave servers should just be warnings, and can be ignored.  If however the configuration isn't actually working, please update your question with more detail.
Comment: It sounds like there isn't one way to set this up.  Just to confirm - for a smaller operation, is it fine for your primary and secondary nameservers to be listed in the NS records?  And would it be okay to have your secondary running on a cloud server like EC2 or DigitalOcean droplet to ensure access to name resolution even when your primary network is unreachable?  I will submit warnings as a new question since it seems to be unrelated to this general planning question.
Answer: I do it another way, in SOA my master is ns1 (slave zone), I have 3 local slaves ns2, ns3, and ns4, and then 2 external nameservers.
All DNS is done on a standalone machine, but is configured to send-notifies to the local master, which is set to 'also notify' the local and remove slaves, this way they updates can only come from 1 IP Address in my local IP Space.
I also layer added TSIG as my external slaves are using public internet to communicate.
This is all personal preference, but the thing to remember is you do not want your published Name servers to do any sort of updates from unsecured networks, only those you maintain, trust and secure, and then layer application security (TSIG) on top.
Also, I run Bind9, but also run DBJDNS (using scripts to retransfer from master on update) which allows me to use a simple, webui and still have a secure slave backend.
Comment: So is it a bad idea to run a secondary nameserver on a cloud server like EC2 or a DigitalOcean Droplet?
Comment: As long as your serial numbers and SOA information matches consistently, I would recommend using either/both.


Make Windows file shares default to domain authentication on the server side?

Question: We are retiring an old domain controller that some genius has set a file share up on. This file share is used heavily by devices that aren't domain joined.
As the share resides on the DC itself, there's no local user database so the clients have been successfully authenticating with just a domain username and password.
The problem arises when we attempt to move said share to a non-DC. If the clients use just their username, authentication will fail. They need to use 'domain\user' or 'user@domain' for auth to succeed.
I assume it is trying to authenticate against the local users on the server.
If this is the case can anyone think of a way to set the implied prefix/UPN on the server side to work around this issue?
Thank you!
Answer: Common things to check that could cause issues would be:

Credential Vault or Credential Manager for stored logins
Matching local usernames (Administrator) between non-domain clients and the domain servers.


Is the hypercube graph $Q_n$ k-factorable for k=modn?

Question: Definition of k-factorable graph: https://en.wikipedia.org/wiki/Graph_factorization
I have proved that a hypercube of any dimension has a perfect matching, thus also a 1-factorization.
Can it be proven that for any n, the graph $Q_n$ has a k-factorization if and only if k divides n?
Answer: Yes. A $k$-factorization of a graph is a partition of the edge set of the graph into spanning $k$-regular subgraphs.  If the edge set of $Q_n$ is the disjoint union of some number of $k$-regular spanning subgraphs, then clearly $k$ divides the degree of a vertex (which is $n$).
To prove the converse, suppose $k$ divides $n$.  Because $Q_n$ is an $n$-regular bipartite graph, by a consequence of Hall's matching theorem, the edge set of $Q_n$ can be partitioned into $n$ perfect matchings.  (In other words, the edge-coloring number, also known as chromatic index, of $Q_n$ is exactly $n$.)  Thus, the edge set of $Q_n$ can be partitioned into $n$ perfect matchings (i.e. $n$ 1-factors). The union of any $k$ of the $n$ 1-factors gives a $k$-factor.  Thus, the $n$ 1-factors of $Q_n$ give a partition of the edge set of $Q_n$ into $n/k$ $k$-factors. Hence, $Q_n$ is $k$-factorizable if $k$ divides $n$.
Comment: Suppose the edge set $E=E(Q_n)$ is the disjoint union of edge sets $E_1,E_2,\ldots,E_r$, where the subgraph $E_i$ is a $k$-regular spanning subgraph.  A vertex $u \in V(Q_n)$ has $n$ edges incident to it.  Of these $n$ edges, $k$ edges are in $E_1$, another $k$ edges are in $E_2$, and so on.  Hence, $n=kr$, which implies that $k$ divides $n$.
Comment: Can you please expand a little on how k divides the degree of a vertex (or all vertices?)?


Understanding output of powerTransform

Question: In the car package, we have the function powerTransform which transforms variables in a regression equation to make the residuals in the transformed equation as normal as possible. I am confused about what this transformation is and further in the following example:
# Box Cox Method, univariate
summary(p1 <- powerTransform(cycles ~ len + amp + load, Wool))

# fit linear model with transformed response:
coef(p1, round=TRUE)
summary(m1 <- lm(bcPower(cycles, p1$roundlam) ~ len + amp + load, Wool))

What I am confused about is what exactly the model p1 is. Is it simply the linear model without a transformation, then it finds the optimal parameter, we then use that to specify m1? So what is the regression equation for p1, m1??
Answer: The powerTransform() function in the car package determines the optimal power at which you should raise the outcome variable (in this case, cycles) prior to including it in a linear regression model. The optimal power is denoted by lambda, so outcome^lambda becomes the transformed outcome variable.
For your example, you can type p1$lam in the R Console and you will see that the optimal lambda is lambda =−0.05915814.
In practice, lambda is rounded before being used to transform the outcome, so that we get a nice power.
If you type p1$roundlam in the R Console, you will see that the rounded optimal value for lambda is lambda = 0.
Now that you know what optimal transformation will be used on the outcome variable cycles in the Wool data set, you can type
bcPower(Wool$cycles,p1$roundlam)
to see the values of cycles^0 (i.e., the outcome values raised to the power 0). The linear model fitted to these transformed outcome values is:
m1 <- lm( bcPower(cycles, p1$roundlam) ~ len + amp + load, data = Wool )

So the real question is: What does it mean to raise a variable to the power 0? By convention, it means that we are log transforming the variable using the natural log transformation. You can check that this is indeed the case by comparing the results of the following R commands:
bcPower(Wool$cycles,p1$roundlam)

log(Wool$cycles)

In summary, the model being fitted for m1 is simply:
m1.new <- lm( log(cycles) ~ len + amp + load, data = Wool )

You can compare summary(m1) with summary(m1.new) to convince yourself that this is indeed the case.
Comment: this answer is incorrect, we can see this by comparing:
`head(bcPower(Wool$cycles, p1$lam))` with `head(Wool$cycles^p1$lam)`, the function doesn't look for the optimal $\lambda$ to take Y to the power to, it takes the optimal lambda for $\frac{Y^\lambda -1}{\lambda}$. Compare to `head((Wool$cycles^p1$lam -1 ) / p1$lam)`.

Understanding output of powerTransform


What does it mean when the test error is nondecreasing as model complexity increases?

Question: In machine learning, I know that there is a bias-variance tradeoff. As model complexity increases, bias decreases, so the test MSE decreases. However, after some threshold, the model begins to overfit, so the model's variance increases, leading to an increase in the test MSE. Overall, the test MSE curve has a U shape.
In my case, my test MSE is increasing monotonically as the model complexity increases. What could this indicate?
Comment: As model complexity increases, bias decreases, so the _training_ MSE decreases.
Answer: Overfitting. It means that your model is not learning anything new while you are adding more complexity, that is your first model is least overfit, but even that may be bad, if your test MSE really does increase from the very start already.
There could be a number of reasons for this: 1) you built your complexity based on your training data which showed you something different than your test data, 2) your model may not be appropriate for your problem, maybe a different one would perform better, 3) your data is not good so no model will be able to learn much from it, 4) your test data is completely different from your training data, could be just random chance or maybe you divided it such (maybe unknowingly).


Is the immediate neighbourhood of an irrational number also irrational?

Question: I had this homework problem:

If $f(x)$ is continuous in $[0,1]$ and $f(x)=1$ for all rational numbers in $[0,1]$, then $f(\frac{1}{\sqrt{2}})$ is equal to $1$.

My logic for marking it false was that there are infinite irrational numbers for each rational number, so the immediate neighbourhood of an irrational number must also be irrational. Since the immediate neighbourhood is not rational, it doesn't have to necessarily be equal to 1, but the given answer was true.
My teacher said that we can't be sure if the immediate neighbourhood of $\frac{1}{\sqrt{2}}$ is irrational or rational, so $f(x)$ will be $1$ for irrational numbers as well.
Are any of us two correct?
Comment: What does it mean for a neighborhood to be "irrational"?
Comment: There is no notion of "infinitely close".  there are limits, of course, but two distinct real numbers $a,b$ can not be "infinitely close".
Comment: Welcome to MSE. What *is* "the immediate neighbourhood of $\frac1{\sqrt2}$"?
Comment: @JoséCarlosSantos I believe it's the value of $x$ infinitely close to $x$ (from both sides) but not exactly $x$
Comment: And related, there is no smallest neighborhood around a point. Any neighborhood you might look at, there are even smaller ones.
Comment: After reading the comments and the answer, I realise that we may have been twisting the meanings of some words in my classes. Feel free to edit the question with better wording if someone understands what exactly my doubt was.
Answer: Every neighborhood in $\mathbb{R}$ (at least, using the standard topology) contains infinitely many rational numbers AND infinitely many irrational numbers. There is no such thing as a "rational neighborhood" or "irrational neighborhood".
For this problem, since every neighborhood of $1/\sqrt{2}$ contains rational numbers and therefore values where $f(x) = 1$, and $f$ is continuous, it must be the case that $f(1/\sqrt{2}) = 1$ (in fact, $f(x)=1$ everywhere in the interval $[0,1]$).
Comment: Sure, there are infinite irrational numbers between any two rational numbers. And also infinite rational numbers between those two rational numbers. And infinite rational numbers between any two irrational numbers. The real numbers are not a sequence, where you can find the "next" number after another number.
Comment: But if the set of irrational numbers is larger than the set of rational numbers, then wouldn't that mean that I should find another irrational number right beside $\frac{1}{\sqrt{2}}$?
Comment: There is no number "right beside" it. If $x = \frac{1}{\sqrt{2}}$ and $y \neq x$ is any other real number at all, there are infinitely many real numbers (including rationals and irrationals) between $x$ and $y$.
Comment: By my above comment, I meant to ask: if there are infinite rational numbers between two integers, say, 1 and 2, then can we say something similar for rational numbers and irrational numbers?
Comment: Between *any two* numbers, not just between integers, there are infinitely many rational numbers and infinitely many irrationals. There are more irrationals (uncountably many) but the rationals are still "dense" on the number line, which means no matter how close you zoom in on the line you still have rationals between any two points.
Comment: 'The real numbers are not a sequence, where you can find the "next" number after another number.' Ah, after reading this I understand your answer. There is no "next" real number after/before $\frac{1}{\sqrt{2}}$ so my logic of saying that there would be infinite irrational numbers between 2 rational numbers with an "infinitely small difference" is wrong since there is no "infinitely small difference".
Comment: @DavidK What I mean in that comment was if we take the set of integers and the set of rational numbers, then between 2 adjacent elements of the set of integers, there will be infinite rational numbers. Now I understand that we can't say the same about the set of rational numbers and the set of irrational numbers since there is no such thing as an adjacent element in the set of rational numbers.
Comment: @AbhyuditSingh, Let's play a game.  We each choose a rational number bigger than $1/\sqrt 2$.  Whoever chooses the smaller number wins.  Would you like to start?


Notehead direction in keyboard style 4-part harmony

Question:
Can someone please explain to me which of the last two chords is written correctly and why? What are the rules for writing the soprano stem going up?
Comment: Note head or note stem? (Header).
Comment: both please, in my examples both are in different places
Answer: From the Music Publishers Association of the United States, Inc. pamphlet "Standard Music Notation Practice: Placement of Note Heads and Accidentals (e)."

When an interval of a second is written with opposite stems, the stems must be in alignment.

Therefore, the first version, with the soprano note on the left, is the correct way to notate a soprano up-stem when the down-stem note is a second below.
Here is an example from Chopin's Nocturne Op. 9 No. 3 (the 7th and 8th measures of the Agitato):

This notation has two benefits:

The note stems align.
The melody is seen first.

Another example comes from Rachmaninoff's Prelude Op. 23, No. 1 (mm. 1–2), the upper voice note heads are written to the left of the lower voice's:
Comment: Thank you. If you look at the first beat of each bar in your Chopin example, both stems align in the middle however, their placement is different with respect to the bass note. In the first bar the melody note lines up with the bass note while in the second  bar it is the inner voices that line up with the bass note and the melody seems displaced to the left. Why the discrepancy?
Comment: @armani I would be guessing. Seems like a good, but separate, question.
Comment: @armani Looks like it's just to save space and make the spacing between the left-hand notes be relatively consistent.  In order to line the right hand stems up with the left, they'd have to increase the spacing between those two sextuplet groups in order for the 16th note in the melody to fit clearly between them.
Comment: Darrel, with that reasoning, wouldnt the same apply to the following bar? or maybe the following bar has less notes
Answer: In SATB voice parts, your S and A voices are written correctly. T should be in the lower stave, with stalks up.  B is good.
If writing for keyboard, I'd write all the RH notes as block chords.  Only use extra 'voices' where polyphony demands it.
('Which of these'? I only see one example.)
Later:
OK, I see you've clarified your question in an edit.   As far as it goes, the first version of the final chord, with the stems in line, is correct.
But neither are optimum, either as SATB or for keyboard.

Later again - addressing your comment on 'a 3rd style'
Keyboard writing generally uses more than one voice where necessary, but ONLY where necessary.   In example A (below) a second voice IS necessary.  A and B are both acceptable (the choice might be influenced by what comes next). Where the texture doesn't demand another voice, C is correct.  D MIGHT indicate that the LH is intended to play the lower notes in the treble staff, but that isn't the case here.  So do C.
And where there's only one voice in the lower stave, it should follow the normal stalk up/down rule.
Comment: The last chord has been written twice, the second time it is different
Comment: Laurence there is a 3rd style where the melody note is different to the inner voices. This is like keyboard style except the melody stems point up regardless of there position on the stave. This style is the keyboard style I was refering to.
Comment: @armani see my extended answer above.


How to do hypothesis testing for many individual means over time?

Question: There is a data set that has yearly data for mean values of the number of ice creams eaten for 5 persons. The data set has values for 5 persons and 5 years(5x5 panel). Suppose due to some theory it is assumed that mean value for the sample should be 50 units of ice creams (null hypothesis). How to perform a hypothesis test for this sample. Please help. Thank you.
Answer: You can assume that number of icecreams eaten per person in each year follows a normal distribution such as $N(\mu_1,\sigma_1^{2})..,N(\mu_5,\sigma_5^{2})$,where $\mu_1,...,\mu_5$ and $\sigma_1^{2},...,\sigma_5^{2}$ are population means and variances respectively.Then for each of the 5 years you will get 5 samples from the normal populations.So,in this case,your required test is $H_0:\mu_1=\mu_2=...=\mu_5=50$ against $\mu_{i}$'s are not equal.
Now you draw a random sample of 5 persons for each year.Let $x_{i1},x_{i2},...,x_{i5}$ be the random sample drawn from the ith population.
By likelihood ratio test you can get the required test statistic as,
$\lambda_x(\theta)=(\frac{1}{1+\frac{SSB}{SSW}})^{\frac{n}{2}}$,$\sum n_{i}=n,i=1(1)5.$  where,
$SSB=\frac{1}{5}\sum\sum(\bar x_{i0}-\bar x_{00})^2$
$SSW=\frac{1}{5}\sum\sum(\bar x_{ij}-\bar x_{i0})^2$,$\bar x_{i0}=\frac{\sum x{ij}}{n_i}$ and $\bar x_{00}=\frac{\sum\sum x{ij}}{\sum n_i}$
As,$\lambda_{x}(\theta)$ is a decreasing function of $\frac{SSB}{SSW}$,we reject $H_0$ when $\lambda(x)<C$ i,e,. $T=\frac{MSB}{MSW}>C'$,$MSB=\frac{SSB}{5-1}$,$,MSW=\frac{SSW}{n-5}$,where $T\backsim F_{(k-1,n-k)},$under $H_0.$
Under $H_0,C'=F_{\alpha;5-1,n-5}$,$\alpha$ is the desired level of significance.
Comment: Please also suggest how to do this in R or any other software?


Operators whose spectrum has a finite number of connected component

Question: Assume that $H$ is  a  separable Hilbert space. Let $Q$ be the set of all operators$T \in B(H)$  such that  the spectrum of $T$  has  a  finite number of  connected component. Is $Q$ a subvector space of $B(H)$? What id $\bar{Q}$, the closure of $Q$? What is the closure of the span of $Q$?
Answer: Let $E=\{1,1/2,1/3,\cdots\}$ and let $\mu_{a}$ be the finite atomic meausre on $[0,1]$ that is supported on $E$ with $\mu\{1/n\}=1/n^{2}$. Let $\mu = \mu_{a}+m$ where $m$ is Lebesgue measure on $[0,1]$.
Let $X=L^{2}_{\mu}[0,1]$. Let $\chi$ be the characteristic function of $E$, and define operators $A, B \in \mathcal{L}(X)$ by
$$
                    Af = xf(x),\;\;\;   Bf =x\{1-\chi(x)\}f(x).
$$
Then $\sigma(A)=[0,1]$ and $\sigma(B)=[0,1]$, but $\sigma(A-B)=E\cup\{0\}$. So you have two operators with connected spectrum and the sum of the two has spectrum consisting of infinitely many disjoint components.
Comment: Thank you for your very interesting example. i have another question which is some how related to the above. Are there some results about the comparision of $\mu (sp(A+B))$  and $\mu (sp (A))$  and $\mu (sp (B))$  where $\mu$ is the Lebesgue  measure of real line  and $A,B$  are self adjoint operators on a Hilbert space?
Comment: @AliTaghavi : That's a fairly broad topic because the Schrodinger operators $(A+B)f=-\frac{d^{2}}{dx^{2}}f + Vf$ fall into that category, for example. Lots of things can happen in general.


Programa não compila com erros diversos

Question: O que está errado aqui? Não consigo ver o erro.
#include <stdio.h>

void Main(void)
{
    int a = 9;
    int b = 3;
    int c = 0;

    int *p = &b;
    c = a/*p;

    printf("%d \n", c);

}

Comment: @drd0sPy Então, não quer [edit] a pergunta para incluir a mensagem de erro como o hugomg sugeriu?
Comment: Nessas horas sempre ajuda mostrar qual é a mensagem de erro retornada pelo compilador.
Comment: verdade @hugomg
Answer: Há três erros:

A função principal deve chamar main  e não Main.
Esta função deve retornar um int e não void. Alguns compiladores aceitam esta forma mas isto não quer dizer que seja correto usar em C padrão.
o uso de /* é um início de comentário. Você precisa garantir que não tenha ambiguidade usando parênteses.

Código correto:
#include <stdio.h>

int main(void) {
    int a = 9;
    int b = 3;
    int *p = &b;
    int c = a / (*p);
    printf("%d \n", c);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: @axell13 editei para esclarecer este ponto
Comment: Obrigado @bigown
Comment: Não Precisa Ser `int main` No Visual C++ 2013 Roda De Boa Como `void`.
Comment: Em vez de parenteses para evitar ambiguidade, também pode usar espaço em branco (espaço em branco é barato e torna o código mais legível): `c = a / *p;`

Programa não compila com erros diversos


What happens with modules and themes when I rebuild the cache?

Question: Just for learning, this document explains me in a "ballpark" way how cache rebuild works, but I want to know more about "Updates the system with latest information about extensions (modules and themes)."
What happens with modules and themes when I rebuild the cache?
Answer: To create a page Drupal needs to make several database queries. This can slow down websites with a lot of traffic. To make websites faster Drupal stores web pages in a cache.
Before Drupal 8, the common mantra was drush cc all (i.e. drush clear-cache). Now, in Drupal 8, it's drush cache-rebuild OR drush cr.
Caching is widespread in Drupal and creates many interdependencies. Improperly or incomplete cache flushing operations can cause the site to fatal error. In order to guarantee that old data is properly flushed and the site stays up and running,  drush cache-rebuild both rebuilds or re-bootstraps the Drupal site in    addition to clearing the cache
In-short, Drush's cache-rebuild command does the following:

Clears the APC cache
Bootstraps Drupal
Calls drupal_rebuild()
Clears the Drush cache (to maintain consistency with Drupal 7's drush cache-clear command)

If you would like to dig more into this check out https://github.com/drush-ops/drush/blob/659f67712adab143a2c921f9f23828782e414e8d/commands/core/cache.drush.inc#L263 at the end of the file, look at function drush_cache_rebuild().
Thanks!


Can't v-bind a style property to a ref in vuejs 3 SFC

Question: https://vuejs.org/api/sfc-css-features.html#v-bind-in-css
Adjusting the slider should change the image opacity but it doesn't.
What am I missing?
If I use an inline style :style="'opacity:'+o" it works fine.

<template>
  Opacity : {{o}}
  <input type="range" min="0" max="1" step = "0.01" v-model="o">

</template>

SFC Playground example
Answer: This works:
  opacity: v-bind(o);

I had an extra close-parenthesis that caused the problem.


Solve the differential equation $y{''}(1+y^{'2})-3y^{'}y^{''2}=0$

Question: Solve the differential equation $y{''}(1+y^{'2})-3y^{'}y^{''2}=0$
Attempt:
$$y{''}+y^{''}y^{'2}-3y{'}y^{''2}=0\Rightarrow \frac{1+y{'^{2}}-3y^{'}y^{''}}{y{''}}=0\Rightarrow 1+y^{'2}-3y^{'}y^{''}=0$$
Substitution $y^{'}=e^t,y^{''}=e^{t}t^{'}\Rightarrow 1+e^{2t}-3e^{2t}t^{'}=0$
Is this the right approach, and if yes, how to continue?
Answer: HINT:
$$y''(x)\left(1+y'(x)^2\right)-3y'(x)y''(x)^2=0\Longleftrightarrow$$

Let $y'(x)=v(x)$ which gives $y''(x)=v'(x)$:

$$v'(x)\left(1+v(x)^2\right)-3v(x)v'(x)^2=0\Longleftrightarrow$$
$$v'(x)=0\Longleftrightarrow\space\space\vee\space\space v'(x)=\frac{v(x)^2+1}{3v(x)}\Longleftrightarrow$$
$$v(x)=\text{C}_1\Longleftrightarrow\space\space\vee\space\space \frac{3v'(x)v(x)}{v(x)^2+1}=1\Longleftrightarrow$$
$$v(x)=\text{C}_1\Longleftrightarrow\space\space\vee\space\space \int\frac{3v'(x)v(x)}{v(x)^2+1}\space\text{d}x=\int1\space\text{d}x\Longleftrightarrow$$
$$v(x)=\text{C}_1\Longleftrightarrow\space\space\vee\space\space \frac{3\ln(v(x)^2+1)}{2}=x+\text{C}_1\Longleftrightarrow$$
$$v(x)=\text{C}_1\Longleftrightarrow\space\space\vee\space\space v(x)=\pm\sqrt{e^{\frac{2(x+\text{C}_1)}{3}}-1}\Longleftrightarrow$$
$$y'(x)=\text{C}_1\Longleftrightarrow\space\space\vee\space\space y'(x)=\pm\sqrt{e^{\frac{2(x+\text{C}_1)}{3}}-1}\Longleftrightarrow$$
$$y(x)=\int\text{C}_1\space\text{d}x\space\space\vee\space\space y(x)=\int\pm\sqrt{e^{\frac{2(x+\text{C}_1)}{3}}-1}\space\text{d}x$$
Answer: At the beginning $y^{''} $ can be cancelled. $ y = C_1 x + C_2 $ is a solution. Next,
$$ \dfrac{1}{3 y^{'}} =  \dfrac{y^{''}}{1+y'^{2} }$$
Using substitution
$$ y^{'} = \tan \phi $$
greatly simplifies it to:
$$ \int dx = 3 \int\tan \phi \cdot d\phi = 3 \log \sec \phi $$
and you can continue with it.
Answer: When you divided by $y''$, you discarded the solutions with $y''=0$.
I don't immediately see how to go through with your substitution.
What I would do is to let $v=y'^2$. Then $v'=2y'y''$, and the equation becomes
$$
1+v-\frac32v'=0.
$$
This is linear and separable, so it can be done in several ways. We get
$$
v(x)=-1+e^{2x/3},
$$
or
$$
y'(x)=\sqrt{-1+e^{2x/3}}.
$$
It follows that
$$
y(x)=3\sqrt{-1+e^{2x/3}}-3\arctan\sqrt{-1+e^{2x/3}}+c, \ \ \ x\geq0.
$$
At the start we also discarded the solutions $y''=0$, so
$$
y(x)=cx+d,
$$
with no domain restriction.


Linq Sql Int null equal to null. Not returning rows

Question: I have a linq query with a where clause as below
var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
                               join pd1 in dbContext.XXXXXXXXXXX on ppatg.ScheduleID equals pd1.ScheduleID
                               where  pd1.GroupID == null
                               select
                               new
                               {
                                FinishPDI = pd1.ProductionDateID,
                                FinishingDate = pd1.WorkFlowDate,
                                ppatg.GroupName,
                                ppatg.PNTGroupID
                               });

In the database GroupID is an int that can be null. The linq query returns rows without the filtered where clause but none when I include the where clause. There are null values in the GroupId column in the database.
It is definitely this statement that produces no results. All the literature on the subject online says that this is equivalent to
pd1.GroupID is null // in sql

I am getting results that contradict this
Sql code is
 select pd1.ProductionDateID as FinishPDI, pd1.WorkflowDate as FinishingDate,GroupName ,PNTGroupId
 from XXXXXXXXXXXX
 inner join XXXXXXXXXXXX pd1 on
 XXXXXXXXXXXX.ScheduleId = pd1.ScheduleID
 where pd1.GroupID is null

Comment: Is GroupID in your Model a nullable type?
Comment: Yes, in the model GroupID is a int?
Comment: It should be int? GroupID.
Comment: Can you show sql code?
Comment: @Backs added sql code
Comment: And executing sql code directly returns correct results?
Answer: You can combine your where with the join, which should give you the expected results:
var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
                               join pd1 in dbContext.XXXXXXXXXXX.Where(p => !p.GroupId.HasValue) on ppatg.ScheduleID equals pd1.ScheduleID
                               select
                               new
                               {
                                FinishPDI = pd1.ProductionDateID,
                                FinishingDate = pd1.WorkFlowDate,
                                ppatg.GroupName,
                                ppatg.PNTGroupID
                               });


How to create a Javascript function that uses parameters and arguments to change the font size and color of an HTML tag?

Question: I created a button that uses function fontColor to activate the id= "main header". I'm trying to get the parameters of function to accept arguments to adjust the font size and color in the id="Main Header". Can I get some help with this? Thanks.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

    <button type="button" onClick="fontColor(30,"blue");" id="push">Change.</button>

 HI

Hello World

function fontColor(s, c) {
    var size = element.style.fontsize(s);
    var color = element.style.color(c);
    var result = [size, color];
    document.getElementById("Main Header").innerHTML = result;

}

Comment: You should use single quotes inside of the onclick propery. Currently it only says `onClick="fontColor(30,"`. change it to `onClick="fontColor(30,'blue');`
Comment: what is `element`  ? I mean which element ?
Comment: You have invalid HTML, `id` cannot be setted with separeted words like `Main Header` or `this one`, use as `Main_Header`
Comment: Noted, I actually realized that space yesterday. However, it still works which surprised me.
Comment: Forgot about the double quotes and single quotes. I'm a beginner at JS, so i'm constantly making rookie mistakes lol. Thanks for that correction.
Answer: Camel-case element.style.fontSize
I could be wrong but also I believe element.style.fontSize needs a string so fontColor("30px","blue")
EDIT: element is undefined and there's more errors than I previously thought. I couldn't just tell you how to fix the errors so I just rewrote your function.
A better solution would be:
function fontColor(s, c) {
  var element = document.getElementById("MainHeader"); <- should be one word
  element.style.fontSize = s;
  element.style.color = c;

}
Comment: abou camel-case, it's correct. ut the inline call to the `fontColor` function should be `onclick="fontColor('30px', 'blue')"`
Comment: Awesome, thanks! Ive been having troubles with the concept of parameters and arguments. Think I'm getting closer now. This snipped of code was about the 10th different way I tried to write it lol. That makes sense.
Answer: Just set the id to a variable, and change it from there. Also, as the other user said, fontSize should be suffixed with px
function fontColor(s, c) {
    var changing = document.getElementById("Main Header");
    changing.style.fontSize = s;
    changing.style.color = c;
}


How we show that $Z := \{(x, y, z) ∈ R^3 | x^2 + y^2 − z^2 = 0\}$ is not a manifold (even it is not a topology manifold)

Question: can anyone help me to prove that $Z := \{(x, y, z) ∈ \mathbb{R}^3 | x^2 + y^2 − z^2 = 0\}$ is not a manifold (even it is not a topology manifold)?
Comment: $R3$ should be $\mathbb{R}^3$ and $x2$, $y2$ and $z2$ should be $x^2$, $y^2$ and $z^2$?
Comment: yes, thank you!
Comment: Hint: It has peak, every other point has neighborhood homeomorphic to $\mathbb{R}^2$. But the peak doesn't. Can you show this?
Comment: @Grey Fox It is not homeomorphic to the plane. Since it can be disconnected by removing one single point.(And the plane can't)
Comment: What kind of shape is $Z$ geometrically speaking? Try to plot it if you can't picture it. Then take a guess at which point the shape behaves less nicely.
Comment: Z here is a set.
Comment: @miraunpajaro Sorry, actually I thought about the upper sheet of the cone.
Comment: @Grey Fox Then I think it could be fine
Answer: The idea for this sort of thing (where it's still low-dimensional enough) is to try and draw it, and see where the problem is on the drawing, and what that problem corresponds to. Once you see that, you can do a formal, precise argument by basing what you're looking for on the drawing (although of course the drawing itself isn't enough !)
To draw it, notice that if you fix $z$, then the "$(x,y)$-slice" is a circle of radius $\sqrt {z^2}$, so your "surface" is just a bunch of circles moving along the $z$ axis, with radius moving "linearly", so it should look something like

Now if you stare at this you'll think it looks like a manifold everywhere, except at the $z=x=y=0$ point, so that's what you have to analyse. Now what's wrong with this specific point ?
Well if you take a small ball around it and intersect it with the surface, it still looks like the surface itself (a smaller version). So the point is to see that the surface itself isn't homeomorphic to $\mathbb R^n$ for any $n$. And why is that ?
Well that's where the formal argument comes from, and now you can just pick one of the arguments that work; the one I would use is that if you take a small ball around the point, intersect it with the surface and remove the point, you get two connected components ! The only $n$ such that $\mathbb R^n$ has that property is $n=1$.
But now it's also clear that the surface is connected (if it's not clear to you, try to prove that it's path-connected), so if there was a $1$-dimensional neighbourhood around this $(0,0,0)$ point, and the surface was a manifold, then every point would have a $1$-dimensional neighbourhood. Now you can simply look at any other point and see that it actually has a $2$-dimensional neighbourhood (with the usual tricks, e.g. the differential of $x^2+y^2-z^2$ is a submersion at other points), which is a contradiction.
Or you can try to find another proof for why the neighbourhood of $(0,0,0)$ is not homeomorphic to $\mathbb R$ (there are probably many arguments)
Comment: can you explain more this sentence:  if you take a small ball around the point, intersect it with the surface and remove the point, you get two connected components !؟and do you mean by (the surface is connected)?
Comment: What part specifically is problematic ? If you take an open ball $B$ containing $(0,0,0)$, and consider $U=(B\cap S)\setminus\{(0,0,0\}$ (where $S$ is the surface) you have two disjoint opens that cover $U$ : $\{z>0\}$ and $\{z<0\}$, therefore $U$ is not connected. By "the surface is connected", I mean that $S$ is a  connected space.
Answer: Notice the following: Which are the open neighborhoods of the point (0,0,0)?
If
$A=\{(x, y, z) \in\mathbb{R}^3 | x^2 + y^2 − z^2 = 0, z>0\}$
$B=\{(x, y, z) \in\mathbb{R}^3 | x^2 + y^2 − z^2 = 0, z<0\}$
Then $Z=A\cup B\cup \{ (0,0,0)\}$
Let $B_Z$ be an open nhood of $Z$
Then $B_Z-\{(0,0,0)\}$ is disconnected.
That means that $B_Z$ can be disconnected by removing one single point. So if it isomorphic to some open set of some $\mathbb{R}^n$ is must be some interval of $\mathbb{R}$. But an interval can be disconnected by removing ANY point (at least an open one), while $B_Z$ remains connected if we remove any other point that is not the origin
Comment: what do you maen by "BZ−{(0,0,0)} is disconnected"?
Comment: I mean $B_Z\cap\{z>0\}$ and $B_Z\cap\{z<0\}$ are non-empty open disjoints sets of $B_Z-\{0,0,0\}$. Whose union is $B_Z-\{0,0,0\}$
Answer: $Z\setminus\{(0,0,0)\}$ is no longer connected. With a manifold, this can happen only if it is 1-dimensional.
But looking at a nighbourhood of $(1,0,1)$, say, $Z$ "should" be two-dimensional.


Isomorphism type of order 16 subgroup of $S_6$

Question: [This question is prompted by Robinson ex. 1.6.17 which I am self-studying.
The question is mostly about improving my style and rigour.]
I needed to find the isomorphism type of a Sylow 2 subgroup of $S_6$.
Obviously such a subgroup is of order 16 (the highest power of 2 dividing 6!)
Since all the Sylow 2 subgroups are isomorphic, I just need to pin one down, call it $S$, and investigate it.
First I looked at the representation of $S_6$ as permutations, and spotted that (some) permutations on elements 1..6 elements can be split into a direct sum of permutations on 1..4 and 5..6.  So $S_4 \times S_2$ is a subgroup of $S_6$.
Question: how to make the previous remark more rigorous/elegant?
By Sylow again, $S_4$ has a subgroup of order $8$. So there is a subgroup of order 16 within $S_4 \times S_2$.
Again, looking at $S_4$ as symmetries of 1,2,3,4 and playing around I eventually found elements $a = (1 2)$ and $b = (1 4 2 3)$ with $abab=1$, I realised that $a$ and $b$ generate $D_8$, and so $S \cong D_8\times Z_2$.
Question: how to remove some of the guesswork from this step.  For example, I know $D_8$ is a candidate of the right order, how can I show that it is or isn't the right group more easily than guessing permutations?  [I can usually understand the general theories, but when confronted by specific groups I go to pieces and end up tabulating.]
Thanks.
Comment: A remark to help you improve your mathematical lexicon: in the given context the syntagm does nevertheless get the idea across, but there is no such thing as a "direct sum of permutations". Also, $\Sigma_6$ is by definition the group of all permutations of the natural interval $[1, 6]$, so it is somewhat awkward to speak of the representation of this group by permutations of $[1, 6]$ (formally, this would be the identity representation). There is no need to represent an object by itself.
Answer: For the remark that $S_6$ contains a subgroup ismorphic to $S_4\times S_2$, I believe the neatest way of saying it is that the standard embedding of $S_4$ in $S_6$ (i.e. permutations fixing 5 and 6) commutes elementwise with $H=\langle (56)\rangle\simeq S_2$ and their intersection is trivial, so that their product $S_4\cdot H=\{\sigma\tau\ |\ \sigma\in S_4, \tau\in H\}$ is indeed isomorphic to their direct product.
The rest of the argument is fine in itself: moreover, you will have to do some handiwork when dealing with concrete groups. For example, knowing that $D_8$ has the right order is not enough.  Even if you exclude abelian groups of order 8 (which seem unlikely to be 2-Sylows of $S_4$), you are left with two options, namely $D_8$ or $Q_8$ (quaternions), and it is concrete exploration of $S_4$ to give you the answer on which of the two is the correct Sylow group.
Surely, though, there are ways to pick the right permutations that are more clever than others: in this case, moreover, there is a way you can get (somewhat) naturally to the answer, i.e. costruct a $2$-Sylow of $S_n$ inductively on $n$. For a positive integer $n$, call $\mu_2(n)$ the exponent of 2 in the prime factorization of $n!$, $P_n$ the (isomorphism class) of a 2-Sylow of $S_n$.
Clearly, $P_2\simeq C_2$ (where $C_n$ is the cyclic group of order $n$), and this holds for $P_3$ as well since $S_2$ embeds in $S_3$ and $\mu_2(3)=\mu_2(2)$.
As $\mu_2(4)=\mu_2(2)+2$, you must enlarge $\langle(12)\rangle<S_4$ by a factor 4. One factor 2 comes naturally by embedding $S_2$ in $S_4$ as $\langle(34)\rangle$: for the same argument used in the first paragraph, you may clearly see that $$H=\langle(12)\rangle\cdot\langle(34)\rangle\simeq C_2\times C_2.$$ Now, you have no more disjoint $C_2$ to multiply to your $H$, but you can still exchange $(12)$ and $(34)$, namely by conjugating by the double transposition $(13)(24)$. If $K=\langle(13)(24)\rangle$, this gives the product $HK$ (which is a subgroup, since $H$ and $K$ commute) a natural structure of semidirect product $H\rtimes K$ or, if you prefer, the isomorphism structure of $D_8$, so that $P_4\simeq (C_2\times C_2)\rtimes C_2$.
At this point, since $\mu_2(6)=\mu_2(4)+1$, just multiplying $P_4<S_6$ by the disjoint $C_2$ given by $\langle (56)\rangle$ does the trick, and leaves you with $P_6\simeq P_4\times P_2$.
Also, this construction has the advantage of showing a pattern. In fact, if you compute $\mu_2(n)$, you will easily see that:

$P_{2^{n+1}}\simeq (P_{2^{n}}\times P_{2^{n}})\rtimes C_2$ as in the case of $P_4$, which is normally written $P_{2^{n}}\wr C_2$ and called a wreath product;
if $n=a_0+a_1\cdot 2+\cdots+a_k\cdot 2^k$ in base 2, $P_n\simeq \prod_{j=1}^k (P_{2^i})^{a_i}$, as with $P_6$;
this generalizes to other primes in the obvious way.
Comment: Thank you for the comprehensive answer!  I'm aware of both semidirect products and wreath products, though not yet confident to apply them to real examples, so this is very helpful.  Just to clarify, are you setting K = <(13)(24)>?  Is there a normality condition to check (for the semidirect product,) or is that automatic by the construction?
Comment: Precisely, it slipped my mind to define $K$. Yes, I was not a hundred percent precise about the semidirect product: in fact, one has to declare *which* semidirect product it is, i.e. what is the morphism $K\rightarrow \operatorname{Aut}(H)$ defining the product. In this case, though, as I tried to quickly hint about, the "natural" morphism is conjugation by elements of $K$. Indeed, as you noticed, this works precisely because $K$ normalizes $H$: but this comes at once from the choice of $K$, since $(13)(24)$ acts on $H$ by conjugation switching its generators, so clearly sends $H$ to itself.


ExtJS how to make toolbar that wraps its elements?

Question: I have a toolbar with few filters, on a small screen (low res) some checkboxes are invisible (outside right edge). How to make toolbar (on a Grid Panel) that wraps its elements ?
I'm using extJs 3.4
Answer: Off the top of my head you could use the enableOverflow: true config option in your Ext.Toolbar instance. This will add a button which, when clicked will show the items that could not fit in the toolbar originally.
Comment: That adds horizontal scrollbar, looks bad, but it solves the problem.
wait, no, it doesn't work on IE9, IE9 makes a lot of empty space below toolbar :/
Answer: you can check out this extension too:
http://www.sencha.com/forum/showthread.php?12283-Scalable-(wrapping)-Toolbar-for-when-toolbar-needs-to-wrap


Base64 decode byte array - APNS token from iOS

Question: I am receiving a device token, encoded as a base64 "byte" array.  The input looks like this:
J6Kwrh15AqXKiaQminI/Eb/Mtj4nMkPhQYsROhJXmes=

I am told this is a base64 encoded value, but decoding it using base64_decode returns:
string(32) "'¢°®y¥Ê‰¤&Šr?¿Ì¶>'2CáA‹:W™ë"

I found this script somewhere which should be outputting the actual APNS token:
$a = base64_decode("J6Kwrh15AqXKiaQminI/Eb/Mtj4nMkPhQYsROhJXmes=");
$b = array();

foreach(str_split($a) as $c)
    $b[] = sprintf("%08b", ord($c));

exit(implode(' ', $b));

But it returns:
00100111 10100010 10110000 10101110 00011101 01111001 00000010 10100101 11001010 10001001 10100100 00100110 10001010 01110010 00111111 00010001 10111111 11001100 10110110 00111110 00100111 00110010 01000011 11100001 01000001 10001011 00010001 00111010 00010010 01010111 10011001 11101011

And I'd expect something like:
c9d4c07c fbbc26d6 ef87a44d 53e16983 1096a5d5 fd825475 56659ddd f715defc

What is wrong?
Answer: To generate a hex, you could use something like this:
$a = unpack("H*", base64_decode("J6Kwrh15AqXKiaQminI/Eb/Mtj4nMkPhQYsROhJXmes="));
print_r($a);

($a is now an array with your hex)
To include the spacing you could use:
$a = unpack("H*hex", base64_decode("J6Kwrh15AqXKiaQminI/Eb/Mtj4nMkPhQYsROhJXmes="));
$b = str_split($a["hex"], 8);
$output = "";
foreach ($b as $current) {
    $output .= "$current ";
}
echo($output);

and finally everything wrapped into a function:
function base64_decode_apns_token($token) {
    $a = unpack("H*hex", base64_decode($token));
    $b = str_split($a["hex"], 8);
    $output = "";

    foreach ($b as $current) {
        $output .= "$current ";
    }

    return trim($output);
}

Comment: Sorry-- this does not work. See fiddle: http://ideone.com/rd0mHR - they all return the same output
Comment: If this can help: "The token is an opaque binary data structure, stuffed into an NSData object. Apple doesn't want you to mess around with its internals. For our purposes it is enough to know that it is currently 32 bytes long. As you can see above, the token can be represented by 64 hexadecimal characters. You will be using it in that format, although you still strip off the brackets and leave out the spaces."
Comment: Well, of course your code doesn't work, if your function decodes the same token every time! (Pls look at my answer)
Comment: LOL. Sorry. That was horrible. Thanks.


Verify domain on mailchimp when emails are received by SES and stored in S3

Question: I have setup a domain in Amazon SES. I can both send and receive emails from/to this domain. Received emails are saved in a S3 bucket.
I can successfully send an email to whatever@mydomain and I can see it in my S3 bucket.
Still, all the verification emails sent from Mailchimp are not received. The first email seems to be sent correctly (despite the fact I do not receive it), all the following email result in the following Bounce Error message.

We're having some trouble delivering to [mydomain]. Looks like the verification email might've bounced.

Any Clue about it?
Is there a way to whitelist IP's or sending domains in Amazon SES?
Comment: *Is there a way to whitelist IP's or sending domains in Amazon SES?* seems like the wrong question, because it shouldn't be necessary.  *"The first email seems to be delivered correctly (despite the fact I do not receive it)"* What does that mean?  It can't both be delivered and not delivered.
Comment: Mailchimp prompt me with a "Your verification email is on the way!" the first time I ask for the confirmation message, but I do not receive it. At the second try it gives me the error message specified in the question. I will update the Q to be clearer.
Comment: They are probably just saying that it's "on the way" because they've enqueued it locally.  It's not good practice to try to actually do anything meaningful with an email message in the high-availability path of a web site, so I would assume the first-attempt appearing different in the UI would not actually be meaningful.  *"I can successfully send an email"* ... from where are you sending the test that's working?  Can you mention your domain so we can take a look at things?
Answer: The problem was related to DNS propagation. Amazon SES was initially set only to send email, then I added the MX record to receive emails and forward them to S3. The MX record acctually took around 48hrs to propagate.


Filtering "Product review" if the exist in Rails

Question: My code works fine, but I want to know if there is an easy and faster way to filter it?
I'm doing: "If current_user already has a review, do not let him review and hide form".
products_helper.rb:
def current_user_commented?
    @product.product_reviews.each do |p|
        current_user.profile.product_reviews.each do |r|
            return false if r == p
        end
    end
end

show.html.rb:
<% if logged_in? %>
  <% if current_user_commented? %>
    <%= form_for ([@product, ProductReview.new]) do |f| %>

          <%= f.label :comment %>
          <%= f.text_field :body %>

      <%= f.submit 'add Comment' %>
    <% end %>
  <% end %>
<% end %>

Comment: Not sure if `profile.product_review` is a typo, it's probably the plural form. You haven't posted a lot of code so this might not work, but try something like this: `current_user.profile.product_reviews.where(product: @product).exists?`
Comment: Ouch, its supposed tobe `profile.product_reviews`.
Sorry for less code, didnt put routes/associations. Reviews `Many and/to belongs`. Profile `has_and_belongs_to_many`
Comment: Thanks, its worked: `<% unless current_user.profile.product_reviews.where(product: @product).exists? %>`
Comment: You're welcome! I've added it as an answer. :)
Answer: Try something like this:
current_user.profile.product_reviews.where(product: @product).exists?

This returns true if the user has already reviewed @product.
This solution is quite efficient as it executes a single database query rather than fetching records and performing equality checks in Ruby.
Also read the Rails documentation on exists? and ActiveRecord queries.
Comment: *WHY* should the OP use this? Providing code is nice, but explaining why the code works is very important as it teaches how to reuse it. It's akin to giving someone a fish or teaching them how to fish.
Comment: I've added fishing instructions :)
Comment: Excellent. Thank you. :-)


What aspects of the "Iris" data set make it so successful as an example/teaching/test data set

Question: The "Iris" dataset is probably familiar to most people here - it's one of the canonical test data sets and a go-to example dataset for everything from data visualization to machine learning. For example, everyone in this question ended up using it for a discussion of scatterplots separated by treatment.
What makes the Iris data set so useful? Just that it was there first? If someone was trying to create a useful example/testing data set, what lessons could they take away from it?
Comment: The 'iris' dataset can be used for discriminant analysis, as well as unsupervised classification (model-based or model-free clustering) for illustrative purpose. This question deserves a cross-reference to [What are good datasets to illustrate particular aspects of statistical analysis?](http://stats.stackexchange.com/q/21486/930)
Answer: The Iris dataset is deservedly widely used throughout statistical science, especially for illustrating various problems in statistical graphics, multivariate statistics and machine learning.

Containing 150 observations, it is small but not trivial.

The task it poses of discriminating between three species of Iris from measurements of their petals and sepals is simple but challenging.

The data are real data, but apparently of good quality. In principle and in practice, test datasets could be synthetic and that might be necessary or useful to make a point. Nevertheless, few people object to real data.

The data were used by the celebrated British statistician Ronald Fisher in 1936. (Later he was knighted and became Sir Ronald.) At least some teachers like the idea of a dataset with a link to someone so well known within the field. The data were originally published by the statistically-minded botanist Edgar Anderson, but that earlier origin does not diminish the association.

Using a few famous datasets is one of the traditions we hand down, such as telling each new generation that Student worked for Guinness or that many famous statisticians fell out with each other. That may sound like inertia, but in comparing methods old and new, and in evaluating any method, it is often considered helpful to try them out on known datasets, thus maintaining some continuity in how we assess methods.

Last, but not least, the Iris dataset can be enjoyably coupled with pictures of the flowers concerned, as from e.g. the useful Wikipedia entry on the dataset.

Note. Do your bit for biological correctness in citing the plants concerned carefully. Iris setosa, Iris versicolor and Iris virginica are three species (not varieties, as in some statistical accounts); their binominals should be presented in italic, as here; and Iris as genus name and the other names indicating particular species should begin with upper and lower case respectively.
(EDIT 4 May 2022 In a generally excellent book to hand on machine learning, the Iris data are described in terms of classes, types, kinds and subspecies, but never once correctly from a biological viewpoint. Naturally that sloppiness makes not a jot of difference to the machine learning exposition.)
Stebbins (1978) gave an appreciation of Anderson, a distinguished and
idiosyncratic botanist, and comments on the scientific background to
distinguishing three species of the genus Iris. Kleinman (2002)
surveys Anderson's graphical contributions with statistical flavor. See also Unwin and Kleinman (2021).
Kleinman, K. 2002.
How graphical innovations assisted Edgar Anderson's discoveries in
evolutionary biology.
Chance 15(3): 17-21.
Stebbins, G. L. 1978. Edgar Anderson 1897--1969.
Biographical Memoir. Washington, DC: National Academy of Sciences.
accessible here
Unwin, A. and Kleinman, K. 2021. The iris data set: In search of the source of virginica. Significance 18: 26-29. https://doi.org/10.1111/1740-9713.01589
Comment: I'd give an extra +1 if I could for a principled stand for biological correctness.
Comment: I like that it is well known, so the student has a rich library of reference/certified results, and that there is a mislabeling which makes for useful imperfect labeling. I also like that the measured variables each have different but nonzero contribution to classification.
Answer: The dataset is big and interesting enough to be non-trivial, but small enough to "fit in your pocket", and not slow down experimentation with it.
I think a key aspect is that it also teaches about over-fitting. There are not enough columns to give a perfect score: we see this immediately when we look at the scatterplots, and they overlap and run into each other. So any machine-learning approach that gets a perfect score can be regarded as suspicious.


Unable to run Scrapy code

Question: I have written the following code:
spiders.test.py code:
  from scrapy.spider import BaseSpider
  from scrapy.selector import HtmlXPathSelector
  from wscraper.items import WscraperItem

  class MySpider(BaseSpider):
  name = "ExampleSpider"
  allowed_domains = ["timeanddate.com"]
  start_urls = ["https://www.timeanddate.com/worldclock/"]

  def parse(self, response):
       hxs = HtmlXPathSelector(response)
       titles = hxs.select("/html/body/div[1]/div[8]/section[2]/div[1]/table/tbody").extract()
    #for titles in titles:
        #title = titles.select("a/text()").extract()
        #link = titles.select("a/@href").extract()
        print title

The code for scraper.items is:
          from scrapy.item import Item, Field
      class WscraperItem(Item):
      # define the fields for your item here like:
      # name = scrapy.Field()
      title = Field()
      pass

I'm getting the following error on running the command "scrapy crawl ExampleSpider":
      [boto] ERROR: Caught exception reading instance data
        Traceback (most recent call last):
        File "/usr/lib/python2.7/dist-packages/boto/utils.py", line 210, in
   retry_url
   r = opener.open(req, timeout=timeout)
   File "/usr/lib/python2.7/urllib2.py", line 429, in open
   response = self._open(req, data)
   File "/usr/lib/python2.7/urllib2.py", line 447, in _open
    '_open', req)
    File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
    result = func(*args)
    File "/usr/lib/python2.7/urllib2.py", line 1228, in http_open
    return self.do_open(httplib.HTTPConnection, req)
     File "/usr/lib/python2.7/urllib2.py", line 1198, in do_open
     raise URLError(err)
     URLError: <urlopen error [Errno 101] Network is unreachable>
    [boto] ERROR: Unable to read instance data, giving up
    [scrapy] ERROR: Error downloading <GET
     https://www.timeanddate.com/worldclock/>
     Traceback (most recent call last):
     File "/usr/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 45,
     in mustbe_deferred
      result = f(*args, **kw)
      File "/usr/lib/python2.7/dist-
     packages/scrapy/core/downloader/handlers/__init__.py", line 41, in
     download_request
      return handler(request, spider)
      File "/usr/lib/python2.7/dist-
      packages/scrapy/core/downloader/handlers/http11.py", line 44, in
      download_request
      return agent.download_request(request)
      d = super(CachingThreadedResolver, self).getHostByName(name, timeout)
      File "/home/priyanka/.local/lib/python2.7/site-
      packages/twisted/internet/base.py", line 276, in getHostByName
       timeoutDelay = sum(timeout)
       TypeError: 'float' object is not iterable
       [scrapy] INFO: Dumping Scrapy stats:
       {'downloader/exception_count': 1,
      'downloader/exception_type_count/exceptions.TypeError': 1,
       'downloader/request_bytes': 228,
       'log_count/DEBUG': 2,
       'log_count/ERROR': 3,
       'log_count/INFO': 7,
      'scheduler/dequeued': 1,
      'scheduler/dequeued/memory': 1,

Comment: could you please include `WebScraperItem` code in the post, most probably issues there.
Answer: Spider name has to be str, not list, so:
class ExampleSpider(BaseSpider):
  name = "timeandzone"

otherwise Scrapy spider loader fails to load it.
Answer: Basically, I had a compatibility issue.So, I installed Scrapy1.3.3 and this resolved the issue and yes as mentioned in the answer above spider name should be a string.

Unable to run Scrapy code


Haskell Webviewhs getElementById from a webpage

Question: Still most potential for a GUI to Haskell for me, but missing some essential info in the examples, being a noob Haskeller. Assuming one of the examples:
{-
  webviewhs
  (C) 2018 David Lettier
  lettier.com
-}

{-# LANGUAGE
    OverloadedStrings
#-}

import qualified Graphics.UI.Webviewhs as WHS

main :: IO ()
main =
  WHS.createWindowAndBlock
    WHS.WindowParams
      { WHS.windowParamsTitle      = "webviewhs - How do I create a window and have it run itself?"
        -- This could be a localhost URL to your single-page application (SPA).
      , WHS.windowParamsUri        = "https://lettier.github.com"
      , WHS.windowParamsWidth      = 800
      , WHS.windowParamsHeight     = 600
      , WHS.windowParamsResizable  = True
      , WHS.windowParamsDebuggable = True
      }

This creates a window in which I can load a custom webpage. Assuming this webpage has a <input type="text" id="mytext"> and there's a button next to it. Not that it matters but <button type="submit" id="sendtohaskell">. How would I go about getting the info in the textfield to Haskell by pressing the button? There's no example like that in the tutorial. For me it is the missing link to get info from a webapp, processing it in Haskell and returning it to eg. SQLite.
Comment: @Madderote Actually there is plenty of documentation at https://lettier.github.io/webviewhs/
Comment: It's not missing from the tutorial. How to communicate between Haskell and JavaScript is literally in the next paragraph after the code you're quoting here on the [github page](https://github.com/lettier/webviewhs)
Comment: You should also take a look at the examples: https://github.com/lettier/webviewhs/tree/master/examples
Comment: @Cubic no its not. That does not create a window nor gets anything back. Sorry that I just don't see it here. Think my question is quite clear and that specific example is not available unfortunately.
Comment: @Michael Litchard: wouldn't have posted the question if I didn't try and tried all examples. It is a very specific question and documentation other than the examples on github are very limited to non-existent.
Answer: As the github page shows, you can receive data from JS with a callback, and execute arbitrary JS in the window from Haskell. This is enough to do any sort of communication you might want, here's an example that that executes some Haskell on a button press and then shows the result in the webpage:
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Main where

import System.Directory(getCurrentDirectory)
import Text.Printf
import Control.Monad(void)
import Language.Javascript.JMacro
import qualified Graphics.UI.Webviewhs as WHS
import qualified Data.Text as T

windowCallback window = do
  return True

handleJSRequest window request = void . WHS.runJavaScript window $ [jmacro|
  show_response `(printf "'Got response: %s'" request :: String)`
  |]

main :: IO ()
main = void $ do
  dir <- getCurrentDirectory
  WHS.withWindowLoop
    WHS.WindowParams
      { WHS.windowParamsTitle = "Test"
      , WHS.windowParamsUri = T.pack $ printf "file://%s/example.html" dir
      , WHS.windowParamsWidth = 800
      , WHS.windowParamsHeight = 600
      , WHS.windowParamsResizable = True
      , WHS.windowParamsDebuggable = True
      }
    handleJSRequest
    windowCallback

    <title>Example</title>
    <meta charset="utf-8">

    <input type="text" id="textbox"/>
    <input value="say hello" type="button" onclick="submit()"/>

You should note though that the haskell webview library has only 2 commits, the last of which was more than 7 months ago, so it's not exactly being actively developed at the moment.
Comment: Thanks Cubic. Answered with exactly what I needed to know. Now I can comfortably concentrate on learning Haskell again 8)
By the way: thanks for the comments on the development. Have to say though that I actually like this one the best when it comes to Haskell GUIs.


How can i put popup box captcha on managed file remove button?

Question: Can We write function for remove button as I want to display Captcha in popup on Remove button for security reason.
same type of some function like used in below post.
How can I automatically upload images on file selection rather than pressing the upload button?
Comment: I have search into file.js file in core modules but what happens if i add any confirmation alert on it, ajax is response  first than javascript calls. I do not underspend how to start..
Comment: can I use Drupal.ajax.prototype.beforeSubmit  function for manage_file form element events??? means can we use ajax.beforeSubmit for remove button events as i have search alot and do not get any solution.. please help me out...
Answer: I have solved it. I have hide remove button access. and then put my own remove button, and open dialog box in form to display popup box.

please see code.
drupal_add_library('system', 'ui.dialog');
drupal_add_js('jQuery(document).ready(function(){
    jQuery("#clicky").live("click", function(){
        jQuery("#dialog").dialog({ modal: true ,height: 250,width: 350, buttons: [
            {
            text: "Cancel",
            click: function() {
                jQuery(this).dialog("close");
            }},
            {
                text: "Submit",
                click: function() {
                     jQuery("#dialog-form").submit();
            }}
        ]});});});', 'inline');


Retorno de vetor e matriz de uma função no c!

Question: O problema que eu estou tendo é que o meu ponteiro serieinversa fica todo nulo, sendo que o resto do código roda de boa, eu realmente não encontro qual é o problema!
Se alguem poder me ajudar eu agradeço desde já!!Obs.: Tem algumas blibiotecas a mais para a utilização em outros códigos que n tem nenhuma ligação com esse em questão!
main:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include "repository.h"

int main()
{
    int *serieoriginal;
    int *serieinversa;
    unsigned int i, j;
    serieoriginal = (int*) calloc(12, sizeof(int));
    serieinversa = (int*) calloc(12, sizeof(int));

    printf("Bem vindo ao modo de musica Dodecafonico!\n\n");

    printf("Digite os valores da serie!\n");
    Sleep(300);
    for (i = 0; i < 12; i++) {
        printf("  %d valor: ", i+1);
        scanf("%d", &serieoriginal[i]);
    }

    *serieinversa = SeInv(serieoriginal);

    printf("\nSerie original: ");
    for (i = 0; i < 12; i++) {
        printf("%d ", serieoriginal[i]);
    }
    printf("\nSerie inversa: ");
    for (i = 0; i < 12; i++) {
        printf("%d ", serieinversa[i]);
    }

    return 0;
}

blibioteca repository.h:
#ifndef REPOSITORY_H_
#define REPOSITORY_H_

int* SeInv(int* s);

#endif

repository.c:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>

int* SeInv(int *s)
{
    int P[12]/*serie transposta*/, *R[12]/*serie retrogradada*/;
    int i, k, aux;

    srand( (unsigned)time(NULL) );
    k = 5;//rand()%12;
    printf("\n K: %d\n", k);
    printf("\nSerie: ");
    for (i = 0; i < 12; i++) {
        printf("%d ", s[i]);
    }
    for (i = 0; i < 12; i++) {
        aux = s[i];
        aux = (aux + k)%12;
        P[i] = aux;
    }
    printf("\nP: ");
    for (i = 0; i < 12; i++) {
        printf("%d ", P[i]);
    }
    k = 0;
    for (i = 12; i > 0; i--) {
        R[k] = P[i-1];
        k++;
    }
    printf("\nR: ");
    for (i = 0; i < 12; i++) {
        printf("%d ", R[i]);
    }
    return (*R);
}

Comment: Por que as tags c++ e c#?
Comment: Jovem, C, C++ e C# **não são** a mesma coisa.
Comment: coloquei apenas para ter uma gama maior de pessoas que poderiam me ajudar!
Answer: Consertei o retorno do método, quanto a ordem dos valores, não sei se deve retornar o exatamente o inverso da original, ou alguma ordem em seus cálculos.
Primeiramente a no arquivo main.c a linha:
serieinversa = (int*) calloc(12, sizeof(int));

Não tem a necessidade de alocar um tamanho para o ponteiro, pois ele recebera um endereço de um método mais para frente. Nesse caso o ideal é:
serieinversa = NULL;

Na linha:
*serieinversa = SeInv(serieoriginal);

O método SeInv retorna um ponteiro de inteiros, a sua variável serieinversa já é um ponteiro de inteiros, no caso do código, você está tentando armazenar o endereço retornado dentro de outros endereço. O correto seria.
serieinversa = SeInv(serieoriginal);

No arquivo repository.c, alinha:
int P[12]/*serie transposta*/, *R[12]/*serie retrogradada*/;

Esta declarando um ponteiro de um vetor de 12 posições *R[12], o ideal é, usar apenas vetor ou apenas ponteiro, no caso do trecho do código, diria que está parecendo mais uma matriz, mudei para:
int P[12]/*serie transposta*/;
int *R = (int *) malloc(sizeof(int)*12);

Como R é o sei retorna, deve ser um ponteiro para não ter incompatibilidade com seu método e variável que irá recebê-la.

E por fim o retorno de SeInv:
return (*R);

Você está retornando o vetor que estava em R, mas os valores não estão dentro do vetor dentro de R, e sim em R. Por isso que deve retornar apenas o R:
return R;

Sugiro dar uma revisado no calculo de inversão para ver se está realmente correto.
Comment: Obrigado amigo, era realmente a alocação do ponteiro R na função SeIvn() que estava ocasionando o problema, e referante ao calculo de inversão, não é apenas uma inversão, tem mais coisa, mas meu problema era só o retorno da função msm, muito obrigado!
Comment: @GuilhermeGehlen, se a resposta resolveu seu problema, você pode marcar o "V" do lado da resposta para indicar que está resolvido


What may cause "An illegal choice has been detected. Please contact the site administrator"?

Question: When a user goes to create content, usually for a forum the following error is received.

An illegal choice has been detected. Please contact the site
  administrator.

The forum topic can still be created however.
This doesn't happen if the user is administrator.
The following errors can be seen in error report
<code>Type form
Date Wednesday, May 1, 2013 - 12:24
User 222_test
Location
Referrer    /node/add/forum
Message Illegal choice 423 in term_node_tid_depth_1 element.
Severity error
Hostname
Operations

Type form
Date Wednesday, May 1, 2013 - 12:24
User 222_test
Location /node/add
Referrer    /node/add/forum
Message Illegal choice 427 in term_node_tid_depth element.
Severity error
Hostname
Operations
</code>
Answer: I would say that this means that the user has selected term 423 for term_node_tid_depth_1 and 427 for term_node_tid_depth, but those values are not actually options in that field.
Usually the way this happens if you have custom code that sets the field value to an invalid value, or if it changes the field and removes some of the possible allowed values.
You say it doesn't happen when you are the admin, so I would guess that the admin has access to all the options in the field but other users are just seeing a subset of the field values, but somehow are still setting the field to one of the values they aren't allowed to see.
Do you have any custom code or are using any unusual field or forum related modules?