Trying to animate such that the other rectangle below it moves upward?

Question:
<StackPanel x:Name="rootStackPanel" Background="{ThemeResource SystemControlAcrylicWindowBrush}" Padding="0,48">

    <Rectangle x:Name="sampleRectangle" Width="200" Height="300" Fill="DeepPink" DoubleTapped="Rectangle_DoubleTapped" RenderTransformOrigin="0.5,0.5">
        <Rectangle.RenderTransform>
            <CompositeTransform TranslateY="-100"/>
        </Rectangle.RenderTransform>
    </Rectangle>
    <Rectangle x:Name="otherRectangle" Width="200" Height="200" Fill="Cyan"/>

</StackPanel>

I want to achieve a dynamic look, where, when the pink rectangle is moved upward, the blue rectangle takes up the left over space. Such that it is always touching the pink rectangle.
I have tried manipulating offsets and scale properties provided by visual layer but the actual height is not affected by any of the property, as a result the other rectangle just stays in the original position. Now I am trying to achieve that effect using storyboards animation. But as you can see, the translation property (and the scale property as well) doesn't effect the actual container of the control somehow but rather makes the content in it move to whatever translation.
So, what properties do I need to manipulate to achieve the effect where the other rectangle inside the stackpanel moves dynamically with the changes to the first rectangle?
I know adjusting width or height property would result in what I am trying to achieve but for more complex scenarios where there might be a textbox rather than simple rectangle that is being animated, there is sort of a weird animation of the placeholder text(shrinking of text), which is something I don't want!
Comment: Have you see [`Microsoft.Toolkit.Uwp.UI.Animations.Behaviors`](https://learn.microsoft.com/en-us/windows/uwpcommunitytoolkit/animations/scale)?
Answer:
So, what properties do I need to manipulate to achieve the effect where the other rectangle inside the stackpanel moves dynamically with the changes to the first rectangle?

You could use  Microsoft.Toolkit.Uwp.UI.Animations.Behaviors to realize this feature directly. Before animate your rectangle, you need to get the absolute position of the each rectangle like the follow.
var scgt = sampleRectangle.TransformToVisual(Window.Current.Content);
Point screenCoords = scgt.TransformPoint(new Point(0, 0));

var ddv = otherRectangle.TransformToVisual(Window.Current.Content);
Point Res = ddv.TransformPoint(new Point(0, 0));

If you want pink rectangle to  move upward, you could Offset offsetY value
sampleRectangle.Offset(offsetX: 0, offsetY: -(float)screenCoords.Y - (float)sampleRectangle.Height, duration: 2500).Start();

And then animate otherRectangle like the follow
 otherRectangle.Offset(offsetX: -(float)Res.X, offsetY: -(float)Res.Y).Scale(scaleX: 2, scaleY: 2).Start();

You need keep scaleX equal with scaleY  when you scale TextBox.Otherwise, the TextBox will be deformed.
Comment: Yeah, I did used offset animation to achieve this, and it worked fine for this situation but for more complex situation where instead of a rectangle there is a listview that takes up all the space in a column. When offset animations are applied to it, the listview offsets by the amount and leaves space, thus no longer taking up the entire space provided.


Como obter um valor dentro de um array

Question: array(3) {
     ["recebidos"]=>
      array(16) {
        [0]=>
        array(25) {
          ["contratante_id"]=>
          int(1028)
          ["datacadastro"]=>
          string(20) "2019-08-01T12:30:44Z"
          ["observacoes"]=>
          NULL
          ["situacaoantiga"]=>
          string(5) "Ativo"
          ["turma_id"]=>
          int(1672)
          ["mataluno_id"]=>
          int(3157)
          ["horarioentrada"]=>
          NULL
    }

Answer: Sérgio, você está com um array multidimensional.
Para acessar as informações você pode trabalhar com foreach(), por exemplo.
    foreach($recebidos as $p => $kp){

            extract($recebidos[$p]);

            echo $contratante_id . '
';
            echo $datacadastro . '
';
            echo $observacoes . '
';

}

Há outras maneira para se resolver o que precisa. A de cima resolve seu problema, conforme array que você postou.
Espero ter ajudado

Como obter um valor dentro de um array


Trocar cor da tabela no Laravel Blade

Question: Olá. Quero trocar o background de uma tabela de acordo com o tipo no DB. Estou usando Laravel 5.5. Podem me ajudar?
Comment: Mesma lógica https://pt.stackoverflow.com/a/281717/99718 . Caso não consiga, poste seu código pois isso irá auxiliar.
Answer: Em primeiro lugar, o que você deve ter em mente é que não é o Laravel que faz a mudança em específico, mas sim uma possível classe que você define na tr da tabela como no exemplo abaixo:

.mytable tr td, .mytable tr, .mytable {
  padding:0; margin:0; border:none;
}
.mytable tr.red td { background: red; }
.mytable tr.blue td { background: blue; }
.mytable tr.green td { background: green; }
.mytable tr.yellow td { background: yellow; }
.mytable tr.pink td { background: pink; }

nome	 tipo

nome	 tipo

nome	 tipo

nome	 tipo

nome	 tipo

nome	 tipo

Sendo assim, para que seu problema seja resolvido você deve fazer algo assim:

<?php
    $lista = [
        ['nome' => 'Foo', 'tipo' => 'red'],
        ['nome' => 'Bar', 'tipo' => 'blue']
        ['nome' => 'Bin', 'tipo' => 'green']
        ['nome' => 'Ids', 'tipo' => 'yellow']
        ['nome' => 'Asd', 'tipo' => 'pink']
    ];
?>

        nome
        tipo

    @for ($i = 0; $i < count($lista); $i++)

            {{ $lista[$i]['nome'] }}
            {{ $lista[$i]['tipo'] }}

    @endfor

Answer: Para resolver, fiz uma validação.
    @if( $financa->banco == 1)
      @php $cor = 'red'  @endphp
    @elseif( $financa->banco == 2)
      @php $cor = 'green'  @endphp
    @else
      @php $cor = 'pink'  @endphp
    @endif

Trocar cor da tabela no Laravel Blade


Every $R$-module is a quotient of a free module

Question: I'm reading through my notes, and I have a theorem as the title says. As proof I have only a picture.

where $v:m\mapsto(0,...,0,1,0,...,0)$ and 1 is at $m$-th position.
I know, that $\oplus_M R$ is a free module generated by set  $M$, but is this all? I do not see how the statement is proved.
Answer: You can think to the free module $F$ generated by $M$ as the set of functions $f\colon M\to R$ such that $\{m\in M:f(m)\ne0\}$ is finite. The map $M\to F$ is $x\mapsto e_x$, where
$$
e_x(m)=\begin{cases} 1 & m=x \\[4px] 0 & m\ne x \end{cases}
$$
Addition and scalar multiplication on $F$ are obviously defined. The surjective homomorphism $\varphi\colon F\to M$ is given by
$$
\varphi(f) = \sum_{m\in M}f(m)m
$$
Clearly,
$$
\varphi(e_x)=x
$$
Answer: Recall the universal property of direct sum: if $M_j(j\in I)$ and $M$ are $R$-modules and $\{\phi_i\colon M_i\to M\}_{i\in I}$ are a family of homomorphisms, then there is a unique homomorphism $\phi\colon \bigoplus_{i\in I}M_i\to M$ making the following diagram commutative
$$
\begin{matrix}
M_j&\overset{\phi_j}{\longrightarrow}&M\\
\downarrow&\overset{\phi}{\nearrow}& \\
\oplus_{i\in I}M_i
\end{matrix}
$$
Now return to your problem. Generating a free $R$-module $R^{(M)}$ with the basis $M$, we define $\phi_m\colon R\to M$ by $\phi_m(1_R)=m$. Then the universal property provides an epimorphism $\phi\colon R^{(M)}\twoheadrightarrow M$.
Comment: Thank you. $\phi$ is surjective because $\mathrm{id}_M$ is surjective? Hence $M\cong R^{(M)}/\ker \phi,$ right?
Comment: @byk7 Ah, $\phi$ is surjective since each $m\in M$ admits a preimage $1_R$, through $\phi_m$ and thus the universal property implies that $m$ is the image of an element in $R^{(M)}$ (for example, the element with the $m$-th entry $1_R$ and other entries $0$). And the surjectiveness surely indicates $M\cong R^{(M)}/\ker\phi$.
Answer: You can take $\oplus_{m\in M}R_m$ where $R_m\simeq R$ and define $f:\oplus_{m\in M}R\rightarrow M$ by $f(1_m)=m, 1_m\in R_m$ is the neutral element, $f$ is surjective.


can infinite cont frac converge to rational

Question: Unsure whether question already answered - there are over 1000 questions on this forum with the "continued-fractions" string.
I request a proof (or hints) that an infinite continued fraction can not converge to a rational number.  Using http://www.math.uchicago.edu/~may/VIGRE/VIGRE2008/REUPapers/Yang.pdf as a reference, I followed pages 1-7 (through theorem 1.19), but can not determine how to use the referenced theorems 1.16 or 1.19 to create the desired proof.
Note: I am aware that all rational numbers have a (unique) finite continued fraction, as discussed at https://en.wikipedia.org/wiki/Euclidean_algorithm and https://en.wikipedia.org/wiki/Continued_fraction.  However, I don't think that the Euclidean Algorithm eliminates the possibility of an infinite continued fraction converging to a rational number.
Comment: It's important that it is a simple continued fraction. An infinite general continued fraction can definitely converge to a rational.
Comment: Also, this isn't twitter. You can use full words in your title.....
Comment: The convergents of the continued fraction for $\alpha \in \mathbb{R}^+$ are the best rational approximations of the number, in the sense that any better approximation has a larger denominator when written as a fraction. You can't have a better approximation than equality.
Comment: to law-of-fives thanks for the specification.  to user296602 although your comment seems intuitively reasonable, I don't understand how to turn this into  a formal proof.  Also, I looked at the bottom of https://crypto.stanford.edu/pbc/notes/contfrac/converge.html, but that reasoning compared (p/q), a convergent of _the_ finite continued fraction with (p_n/q_n), a convergent in the (mythical) infinite convergent fraction.  This seems invalid to me.
Answer: Next day, better mood. Khinchin does, indeed, do a better job. Theorem 11 on page 12 says, with the $a_0; a_1, a_2,...$ (positive) integers, all convergents $p/q$ are irreducible, that is $\gcd(p,q)=1.$ ASSUME the limiting value of an infinite (simple) continued fraction is rational $m/n$ with $\gcd(m,n) = 1.$
Theorem 9 on page 9 says  $$ \left| \frac{m}{n} - \frac{p}{q} \right| < \frac{1}{q^2} \; \; ,  $$
since the apparatus has $q_{k+1} > q_k.$
Your continued fraction is infinite, which means we can take a convergent far enough out so that
$$  q > n \; \; . $$
Then
  $$ \left| \frac{m}{n} - \frac{p}{q} \right| = \left| \frac{mq-np}{nq}  \right| < \frac{1}{q^2} \; \; . $$
In turn, this says
$$ |mq-np| < \frac{nq}{q^2} = \frac{n}{q} < 1. $$
As $|mq-np|$ is a non-negative integer, we find
$$   mq=np.  $$
As $\gcd(p,q) = 1,$ it follows that
$$  q | n \; \; .  $$
However, this contradicts $q > n,$ then contradicts the assumption that the limit of the infinite continued fraction is a rational number.
Comment: wow.  i'm going to flag, requesting that you be given more points.  i was frustrated because i had looked at 6 different cont frac sources, the REU pdf seemed the best of the 6, and I didn't want to start over with Khinchin.  Through thm 11 of the Khinchin pdf, it seems great.


Spring MVC - Gravar Dados em TXT

Question: Como poderia fazer pra dentro de um controller Receber dados via Post (no Spring MVC) e gravar estes dados em um TXT?
Posteriormente, na Model abrir este TXT e enviar para View.
Alguem teria algum exemplo?
Answer: Crie um metodo no seu controlar que receba uma requisição tipo post com os dados que deseja salvar como parametro. Crie um TxtDAO para o CRUD que deseja realizar em cima desse txt. A requisição entrega para o controller que entrega para o dao, este aplica a ação que você quer e te retorna o resultado. Na verdade eh a mesma analogia que faria em um DAO para banco de dados, soh que no conector, ao invés de ter um banco de dados, você construiria o DAO para arquivo.

Spring MVC - Gravar Dados em TXT


Determine significant figures from a scale/weight reading

Question: (Hope this is the right forum, otherwise please bear with me)
This is not a homework assignment but just some of the stuff you come across and stop to wonder.. Either I forgot how to do it or my old school books forgot to teach me.
Say I have a scale with the specs:

10 kg max load
0.005 kg resolution

What would be the significant figures in that reading?
I assume it would be 3 (#.## kg) even though the display might would show #.##0 or #.##5 kg.

EDIT
Thinking out loud example

First I was thinking that rounding should be conducted.
But I see that not rounding almost follows the meaning of sign. figures which means that a value of 1.44 kg could come from 1.435 kg or 1.444 kg - it's just shifted 0.001 kg due to computer resolution rounding (up).
Comment: Any digit could change when you add or subtract the resolution: consider a reading of `4.995`. Reporting to 1 decimal place would ensure that the reported value didn't differ from the similarly rounded upper & lower limits got by adding & subtracting the resolution; but might be taken to imply a worse resolution than you in fact have. [Edit: in fact that wouldn't *ensure* it: consider a reading of `1.445`]
Comment: https://en.wikipedia.org/wiki/Significant_figures
Comment: http://www.scalenet.com/applications/glossary.html
Comment: Hi @Scortchi, I didn't ask for how you look up things on wikipedia. But thank you for taking the time to read my question. Comments are used to clarify the question being asked.
Comment: Yes - I was hoping you'd clarify how the answer would differ from what you'd get by looking in Wikipedia. Not quite sure how the first part of the question on significant figures relates to the 2nd part (your edit) on resolution. Or how you arrive at 1.44 kg $\pm$ 0.009 kg.
Comment: @Scortchi sorry if my question is unclear. But what I mean by sign. figures are that these numbers er *certain* and will not vary.
Comment: I see your problem with the edit.. hmm.. looking into it
Answer: If the resolution of your scale is given in absolute numbers  $\delta$ and the true value you want to measure is $x_{true}$ then the measured value $x_m$ is within the range $x_m \in [x_{true}-\delta;x_{true}+\delta$].
Hence, you should give $$x_{true} = x_m\pm \delta$$ which leads to $1.44$kg $\pm5$g in your case.
Comment: (+1) But it'd make sense to report the measured value to the same precision as the uncertainty. After all, if the display read `1.445` you wouldn't report it as 1.45 kg $\pm$ 5 g. So 1.440 kg $\pm$ 5g.
Comment: Harald and @Scortchi please see my update. I might be mixing things so perhaps I can't talk about sign. figures in this case.
Comment: @Norfeldt. What exactly is the *question* though? You seem to be trying to find a way of rounding the measurement from which an uncertainty interval could be inferred equal to that calculated from the given precision. In general you won't be able to do that.
Comment: Sorry if my question is a brain fart..


Fourier Series of a sum of two functions

Question: Is the Fourier series of a  sum of two functions $f,g$ the term by term sum of the Fourier Series?
Comment: Yep, provided these sums converge.
Answer: Yes because of the linearity of integration.


In a GLM, does the link transform the estimated mean, or is the mean estimated from the transformed RHS?

Question: Is a GLM with a log link function the same as estimating:
$$y_i = \exp(\beta_0 + \beta_1 x_i)\ ?$$
A GLM is the following:
$$g(\mu_i) = \eta_i = b_0 + b_1 X_i$$
where $g(x)$ is the link function.
I don't understand $\log(\mu_i)=b_0+b_1 X_i$. Are you transforming the estimated $\mu_i$?  Is $\mu_i$ estimated based on:
$$\mu_i = \exp(\beta_0 + \beta_1 X_i)\ ?$$
If $\mu_i$ is estimated based on $\exp(\beta_0 + \beta_1 X_i)$, then $\mu_i = y_i$ because we haven't changed its value in the dataset at all. So is a GLM just a transpose of the predictor variables and model parameters?
I am very confused by the GLM because it looks like they're estimating parameters based on a transformed estimated result ($\mu_i$) which has been transposed but how can you do that if it is already estimated by the model?
Comment: I edited the appearance of your post so the formulas read easier. Please check that the meaning remains the same.
Comment: Obviously it cannot be that $y_i = \exp(\beta_0 + \beta_1 x_i)\ $ - that each data value is actually equal to some function of the population parameters. If it were, *two points* would give us an equation we could solve exactly for the $\beta$s, no uncertainty involved. You need to think more precisely about the model, & much of the mystery drops away immediately. What you mean for a GLM is actually more like $E(Y_i|x_i) = \exp(\beta_0 + \beta_1 x_i)\ $ (which when combined with the particular distributional family, and the assumption of independence allows you to form the likelihood function)
Answer: We have to be clearer on what it means to "estimat[e] $y_i = \exp(\beta_0 + \beta_1 x_i)$".  Although that looks like a completely formed thought, it isn't quite.  What's missing is the specification of the response distribution and/or error term.  (Since you are using the log link, I'll assume you are using the Poisson GLiM as your example, since the log is the canonical link for the Poisson GLiM.)  Now we have:
$$
\log(\lambda_i) = \beta_0 + \beta_1 x_i
$$
Thus, we can find estimated betas by finding the values of the betas that will maximize the likelihood:
$$
L_i = \prod_{i = 1}^N \frac{\lambda_i^{y_i}}{y_i!}e^{-\lambda_i}
$$
(or that minimize the deviance, $-2\times\ln(L_i)$, which is preferred for computational reasons, but yields the same estimated betas).

Since this is confusing, let's walk through it slowly.

Are you transforming the estimated $μ_i$?

Yes... or, sort of.  We estimate $\hat\mu_i$ by back transforming the RHS of the equation.

Is $μ_i$ estimated based on: $μ_i=\exp(β_0+β_1X_i)$?

Yes.

...then [isn't] $μ_i=y_i$ because we haven't changed its value in the dataset at all[?]

No.  The way this works is that we plug in some candidate values for the betas, run them through the RHS of the equation, and then exponentiate the result.  That is the predicted mean of the data at that point in the covariate space (i.e., when $X=x_i$) given the stipulated candidate betas.  For the Poisson distribution, the mean is $\lambda$, which is the parameter that governs the behavior of the distribution—once you know that, you know everything you need to know about that particular (conditional) Poisson distribution.  For example, you can determine the relative likelihood of any observed datum $y_i$.  So we are not assuming $y_i = \mu_i$; we use $\hat\mu_i = \hat\lambda_i$ to make it possible to determine $L(y_i|{\bf X}, \boldsymbol{\hat\beta})$.
Now, none of that implies that any given set of candidate beta values that we had stipulated are the best ones.  We will have to search.  But as we search, at each point we are now able to evaluate the fit / the likelihood of the stipulated beta values given the data.
For more on these topics, it may help you to read my answer here: Difference between logit and probit models.


Website responsivo

Question: Alguém me pode ajudar a colocar no site que estou a desenvolver ao que dizem de ser responsive, ou seja, quando acedo através de um smarthphone o website ajusta-se ao smartphone e se minimizar a janela do browser no desktop/laptop o website ajustar-se a ele?
O que eu vi foi estilo isso: http://www.w3schools.com/html/html_responsive.asp
Mas queria para o meu site e não estou a conseguir colocar, o site ajusta-se ao tamanho da janela em que esta a ser visualizado.
Cumprimentos e Obrigado
Comment: Um framework que eu aconselho é o Bootstrap. É bem produtivo. Mais informações em: http://getbootstrap.com/
Comment: Aqui está jovem padawam: [Tabela de comparação entre frameworks CSS](http://usablica.github.io/front-end-frameworks/compare.html). Estudar você deve.
Comment: Deixar um site responsivo caberia em um livro o nível de explicação, o que não é o objetivo deste site.
Comment: Procura sobre Media queries, assim você consegue ajustar o layout de acordo com a resolução que deseja, e com várias media queries de acordo com cada ponto de quebra do código. https://developer.mozilla.org/pt-BR/docs/Web/Guide/CSS/CSS_Media_queries
Answer: Deixar um site responsivo não é como adicionar uma feature no seu site, para isso é necessário um prática de estilização específica para isso, coisas que vão de um bom uso de unidades de medida (%, em, px, vw, etc) até um bom uso de breckpoints. É fundamental ter um conhecimento pelo menos intermediário de css para deixar um site realmente responsivo.
Uma coisa que pode ajudar muito a sua vida é o uso de bibliotecas de CSS, a mais usada e que é de muito fácil uso é o bootstrap, ele possui um sistema de grid que facilitara muito o processo de deixar um site responsivo. Recomendo que de uma lida na documentação dele e veja se pode lhe ser útil. Mas acima de  tudo recomendo que aprenda sobre os fundamentos de css.
Link do bootstrap: http://getbootstrap.com/

Website responsivo


Determine if Holiday falls within date ranges

Question: I have the following dataframe with start and end dates, as well as a list of defined holidays.
df = pd.DataFrame({'Start': ['2018-01-01 18:47','2018-01-08 06:11','2018-01-12 10:05','2018-02-10 09:22','2018-02-18 14:14','2018-03-08 16:17','2018-03-25 17:35'],
               'End': ['2018-01-02 17:00','2018-01-08 17:00','2018-01-16 10:05','2018-02-12 17:00','2018-02-19 14:14','2018-03-12 16:17','2018-03-26 17:00']})

Holidays = [date(2018,1,1),date(2018,1,15),date(2018,2,19),date(2018,3,9),date(2018,5,28),date(2018,7,4),date(2018,9,3),date(2018,11,22),date(2018,11,23),date(2018,12,24),date(2018,12,25)]

How can I go about determining the instances where a Holiday is either in between the respective Start and End Dates or is the same as the End Date?
I'm not interested if the holiday shares the same date as the Start Date.
The result should be as follows:
result = pd.DataFrame({'Start': ['2018-01-01 18:47','2018-01-08 06:11','2018-01-12 10:05','2018-02-10 09:22','2018-02-18 14:14','2018-03-08 16:17','2018-03-25 17:35'],
                   'End': ['2018-01-02 17:00','2018-01-08 17:00','2018-01-16 10:05','2018-02-12 17:00','2018-02-19 14:14','2018-03-12 16:17','2018-03-26 17:00'],
                   'InRange': [0,0,1,0,1,1,0]})

Answer: This is a O(n*m) solution
l=[any([(z>x)&(z<y) for z in Holidays]) for x , y in zip(df.Start.dt.date,df.End.dt.date)]
#[any((z>x)&(z<y) for z in Holidays) for x , y in zip(df.Start.dt.date,df.End.dt.date)]
l
Out[1089]: [False, False, True, False, False, True, False]

#df['InRange']=l
#df['InRange']=df['InRange'].astype(int)

Comment: Can't you use a generator expression with `any` to make it short-circuit? Like `any((z>x)&(z<=y) for z in Holidays)` [probably need `<= y` too]
Comment: @jpp yep we can do that


SPF and DKIM help: Do the FAIL reports from DMARC indicate an issue?

Question: I am having trouble determining if my SPF and DKIM are configured properly. Here are key details:

My domain is mysteryscience.com
We send mail from google apps, from SendGrid, and from Intercom. All seem to be working properly, although I do hear cases of our emails getting flagged as spam which is why I'm investigating this.
I have enabled SPF, DKIM, and DMARC
My SPF record seems to be semantically correct (checked here: http://www.kitterman.com/spf/validate.html)
My SPF TXT record is: v=spf1 ip4:126.96.36.199 include:_spf.google.com include:spf.mail.intercom.io -all
126.96.36.199 is my dedicated IP address for sending through SendGrid (mail.mysteryscience.com is my CNAME forwarding to them)

I have enabled DMARC and I'm reviewing the emails I get from various mail servers. While reviewing my results from Google.com I noticed a bunch of SPF and DKIM fails. It looks like these may have been rejections of legitimate emails I sent, but I'm not sure how to read this file. Here are a few of the results, note the "fail" on a few of the < dkim > and < spf > lines. And here is a dmarcian processed version of the XML file: https://dmarcian.com/dmarc-xml/details/Ybk591jex3JpVBmW/
<record>
<row>
  <source_ip>126.96.36.199</source_ip>
  <count>1</count>
  <policy_evaluated>
    <disposition>none</disposition>
    <dkim>pass</dkim>
    <spf>fail</spf>
  </policy_evaluated>
</row>
<identifiers>
  <header_from>mysteryscience.com</header_from>
</identifiers>
<auth_results>
  <dkim>
    <domain>mysteryscience.com</domain>
    <result>pass</result>
  </dkim>
  <spf>
    <domain>granderie.ca</domain>
    <result>pass</result>
  </spf>
</auth_results>
</record>
<record>
<row>
  <source_ip>126.96.36.199</source_ip>
  <count>1</count>
  <policy_evaluated>
    <disposition>none</disposition>
    <dkim>fail</dkim>
    <spf>pass</spf>
  </policy_evaluated>
</row>
<identifiers>
  <header_from>mysteryscience.com</header_from>
</identifiers>
<auth_results>
  <spf>
    <domain>mysteryscience.com</domain>
    <result>pass</result>
  </spf>
</auth_results>
</record>
<record>
<row>
  <source_ip>2607:f8b0:4001:c05::232</source_ip>
  <count>1</count>
  <policy_evaluated>
    <disposition>none</disposition>
    <dkim>pass</dkim>
    <spf>fail</spf>
  </policy_evaluated>
</row>
<identifiers>
  <header_from>mysteryscience.com</header_from>
</identifiers>
<auth_results>
  <dkim>
    <domain>mysteryscience.com</domain>
    <result>pass</result>
  </dkim>
  <spf>
    <domain>mail.mysteryscience.com</domain>
    <result>fail</result>
  </spf>
</auth_results>
</record>
<record>
<row>
  <source_ip>220.127.116.11</source_ip>
  <count>1</count>
  <policy_evaluated>
    <disposition>none</disposition>
    <dkim>pass</dkim>
    <spf>fail</spf>
  </policy_evaluated>
</row>
<identifiers>
  <header_from>mysteryscience.com</header_from>
</identifiers>
<auth_results>
  <dkim>
    <domain>mysteryscience.com</domain>
    <result>pass</result>
  </dkim>
  <spf>
    <domain>mail.mysteryscience.com</domain>
    <result>fail</result>
  </spf>
</auth_results>
</record>
<record>
<row>
  <source_ip>184.108.40.206</source_ip>
  <count>1</count>
  <policy_evaluated>
    <disposition>none</disposition>
    <dkim>fail</dkim>
    <spf>pass</spf>
  </policy_evaluated>
</row>
<identifiers>
  <header_from>mysteryscience.com</header_from>
</identifiers>
<auth_results>
  <spf>
    <domain>mysteryscience.com</domain>
    <result>pass</result>
  </spf>
</auth_results>
</record>
<record>
<row>
  <source_ip>188.8.131.52</source_ip>
  <count>1</count>
  <policy_evaluated>
    <disposition>none</disposition>
    <dkim>fail</dkim>
    <spf>fail</spf>
  </policy_evaluated>
</row>
<identifiers>
  <header_from>mysteryscience.com</header_from>
</identifiers>
<auth_results>
  <spf>
    <domain>nurturingwisdom.com</domain>
    <result>fail</result>
  </spf>
</auth_results>
</record>
<record>
<row>
  <source_ip>2607:f8b0:4003:c06::236</source_ip>
  <count>2</count>
  <policy_evaluated>
    <disposition>none</disposition>
    <dkim>pass</dkim>
    <spf>fail</spf>
  </policy_evaluated>
</row>
<identifiers>
  <header_from>mysteryscience.com</header_from>
</identifiers>
<auth_results>
  <dkim>
    <domain>mysteryscience.com</domain>
    <result>pass</result>
  </dkim>
  <spf>
    <domain>ssanpete.org</domain>
    <result>none</result>
  </spf>
</auth_results>

Can anyone help me determine if these SPF and DKIM fails are problematic?
Comment: @peterh you may misunderstand the function of [canonical](http://meta.serverfault.com/questions/1986/what-are-the-canonical-answers-weve-discovered-over-the-years) questions on SF; I recommend the first para of the linked document.  Nevertheless, unless four others agree with me, this question will stay open, so it's not done and dusted yet.
Comment: @MadHatter Although there are undeniable essential similarities, I think this question is much more specialized - and has a much better quality.
Comment: I revised my question to help clarify further.
Comment: Just remove your DMARC record, and watch your problems disappear.  See my answer below.
Answer: I ran some queries like spfquery --mfrom mail.mysteryscience.com -ip 2607:f8b0:4001:c05::232 on the results you provided.  It appears you have not configured SPF for mail.mysteryscience.com to allow google to deliver email for that domain.  That explains the SPF failures for deliveries from Google. The query above is based on the domains listed in the record.
There are some records that do appear to be Spam, so they should be in the list.
You may have similar problems with email not having appropriate DKIM signatures. Some may be Spam, or you may have delivery paths that do not sign the email with an expected signature.
Comment: But deliveries from Google are being sent from mysteryscience.com. It's only deliveries from SendGrid that are being sent from mail.mysteryscience.com. SendGrid controls that SPF (since it's just a CNAME to them). On the IP address you referenced, the "header_from" line a few rows down says "mysteryscience.com" so it seems to confirm what I'm saying. However, I do see a few lines down the SPF fail lists the domain mail.mysteryscience.com. I'm clearly misunderstanding something.
Comment: You mentioned "there are some records that do appear to be spam". How can you tell? Is it possible the 2607:f8b0:4001:c05::232 record is also a spam? Maybe every fail in my XML is legitimate?
Answer:
Parse your DMARC XML's somewhere like dmarcian, so your information is human readable
Google Outbound gateway goes where? Do you have a gateway configured? If not there's nothing to change.
DKIM is failing, are you signing your emails without a public key published? check your DNS.
SPF records for subdomains, you only need this if the mail server accepts emails and sends NDR's.  a typical subdomain record would be:

mail.example.com. IN A 18.104.22.168
mail.example.com. IN TXT "v=spf1 a -all"
Comment: what? Why do you cname mail to sendgrid? I use sendgrid on my blog and I never had to do something like that, I have a dkim sector that is a cname to sendgrid's and include their SPF in my domain, which is all anyone needs to authenticate email.
Comment: 1. Very helpful, thanks. Here is the dmarcian parsed version of the raw XML I pasted above. I'm having trouble interpreting the results. I see many fails in my raw XML, but it's not obvious if I have actual problems. Can you tell? https://dmarcian.com/dmarc-xml/details/Ybk591jex3JpVBmW/
Comment: 2. You're right, I was mis-reading that google gateway comment. I don't have one configured.
Comment: 3. You're right, thanks. I had DKIM configured for mail.mysteryscience.com but *not* for mysteryscience.com. I just added this.
Comment: 4. After researching more, I can't add SPF records for subdomains because mail.mysteryscience.com is a CNAME to SendGrid. This delegates the SPF to SendGrid. I don't think this is my issue.
Comment: Jacob, I'm just following SendGrid's directions on that. If I don't white label, they're claiming the "from" will add "on behalf of" for some email clients because the from domain is different than the mail server sending. This screenshot from their control panel summarizes the difference: https://www.dropbox.com/s/is8msl3ly1uhg1e/Screenshot%202015-10-02%2015.20.45.png?dl=0
Comment: I was in my SendGrid and saw that, which is why I went back to mandrill


string replace phone number iOS swift

Question: I import a phone-number  from "Contacts" and save in NSString.
this string contains white-space and I try to delete them using the method:
numero = numero.stringByReplacingOccurrencesOfString(" ", withString: "")

this method doesn't work.

func sostituisci( stringa: NSString! ) -> NSString
{
var numero: NSString = ""
NSLog(stringa)
numero = ((stringa as String).stringByReplacingOccurrencesOfString(" ", withString: "") as NSString)
NSLog(numero)

return numero
}

the output unchanged

log
2014-11-05 17:54:50.734 HappyRicarica[33438:3119446] (327) 124-3503
2014-11-05 17:54:50.737 HappyRicarica[33438:3119446] (327) 124-3503

Comment: For the record, Foundation's types are different from Swift's Types. A `String` in Swift is not an `NSString`
Comment: What happens when "it doesn't work?"  Is the string unchanged?  Do you get an error?  This worked fine for me with `numero` declared as either `String` or `NSString`.  Is `numero` declared with `var` or `let` ?
Comment: the string unchanged.
Comment: numero is declared var
Comment: option-click on `numero`.  What does it say?  Also, could you show us the value of `numero` before you try to change it?
Comment: method
[code]
   func sostituisci( stringa: NSString! ) -> NSString
    {
        var numero: NSString = ""
        NSLog(stringa)
        numero = ((stringa as String).stringByReplacingOccurrencesOfString(" ", withString: "") as NSString)
        NSLog(numero)
        return numero
    }
[/code]
Comment: log: 2014-11-05 17:24:03.212 HappyRicarica[33274:3108083] (327) 124-3503
2014-11-05 17:24:03.213 HappyRicarica[33274:3108083] (327) 124-3503
Comment: update your question with the code and output from the above comments.  It is hard to read in comments.
Comment: So if you call `sostituisci(" 1 2 3 4 5 ")` you are saying that both `NSLogs` are the same?
Comment: update the question whit log.
Comment: if try whit "sostituisci(" 1 2 3 4 5 "), the method is true
Comment: Why as you saving the number in an NSString in the first place?
Answer: I suspect that the space character in your string is not really a space.  Try adding this after NSLog(string) to see what the unicode scalar values are for the characters in your string:
for uni in (stringa as String).unicodeScalars {
    println("\(uni) = \(uni.value)")
}

The expected output for "(327) 124-3503" is:
( = 40
3 = 51
2 = 50
7 = 55
) = 41
  = 32
1 = 49
2 = 50
4 = 52
- = 45
3 = 51
5 = 53
0 = 48
3 = 51

From your comment, your space has value 160 instead of 32.  You could remove that with:
numero = stringa.stringByReplacingOccurrencesOfString(String(Character(UnicodeScalar(160))), withString: "")

Comment: the log when I use your method:

HappyRicarica[33497:3132714] (327) 124-3503
( = 40
3 = 51
2 = 50
7 = 55
) = 41
  = 160
1 = 49
2 = 50
4 = 52
- = 45
3 = 51
5 = 53
0 = 48
3 = 51
Comment: I know you aleady accepted an answer.  I just wanted you to know why your original code wasn't working.  Your space wasn't really a space (ASCII 32) but it had a value of 160 instead.  See the update above with how to replace that.  The answer you accepted is really nice, so I'd leave that as the accepted answer.
Answer: update: Xcode 7.2 • Swift 2.1.1
extension String {
    var numbersOnly: String {
        return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890")
            .invertedSet)
            .joinWithSeparator("")
    }
    var numbersExempt: String {
        return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890"))
            .joinWithSeparator("")
    }
    var charactersOnly: String {
        return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet).joinWithSeparator("")
    }
    var charactersExempt: String {
        return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")).joinWithSeparator("")
    }
    func keep(keepIt: String) -> String {
        return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: keepIt).invertedSet).joinWithSeparator("")
    }
    func exclude(excludeIt: String) -> String {
        return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: excludeIt)).joinWithSeparator("")
    }
}

let phoneNumber = "+1 (555) 555 - 5555".numbersOnly
print(phoneNumber) // "15555555555"

let excludePlusMinus = "+1 (555) 555-5555".exclude("+-") // "1 (555) 5555555"
let keepWhatever = "+1 (555) 555-5555".keep("()-+") //  "+()-"

you can also use your function to subtract only spaces with some adjustments. Try like this:
func sostituisci(stringa: String) -> String {
     return stringa.stringByReplacingOccurrencesOfString(" ", withString: "")
}

sostituisci("1 234 567 8901")   // "12345678901"

or like an extension:
extension String {
    var sostituisci: String {
        return stringByReplacingOccurrencesOfString(" ", withString: "")
    }
}
let phoneNumber2 = "1 234 567 8901".sostituisci

Comment: Upvoted, very helpful in understanding the power of componentsSeperatedByCharactersInSet.
Answer: did you try :
let str = "XX XX XX XX XX"
    let separated = str.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    let finalStr = "".join(separated)

Comment: if you replace `let finalStr = "".join(separated)` with `let finalStr = ("" as String).join(separated)` ?
Comment: error in line:
let finalStr = "".join(separated)   -> "'String' is not identical to 'AnyObject'
Answer: NSString is not String, so you should use:
numero = ((numero as String).stringByReplacingOccurrencesOfString(" ", withString: "") as NSString)

string replace phone number iOS swift


$\int_2^\infty \left(\frac1{x\log^2x}\right)^p\mathrm dx$ diverges for p>1

Question: I see this question and the answer by joriki.
However I cannot understand joriki's argument that $$\int_2^\infty \left(\frac1{x\log^2x}\right)^p\mathrm dx$$  diverges for p>1.
So I try to show that by myslef, by finding a function $f(x)<\left(\frac1{x\log^2x}\right)^p$ for sufficiently large $x$ and $\int f(x) dx=\infty$, but it is difficult.
Please help me to understand that argument or give me some hints.
Comment: This is **NOT** what @joriki wrote. Please read more carefully.
Comment: Oh, I got it. I was a moron.....
Comment: A reformulation of the question seems mandatory.
Answer: For $p>1$, the integral converges, since $$\dfrac1{x\log^2(x)} < \dfrac1x\quad\text{for }x>e$$ and $$\int_2^{\infty} \dfrac{dx}{x^p} = \dfrac1{(p-1)2^{p-1}}$$
Answer: Meanwhile I was working the problem came user141421's answer which shows that, for $p \gt 1$, $$I(p)=\int_2^\infty \left(\frac1{x\log^2x}\right)^p\mathrm dx$$ converges. Just for your curiosity, I give you a few values of this integral $$I(1)=\frac{1}{\log (2)}\simeq 1.4427$$ $$I(2)=\frac{\log (2) \left(2 \log ^2(2) \text{Ei}(-\log (2))-1+\log (2)\right)+2}{12 \log
   ^3(2)} \simeq 0.384129$$ $$I(3)=\frac{2 \log ^2(2) \left(16 \log ^3(2) \text{Ei}(-\log (4))+1+\log (2) (\log
   (4)-1)\right)+6-\log (8)}{120 \log ^5(2)} \simeq 0.235996$$ For higher values of $p$, a CAS gives long formulas and I shall just report numerical values for the next integrals $$I(4) \simeq 0.174447$$ $$I(5) \simeq 0.140805$$ $$I(6) \simeq 0.119689$$ $$I(7) \simeq 0.105277$$ $$I(8) \simeq 0.0948764$$ $$I(9) \simeq 0.0870681$$


Ofuscando código Java com ProGuard

Question: Problema:
Estou recebendo warnings do ProGuard e com isso não consigo ofuscar meu .jar, é a primeira vez que recebo estes avisos e com isso não consigo finalizar a ofuscação.

Imagem com detalhes do problema:

Observação:
Aplicação está funcionando, dentro do .jar estão todas as API's (dependências) necessárias, porém o ProGuard me dá esses warnings.
Comment: Tem certeza que a ofuscação não é finalizada? Warnings não deveriam interromper a ofuscação.
Comment: Tenho sim, Embora seja um "Warnings" recebe a seguinte mensagem "Please correct the above warnings first". Ela está na imagem.
Comment: "21 referências não resolvidas para classes e interfaces. Talvez você deva adicionar bibliotecas ou atualizar suas versões. Se seu código funciona sem as classes faltantes, você pode suprimir os alertas com a opção '-dontwarm'"
Answer: Isso ocorre pois o apontamento padrão do Proguard faz menção somente para a lib rt.jar, faça o apontamento manual para a lib jce.jar que tudo estará resolvido.
Comment: vou testar, brother.
Comment: Devo apontar para o `rt.jar` e `jce.jar`? Seria de mais perguntar o que é `rt.jar` e `jce.jar`? O `rt` tenho uma noção, mas se poder ajudar. agradeço.
Comment: Tive que usar os dois, se usar `jce.jar` é `Warnning ` quase infinito. haha @Petter
Answer: O erro tá te dando a solução:

"21 referências não resolvidas para classes e interfaces. Talvez você
  deva adicionar bibliotecas ou atualizar suas versões. Se seu código
  funciona sem as classes faltantes, você pode suprimir os alertas com a
  opção '-dontwarm'"
Comment: Acho que isto cabe mais como comentário, não achas?
Comment: Interessante, mas onde posso passar esse parâmetro, estou utilizando a interfase gráfica do proGuard em minhas buscas não encontrei um lugar passar ele.

Ofuscando código Java com ProGuard


Cannot open the Windows Search Pane in WPF: Element not found. (Exception from HRESULT: 0x80070490)

Question: I have a WPF project with only these changes from an empty project:

This line added to the .csproj: <TargetPlatformVersion>8.0</TargetPlatformVersion>
A reference added to Windows
A button with a Click handler executing this: SearchPane.GetForCurrentView().Show("test");

When I click the button, I have an exception when calling .GetForCurrentView():
Element not found. (Exception from HRESULT: 0x80070490)
What can I do to diagnose it and make it work?

Details:
Note that I have no breakpoints, I'm running on Windows 8.1 and I already tried:

Adding await BackgroundExecutionManager.RequestAccessAsync(); before;
Adding a 1000ms delay;
Referencing System.Runtime, System.Runtime.WindowsRuntime and System.Runtime.InteropServices.WindowsRuntime

I know I can use SendKeys to send Win + S + (query), but this is exactly what I'm trying to replace since at the moment I try to open the search charm, the Ctrl key will be down (launched by a shortcut).
Comment: Linking question http://stackoverflow.com/questions/12742558/search-pane-element-not-found-exception-in-win-8-app since it is the same error, but this question is with WPF
Comment: You cannot use WinRT classes in a WPF app, this is supposed to fail.
Comment: @HansPassant to you have a reference? There are articles on doing this on MSDN blogs (e.g. http://blogs.msdn.com/b/eternalcoding/archive/2013/10/29/how-to-use-specific-winrt-api-from-desktop-apps-capturing-a-photo-using-your-webcam-into-a-wpf-app.aspx)
Comment: Actually, I found the reference myself: WinRT is supported, but SearchPane specifically is not supported... http://msdn.microsoft.com/en-us/library/windows.applicationmodel.search.searchpane.aspx
Answer: Even though some WinRT API functions can be used in a desktop app, SearchPane cannot.
MSDN pages show whether each individual API function can be used or not in Desktop apps: http://msdn.microsoft.com/en-us/library/windows.applicationmodel.search.searchpane.aspx


In Berkson's paradox, is $\beta_1 = 0$ or $\ne 0$?

Question: There is "a general phenomenon known as Berkson's paradox (Berkson, 1946), whereby observations on a common consequence of two independent causes render those causes dependent. For example, the outcomes of two independent coins are rendered dependent by the testimony that at least one of them is a tail" (Pearl, 2009).
$$
y = \beta_0 + \beta_1x_1 + \beta_2x_2 + \epsilon
$$
If (a) we make a linear regression model as above in which $x_2$ is a common consequence of independent causes $y$ and $x_1$ and (b) these latter two are rendered dependent by observations on $x_2$:

Is $\hat\beta_1 \ne 0$? Why?

"Yes, because that is what Pearl must mean by "rendered dependent."

Is the true value of $\beta_1 = 0$? Why?

"Yes, because that is what Pearl must mean by "independent causes."

*Or, do we not have enough information?
*Or, is Berkson's paradox not applicable (e.g., to a linear regression model with a continuous $y$)?
Berkson, J. (1946). Limitations of the application of fourfold table analysis
to hospital data. Biometrics Bulletin 2, 47–53.
Comment: The misunderstanding on which this question is based is addressed in your subsequent question at http://stats.stackexchange.com/questions/141607/in-linear-regression-what-does-beta-1-0-really-mean.
Comment: @whuber: Sorry, I hope latest edits are clear. I just want to be clear that Berkson's Paradox requires the true $\beta_1 = 0$. This is in part because I wondered if NeilG's answer here was in fact an example of Berkson's Paradox or something else (https://stats.stackexchange.com/questions/141309/does-rejection-of-null-hypothesis-in-multiple-regression-entail-causation). If it is a BP example, then I know how to classify it; if not, I need to learn something from NeilG.
Comment: You seem to be thinking that to say the true value of $\beta_1\neq0$ implies $x_2$ causes $y$. It doesn't; it implies only a correlation. If the true value of $\beta_1\neq0$ because $y$ & $x_1$ have causal effects on $x_2$ then $\hat\beta_1$ is a consistent estimator of the non-zero $\beta_1$ (it approaches it closer & closer as the sample size increases).
Comment: Think you should specify the regression model even if your notation's fairly standard, to avoid confusion.
Comment: @whuber: Sorry I don't see my misunderstanding yet. My Berkson's paradox question seems to me a special case where I think "rendered dependent" means $\hat\beta_1 \ne 0$ but I want to know if CV community thinks it means $\beta_1 \ne 0$ or something else. Other question I hope is more general theory (of which Berkson's is a special case) and thus I hope they illuminate rather than duplicate each other. But perhaps someone has a simple answer to $\beta_1 = 0$ question that will make Berkson's question obvious.
Comment: In that case I apologize for not understanding your question at all.  Stripped of some distracting and irrelevant details, it asks (in bold) "if my estimate of the true (but unknown value) of a model parameter $\beta_1$ is nonzero, is the true value of $\beta_1$ zero or not and why?"  That is so trivial to answer that I'm sure I'm misunderstanding it, but I don't see any other interpretation.  Could you clarify what you are trying to ask?
Comment: @Scortchi: Hmm, definitely does not imply direction of causality. But, my big misunderstanding may be this: the true $\beta_1$ for $x_1$ is linked to the model, not the true data generating process for $y$? If that is true, thank you for clarification!
Answer: Your question is quite similar to this one Which OLS assumptions are colliders violating?
I suggest you to see that one too and links therein.
My first point is that if you want to follow Pearl's Theory you have to use related rules. Probably confusion come from that. Therefore, first of all, you must distinguish clearly structural equations/parameters from regression one.
The structural causal model (SCM) you are interested in seems me
\begin{aligned}
Y&=u_Y \\
X_2&=\beta_1X_1+\beta_2Y+u_{X_2} \\
X_1&=u_{X_1}
\end{aligned}
so that $X_2$ is a collider: $X_1\rightarrow X_2\leftarrow Y$.
structural errors can be considered the exogenous variables in the system and we assume them as zero mean rvs independent each others. Note that one implication of that is: $E[u_{X_2}|X_1,Y]=0$.
Note that, in general, the SCM encode (explicitly) all causal assumptions made by the researcher. In this case the SCM is consistent with Berkson's paradox.
Now your question is as follow: if you perform this regression
$ Y=\theta_0 + \theta_1X_1+\theta_2X_2+\epsilon $
what you have to expect as value for $\theta_1$?
Here $\theta_1$ stay for your $\hat\beta_1$. I do not consider hat symbol for $\theta$ because we can avoid sample/population difference and my notational distinction help us.
Now the answer: you have to expect $\theta_1 \ne 0$
It is so because $X_1$ and $Y$ are marginally independent but become dependent conditioning on collider ($X_2$). Note that $\theta_1$ do not have any causal role, do not identify any causal parameter. This is why, in general, to control for collider is not a good idea.
Indeed if you compute
$ Y=\theta_3 + \theta_4X_1+\epsilon_2 $
$\theta_4$ identify the causal effect of $X_1$ on $Y$, in fact
$\theta_4=0$


What does "completed x-for-y passes" mean?

Question: What does it mean to say that a quarterback completed x-for-y passes? That is different than the average yards per rush or yards per completion, right?
Background:
One article states "During the game [Tebow] threw for 316 yards, [Tebow] yards per completion were 31.6, [Tebow] yards per rush were 3.16".
A second article, states that Tim "Tebow's stats for the first three quarters. He completed [...] 3-for-16 passes".
A third article states "Ben Roethlisberger's second-quarter interception, which led to a Matt Prater field goal and a 17-6 Broncos lead, came on third-and-16."
What I ultimately want to know is whether the statistic "3-for-16 passes" of the second article and/or the statistic "third-and-16." are included in the statistics of the first article. Are those different statistics (that just look so similar) or is there an overlap of information? With "overlap of information", I mean that one statistic can be unambiguously calculated from the other.
Going by what ATCOlogy wrote, I would have to calculate 316 / 16 = 19.75, which would not match up with the "yards per completion were 31.6". However, the first articles says "3-for-16" for the first three quarters, so maybe "316" and "31.6" were for the whole game and my calculation is off.
Comment: Could you give an example of where you have seen this specific phrasing "x-for-y passes" used? The normal phrases would be "x **of** y passes" or "x passes **for** y yards".
Comment: @PhilipKendall: Of course. In https://bleacherreport.com/articles/1019128-tim-tebow-and-john-316-scholars-new-sighting-from-the-broncos-vs-bears-game, it is written that Tim "Tebow's stats for the first three quarters. He completed [...] 3-for-16 passes". In https://www1.cbn.com/cbnnews/entertainment/2018/january/tim-tebow-rsquo-s-nbsp-shocking-story-about-john-3-16-lsquo-coincidence-rsquo-goes-viral it is written "During the game [Tebow] threw for 316 yards, [Tebow] yards per completion were 31.6, [Tebow] yards per rush were 3.16".
Comment: What I ultimately want to know is whether the statistic of the first article is included in the statistics of the second article. Going by what @ATCOlogy wrote, I would have to calculate 316 / 16 = 19.75, which would not match up with the "yards per completion were 31.6". However, the first articles says "3-for-16" for the first three quarters, so maybe "316" and "31.6" were for the whole game and my calculation is off.
Comment: Finally, https://www.espn.com/nfl/story/_/page/10spot-divisional/tim-tebow-phenomenon-gets-eerie--adam-schefter-10-spot writes "Ben Roethlisberger's second-quarter interception, which led to a Matt Prater field goal and a 17-6 Broncos lead, came on third-and-16." is "third-and-16." here another, different statistic or is this included in one of the above statistics.
Comment: Please edit all this into your question; at the moment, you're getting contradictory answers because it's not entirely clear what you're asking.
Comment: @PhilipKendall: Of course, thanks for the review! I have done that. Please give further corrections if necessary :-).
Comment: @Make42 The box score from the game in the first article is here: https://www.espn.com/nfl/boxscore/_/gameId/320108007 It shows that Tebow completed 10 passes on his 21 attempts (10-for-21). 316 yards divided by 10 completions is 31.6. The 3-for-16 passing performance in the first three quarters from the second article is talking about a different game at a later date.
Answer: It indicated the number of passes completed and the total pass yards. For example: QB completed 20 passed for 300 yards. So in a sense it's a more explicit way of describing the yards per completion.
You may also hear a more verbose version like this, completed 20 of 30, for 300 yards. In this case the pass attempts are also included.
Comment: I read about a game in an article that a QB "completed 1-for-23 passes in the first three quarters" and in a different article about the same game that the QB had an "average of 12.3 yards per completion and average of 1.23 yards per rush". Are those three different statistics (that just look coincidentally so similar) or is there an overlap of information? With "overlap of information", I mean that one statistic can be unambiguously calculated from the other.
Answer: Using the quarterback stats from this game as an example, let's break this down.
Josh Allen, the Bills QB, went 24 for 42 in this game. That means he threw 42 passes, and 24 of those passes were completed (that is, caught by receivers on his own team). He threw for 253 passing yards, and since we know he completed 24 passes, his yards per completion is 253 divided by 24, or about 10.54 yards per completion. Yards per rush is unrelated to passing, but we can calculate that too: Allen attempted 10 carries, and gained a total of 78 rushing yards doing so. 78 divided by 10 is 7.8 yards per rush.
Let's check the stats for Jared Goff, the Lions QB. He threw 37 passes, completed 23 of them (23 for 37), accumulating 240 passing yards, or  about 10.43 yards per completion. Goff didn't attempt any carries, so we can't calculate yards per rush for him.
This use of "x-for-y" is common in several American sports (a baseball hitter who gets 1 hit in 4 at-bats goes 1-for-4, a basketball player who hits 8 shots out of 11 tries went 8-for-11, etc.)

Regarding the article excerpts:

The first article refers to a statistical coincidence (it's even in the title of the article!) that occurred with Tim Tebow. Tebow was a famously devout Christian, and John 3:16 is a significant Bible verse. According to the article, several of his stats and stats about a specific game generally ended up being 316, 3.16, 31.6, or something similar. The point of the story is that most of those stats are unrelated to each other; none of them can be directly calculated from another. (Pass yards and yards per completion ARE related but you can't calculate yards per completion without also knowing the number of completions.)

The second article is using my above definition of 3 for 16: 3 completions out of 16 attempts. (This is, for what it's worth, a subpar performance for a quarterback in most circumstances.)

The third article is referring to down and distance. In American football, teams have four chances ("downs") to gain ten yards from where they started. 3rd and 16 means a team is on its third of four chances, and need to gain 16 yards to reset those chances. It's not related to passing statistics.
Comment: That sounds very different than what @alamoot wrote, namely " completed x passed for y yards", while you say "completed x passes out of y pass attempts". So who is right? Or what do I misunderstand?
Comment: American sports, at least, usually use this sense for "x-for-y". Cricket has a usage more similar to alamoot's suggestion, where a bowler who gave up 50 runs and recorded five outs "bowled 5 for 50".


Need to call jquery function or vice versa

Question: I have a jquery function that controls some css that sets state to active or not. It runs on a click event.  I need to have a similar function run when a php function runs (when the user searches with a form). The search term goes through a php function which will match the term with an id.  How can I set the state to active with the php function?
Here is a link to a test area
http://vtour.dev4.webenabled.net/tester/index.html
If you click an area, the selection remains active.  if you type a name in the lavender search box, and click the search icon, the  corresponding area does not become selected.
(attaching the search functionality file.  i know there is a bunch of junk in there but the section that corresponds to this example starts around line 149
The small lavender box next to the input line is the click/search icon
Thank you
Comment: have you considered either using jquery, or not using jquery? the mixture of code must become confusing at some point; continuity is +1. Also..you call jQuery twice in your site. which plays an issue. It also make look as if you call searchTerm.value, but you never pass `searchTerm` to function `getInfo()`, which should probably be function `function getInfo(searchTerm)`. and even if you dont want to pass it over, you would still need to declare `var searchTerm = $('input#searchTerm')` somewhere for this to begin to work.
Comment: I'm working on someone else's project that was left mid stream. PHP is nor my forte nor is jquery. Since this is working except for the sctive state, I'd like to attempt a fix
Answer: You can't do this from PHP, you do everything through Javascript (and see Ohgodwhy's comment, especially the note about using jQuery or not using jQuery - you should use .ajax() or .post() for example).
To do it, the AJAX would return some flag to tell Javascript what blocks to turn on/off, as well as the text response. You can wrap all this up in a JSON object.
<?php

$returnArray = array('html' => 'HTML TO DISPLAY', 'blocks'=>array(1,3,4));
echo json_encode($returnArray);

?>

and in javascript use the JSON object elements to display the text, and then also turn on/off the right blocks. This bit will be easier in jQuesry as it handles the JSON object for you, so you'd only need response.html for the html bit, and response.blocks for the blocks.
Answer: You can execute a javascript function by outputting a html script tag.
ie.
<?php
echo "";
?>

So you could technically drop that into the response from your FetchData.php - but if it were me, I would do it all with jQuery:
$('#woodward-title-search-button').click(function() { //on button click
    var term = $('#searchTerm').val(); //the search term
    $('#room-'+term).css('background','red'); //or more nicely: .addClass('highlighted');
    //load the response of fetchdata into #myDiv
    $('#myDiv').load('FetchData.php?searchTerm='+term);
});

I would suggest communicating with your PHP in json and providing an ID of some kind to better target your div.. but this should work as a down and dirty solution.
Comment: Hi Chris, My problem with your suggestion is that the search term does not correspond to the room.  The routine is taking the search term and finding the id in the XML file.
Comment: Then I would suggest sending the ID back with your HTML as a seperate entity as Robbie showed you:
` 'The html for room 101 to return', 'id'=>'room-101');
echo json_encode($returnArray);
?>`

and then on button click:

`$.getJSON('FetchData.php?searchTerm='+term, function(data) {
  $('#'+data.id).css('background','red');
  $('#myDiv').html(data.hmtl);
});`


Find an element $a \in A_6$ that is not of the the form $b^2$ for any $b\in S_6$

Question: Find an element $a \in A_6$ that is not of the the form $b^2$ for any $b\in S_6$.
My professor gave the hint that we should consider the disjoint cycles of $A_6$.
So elements in $A_6$ will have either 0 or 2 disjoint two cycles but I'm not sure how i should use this to go about finding $a$.
Any guidance would be appreciated.
Answer: First step is to find all possible cycle structures for elements of $A_6$;

$5$-cycle,
$4$-cycle times $2$-cycle,
$3$-cycle,
product of two $3$-cycles,
product of two $2$-cycles,
identity element.

Second step is to think about which of these are, and which aren't, squares in $S_6$.


How do you keep a div size static even if the font size of the text inside it changes

Question: See my demo below. When you click the buttons, the font size changes and this is making the div box grow and shrink. I don't want the box size to change.
How do I prevent this?

$('#button-plus').click(() => {
 var currentFontSize = parseInt($('.main > span').css('font-size'));
 $('.main > span').css('font-size', currentFontSize + 5 + 'px');
});

$('#button-minus').click(() => {
 var currentFontSize = parseInt($('.main > span').css('font-size'));
 $('.main > span').css('font-size', (currentFontSize - 5) + 'px');
})
.main {
  text-align: center;
  width: 200px;
  max-width: 200px;
  overflow: overflow;
  padding: 10px 5px;
  border: 2px solid #bbb;
}

.main > span {
  font-size: 12px;
}

  Some Text

<button id="button-plus">+</button>
<button id="button-minus">-</button>
Comment: `overflow: overflow` is not valid css. If you set `overflow: auto` and give the div an explicit height, you should get the outcome you desire.
Comment: @dillon Thanks! I was playing with it. It should have been "hidden"
Answer: It seems you are trying to create a fixed width and height for your div box. You can simply fix this by including a height to your .main class.
.main {
  text-align: center;
  width: 200px;
  height: 20px; // <-- specify a height.
  max-width: 200px;
  overflow: overflow;
  padding: 10px 5px;
  border: 2px solid #bbb;
}

.main > span {
  font-size: 12px;
}

Answer: Not totally clear what behavior you are expecting.
One approach might be take the current height on page load and apply it inline so it becomes fixed height using:
$('.main').height((_,curr) => curr)

Another alternative is using css flex box rules

$('#button-plus').click(() => {
 var currentFontSize = parseInt($('.main > span').css('font-size'));
 $('.main > span').css('font-size', currentFontSize + 5 + 'px');
});

$('#button-minus').click(() => {
 var currentFontSize = parseInt($('.main > span').css('font-size'));
 $('.main > span').css('font-size', (currentFontSize - 5) + 'px');
});

$('.main').height((_,curr) => curr)
.main {
  text-align: center;
  width: 200px;
  max-width: 200px;
  overflow: auto;
  padding: 10px 5px;
  border: 2px solid #bbb;
}

.main > span {
  font-size: 12px;
}

  Some Text

<button id="button-plus">+</button>
<button id="button-minus">-</button>
Answer: $('#button-plus').click(() => {
 var currentFontSize = parseInt($('.main > span').css('font-size'));
 $('.main > span').css('font-size', currentFontSize + 5 + 'px');
});

$('#button-minus').click(() => {
 var currentFontSize = parseInt($('.main > span').css('font-size'));
 $('.main > span').css('font-size', (currentFontSize - 5) + 'px');
})
.main {
  text-align: center;
  width: 200px;
  height: 400px;
  overflow: overflow;
  padding: 10px 5px;
  border: 2px solid #bbb;
}

.main > span {
  font-size: 12px;
}

  Some Text

<button id="button-plus">+</button>
<button id="button-minus">-</button>


Wrong results/pagination when ignoring tags

Question: Steps to reproduce:

add some ignore tags (for me all Magento 2 related)
go to unanswered section
set X per page

Expected:

show X per page

Currently:

it shows X minus ignored questions (2 instead of 15)
Answer: This is status by design and won't be fixed (see linked Meta.SE question for details)
Comment: Thanks. According to this comment: "Darn, I thought we'd patched that once... will look – Marc Gravell♦ Mar 26 '12 at 6:18" it will be fixed sometime ...


Too many data replication technologies in environment

Question: It is possible to configure remote data replication at many layers of the storage stack. Some examples to explain what I mean by layers:

Physical Volume Layer (TruCopy, SRDF/MirrorView, SnapMirror)
Virtual Server Layer (vReplicator, Veeam)
Logical Volume Layer (VVR, AVS)
Filesystem Layer (Rsync, ZFS Send/Recv)
Application Layer (Data Guard, MySQL/PostgreSQL Replication, AD Replication)

Replication at each layer has a unique value proposition but it would be crazy to use them all. My particular problem is the proliferation of different solutions; I'd like to standardize on one or two solutions in order to keep down license costs, complexity, and expertise requirements.
My question is: ignoring the individual product examples, which layer or combination of layers of replication provide the most value in a typical corporate environment, and which are becoming more valuable?
Possible metrics include ease of administration, availability of expertise, protection from data corruption, recovery time/complexity in a DR scenario, reduction in planned outage windows, application performance, application flexibility, and anything else that might be valuable.
This is a question I encounter often as a system administrator so I would appreciate any advice.
Answer: Which solution is better suited to a given scenario strongly depends on the applications and data involved, there is no "global" approach that can work everytime, everywhere.
There really are too many different scenarios involved. Some examples:

Active Directory domain controllers are designed to work as a multi-master, replicated, distributed database; and you also need to have local DCs in a WAN setup, because domain-joined Windows machines need to have a DC available in order to work properly. At the same time, with AD you wouldn't benefit at all from having a lower-level replication, at the virtual server layer or at the physical storage layer, as you can't have a DC "mount" a database copied from another one, and you can't either start a cloned DC and expect it to work (don't even try to do that, USN rollback is nasty).
For a file server, the exact opposite is true: while there are application-level replication technologies (DFS in Windows), for big amounts of data a storage-level replication is probably the best approach.
Now, let's say you are using Exchange; recent Exchange systems (2007-2010) are designed with transactional database replication in mind, and this is the only officially supported approach; you actually can copy an Exchange database and mount it on another Exchange server (that's called "database portability"), so storage-level replication could be made to work... but it's a lot more painful, and moving users to such a server requires heavy reconfiguration. Also, while in the two aforementioned scenarios there actually is a point in having local copies of the data in multiple places (AD is needed everywhere, and users in different offices could need to access the same file server data), for Exchange this only makes sense in a disaster-recovery scenario, because in normal operation each user only accesses his/her own mailbox, which can only be active on a single server at a time.
For various database systems, again, this could work both at the application level or at any underlying level; but this strongly depends on the application: if you need to modify data in multiple places (as opposed to only read them), there's no way storage replication can merge conflicting copies, and you will need to let your DBMS handle that.

Each technology has its own benefits and use cases; there really is no "one size fits all" approach.
Comment: Thanks, great answer. I don't mind so much that each application is different, because managing a particular app is a self-contained skillset, whereas coordinating data up and down the stack is much harder! Perhaps VM replication has a place as long as it is seen as a pure DR technology which is not a substitute for application-specific replication.
Comment: Thanks for your comment. Despite your pessimism, to me your answer sounds quite positive: that in most cases replication can be handled best at the application layer. File servers need to be handled differently, but the trend for file servers is towards NAS appliances anyway, i.e. towards simplified management with well-documented DR features, so this is not such an issue. I'm keen to hear any more exceptions.
Comment: @Tom, I didn't mean by any means to appear pessimistic :-) I totally agree on handling data replication at the application level *for most cases*... but this makes all those new and great lower-level replication technologies seem quite useless, hence what could be perceived as "pessimism". Also, each application handles its replication howewer it sees fit, so there is absolutely no standardization here.
Comment: @Tom: absolutely agreed, VM and SAN replication are great for DR (if you have enough bandwidth to the DR site, of course).
Answer: I've so far considered two options. The over-arching idea of both is to assign responsibility for replication to one team only: either the system administrators or the application administrators. With only one team involved, you decrease the complexity of the system and the risk.
Standardize on Virtual Server Layer Replication
By configuring replication at the virtual server layer only, you can treat the operating system and any applications running in it as a black box. The system administrators are in control.
Advantages:

The DR procedure for all applications is identical: stop the replication, start the DR virtual servers, and ask the different application teams to confirm that all is well.
It is easy to confirm that you have complete coverage of all data.
It is easy to plan server/storage maintenance because the involvement of the application teams is minimal.

Disadvantages:

The DR servers are idle the majority of the time: a possible waste of server resources.
It can be difficult to test DR without a full failover given that IP addresses match Prod.
Replication is immediate, so if there is data corruption in Prod it is propagated immediately to DR.
It may be difficult to use this method to clone to Dev/Test.
Can't be used with systems that don't run well in a VM.

Can be used in combination with physical volume layer technologies to enhance performance of replication (while still being managed from the VM software).
Standardize on Application Layer Replication
By configuring replication at the application layer only, you can treat the server, storage and the operating system as a black box. The application administrators are in control.
Advantages:

Many applications can run in a multi-master or master-slave mode to take advantage of all server resources.
Many applications can transmit changes in a concise format, saving on bandwidth and improving performance.
Some applications can delay the application of changes to prevent corruption from being propagated immediately at DR.
It is relatively easy to sever replication and re-configure servers as Dev/Test.

Disadvantages:

Each application team must configure replication in their own unique way.
Not all applications support this kind of replication, so there needs to be a fall-back option.

Can be used in combination with filesystem layer technologies to support applications without the ability to replicate.
Comment: Your implicit assumption here is that system/storage administrators and application administrators are two independent units working incoherently. While this might be the case, I'd expect an organisational change to reduce the friction between these two units to yield a better result than creating an overly fixed and inflexible policy about replication. In fact, I'd think that using *both* - replication at storage or virtualization layer along with application layer replication - would give you the greatest flexibility and the richest featureset - of course at the cost of additional complexity
Comment: @syneticon-dj: Yes there is a cost to flexibility and features. I've seen convoluted DR procedures which  require action by the storage guy, network guy, sysadmin, dba and appserver guy. DR testing takes hours and never quite works as planned. Regarding oranisational change: these complex systems are often designed by one superstar who knows the whole stack. Then that person leaves and it is simply impossible to find someone with the breadth of skill to understand it all. If no-one knows how to use and fix it, it's worse than useless.
Comment: Ah, now as you narrow down the problem set to disaster recovery, it gets much more practical indeed. as desaster recovery has a clear goal of a minimized time-to-recovery, I would agree with you that using just one technology and simplify the processes is the way to go.
Comment: @syneticon-dj: Cheers. For the record, here's what I've learned. Application layer replication is almost essential because it is the only clean way of achieving many functionality goals. It may also be sufficient by itself for DR purposes. A lower-layer technology like VM replication or volume replication of entire servers may be added to make a full DR failover quicker and easier and to ensure complete data coverage. It gets painful when you mix strategies and try to combine lower-layer technology with application migration.


Hook menu - title arguments

Question: I have those menu elements declared in hook_menu function:
$items['submission/%/id/%'] = array(
    'title' => 'View submission',
    'title callback' => 'fr_form_view_submission_page_title',
    'title arguments' => array(3),
    'page arguments' => array(1, 3),
    'page callback' => 'fr_form_node_object_id',
    'access arguments' => array('content access'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 100,
  );

  $items['submission/%/id/%/view'] = array(
    'title' => 'View submission',
    'title callback' => 'fr_form_view_submission_page_title',
    'title arguments' => array(3),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['submission/%/id/%/edit'] = array(
    'title' => 'Edit submission',
    'page arguments' => array(1, 3, 4),
    'page callback' => 'fr_form_node_object_id',
    'title callback' => 'fr_form_edit_submission_page_title',
    'title arguments' => array(3),
    'access arguments' => array('content access'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );

As you can see the first menu item has a fr_form_view_submission_page_title() function to set the title. And the function looks like this:
function fr_form_view_submission_page_title($id) {
  return t('View submission ID: @id', array('@id' => $id));
}

Second item makes the first one default.
Third menu item has a title callback function which looks like this:
function fr_form_edit_submission_page_title($id) {
  return t('Edit submission ID: @id', array('@id' => $id));
}

When I go to page /submission/10/id/1 I get the result. Two tabs next to each other with text on it:
first tab: View submission ID: 1
second tab: Edit submission ID: 1
And the page title is: View submission ID: 1
And if I go to the edit tab (/submission/10/id/1/edit) I get exacly the same, so:
first tab: View submission ID: 1
second tab: Edit submission ID: 1
And the page title is: View submission ID: 1
What I want to achive is to have tabs always signed:
first tab: View submission
second tab: Edit submission
And the page title depending on path, so for /submission/10/id/1 I should get:
View submission ID: 1
And for /submission/10/id/1/edit I should get:
Edit submission ID: 1
Comment: Hi, David. Hopefully someone else can confirm but I don't think it's currently possible to set a different page title using `hook_menu()`. You may have to `drupal_set_title()` inside your page callback instead, perhaps retrieving your arguments from `$_GET['q']`.
Answer: You can use single title callback by passing two arguments :
'title arguments' => array(3, 4),

and use same callback for both function :
function fr_form_view_submission_page_title($id, $type = 'view') {
  $type = ucfirst($type);
  return t('@type submission ID: @id', array('@type' => $type, '@id' => $id));
}

Hook menu - title arguments


Como posso colocar caracteres no meio de uma string, sem sobrescreve-la em c?

Question: Como posso colocar caracteres no meio de uma string, sem sobrescreve-la?
Preciso cada vez que encontrar um espaço, adicionar mais 3 espaços:
TESTE TESTE TESTE

E transformar pra isso:
TESTE   TESTE   TESTE

Tentei fazer assim, ele até adiciona os espaços, mas esta sobrescrevendo o resto da string...
Comment: As respostas abaixo são complementares, uma diz pra usar `fgets` em vez de `gets` (correto, mas o resto da resposta vc pode ignorar porque não faz diferença - veja o comentário deixado lá), e a outra mostra como usar funções já existentes (`strtok`, etc), mas caso não possa usar essas funções (talvez seja um exercício que tenha essa restrição), a ideia de ter 2 contadores seria mais ou menos assim: https://ideone.com/G0n1b4 (ainda não é muito robusta porque vc deveria fazer uma conta pra alocar espaço suficiente - no pior caso, em que `s` só tem espaços, tem que alocar o triplo do tamanho)
Comment: Basicamente, vc precisa de 2 contadores: um pra posição da string `s` e outro pra posição da string `teste` (não pode usar o mesmo em `teste[i++]`, já que quando encontra um espaço, `i` deve andar apenas 1 casa, enquanto na string `teste` vc anda mais posições)
Answer: Uma possibilidade é utilizando as funções do arquivo de cabeçalho string.h que define várias funções para manipular arrays de caracteres.
Use a função strtok() para dividir uma string em substring a cada ocorrência de um delimitador. Em uma primeira chamada, a função espera uma string C como argumento, cujo primeiro caractere é usado como local inicial para procurar delimitadores. Em chamadas subsequentes, a função espera um ponteiro nulo e usa a posição logo após o final do último delimitador como o novo local inicial para varredura.
Use a função strncat() para juntar as substrings obtidas com strtok() mais os espaços:

Esse código não faz a verificação de buffer overrun.
Esse código não testa entrada vazia.

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main(void) {
    char str[] ="TESTE TESTE TESTE";                  //Declara string de entrada.
    char result[256];                                 //Declara uma porção de memória para conter o resultado.
    memset(result,'\0',256);                          //Prepara a memória que conterá o resultado.
    char * pstr = strtok(str, " ");                   //Quebra a entrada na primeira ocorrência do caractere espaço.
    do
    {
      strncat(result, pstr, (unsigned)strlen(pstr));  //Adiciona ao resultado a  substring resultante da quebra da entrada.
      pstr = strtok (NULL, " ");                      //Quebra a entrada na próxima ocorrência do caractere espaço.
      if (pstr == NULL) break;                        //Se não houver outra sbstring abandona o laço.
      strncat(result, "   ", 3);                      //Adiciona a três espaços ao resultado
    } while (true);
    printf ("%s\n",result);
    return 0;
}
//TESTE   TESTE   TESTE

Teste o exemplo no ide.one
Answer: o gets é uma função que está em desuso, já faz tempo,  melhor usar o fgets,
fgets(s , sizeof( s )  , stdin);

o finalizador de string é o valor zero  0,
for(int i=0; s[i]  !=0;  i++);

e não precisa das aspas nem da barra , coloque no final da string  teste , depois de preenchida
teste[w] = 0;

o loop for para colocar os espaços, esta indo ate enquanto for menor que 4  , e assim vai colocar Quatro e não Três espaços .
Comment: Na verdade, para terminar uma string, o `0` e `'\0'` [são equivalentes](https://stackoverflow.com/a/14462305) (apesar que o segundo deixa mais claro a intenção, que é usar um caractere, e não o valor numérico)


Getting String Sets into Presentation Layer

Question: We're working on an hospital information system that is being written on C# and using NHibernate to map objects to database. MVC pattern is being used to separate business logic from UI. Here is the problem,
How do you get variable sized different set of strings to UI?
For example a Contact object have a property named City that holds which city contact lives. In country that the app is written for has more than 80 cities. How could you write those cities to a combo box? (or a data grid, tables, ...) In this example the city number is fixed. There is no need to add another city for a long time. (If the city list changes, recompiling is not a problem)
For example a Contact object have another property named FooBar which is going to be hold 1000 different string values and these values is going to be selected from a combo box for that property. And this set can be grown if users want. How do you load the combo box with these values? (If the string list statically written to combo box object, recompiling is a problem)
I have different solutions as below

All string values statically written to combo box in code or designer
Get the values from a resource file
Write those values to an XML file (Actually same as above, but no need to recompile)
Make a City object and get the values into a list from CITY table with NHibernate
Make a class named StringHolder which has a Type and Value property. All string values(including City and FooBar) would be written in just one table named STRINGHOLDER. And get those values with a key like "CITY" or "FOOBAR" with NHibernate.

Which one would you choose? Or could you suggest me another one?
Thanks all
Answer: I would vote for solution #4. That's the way I have always done it in similar situations. It just seems like a cleaner solution.
Comment: But City is going to hold just a string. Do you think it is right for domain model?

public class City{
  private string _name;
  public string Name{
    get {return _name;}
    set {_name = value;}
  }
}

There is going to be many classes like this if i don't use inheritance.
Comment: If i use inheritance there is going to be many empty classes like Contact, FooBar etc..

What do you think?
Comment: If City is just going to hold a string and never be used for Anything else then a Table may be overkill. But, many times once code is in production you may find new uses/needs for it. I personally use lookup tables/Domain objects for entities like city (States, Countries).
Comment: There is going to be so many string sets like this. Solution #4 will take too much to make for too many entities. I think we'll going with #3 and see if it works or not. But as i said string values(instead of integer keys to those values) will take too much space in database with #3. Thanks again
Answer: If the locations are actually going to be used for anything, get them into the database. If the data "isn't really used", but cities lookup is provided to make the user interface better, then the XML file option is not a bad way to go either.
By used, I mean stuff like list all emplyees in New York and stuff like that. If it's "dead data", just to be displayed, go for the solutions that will require the least amount of work and least risk - which might be the file option.
Comment: For example every Contact added to database has a City and FooBar field which is coming from combo boxes. So it's not that dead :)

In some string sets some of the string values has more than 100 characters. For every contact a row added and all rows will take 100 chars for just one field.
Comment: If i make it like this there is a "normalization" problem. Most of the rows in a table will going to have same value on FOOBAR field.

If i make classes for each string value sets, domain design will going to be messy :)

Both have advantages and disadvantages. What do you say?
Comment: I stick with what I said. Your domain model should ideally don't care one bit about how the database looks btw, the domain classes should look the way you want your code to work. But if you store the cities in db, I would normalize and have a separate city table with id's.
Answer: How do you feel of using List<string> for a list of City? Load this list of strings in your DAL or BL and then pass it on to UI.
Same solution should be good for FooBar values too.
In case you have IDs associated with City or FooBar, say NY and its numeric ID in DB is 1, then you can use KeyValuePair<TKey, TValue>. With generics you can dictate what data goes in this KeyValuePair. City name or FooBar's string value can be key and numeric ID can be value.
Just 2 cents.


Palantir Foundry: Composite-Key for DataSet-Rows / Object-Instance Primary Key

Question: I have a one-to-many Ontology relationship where -- for a given Alert object-instance -- I want at most one Feedback object-instance for it per User. A Feedback object-instance is Created & Updated by Users using  its Add & Modify Actions, respectively (and is used to provide one feedback score & commentary per User per Alert object-instance).
As such, to implement at most one semantics, each Feedback object requires a Primary Key composed of:

feedbackID (PK) = alertID (PK) + userID (PK)

However, in its backend definition, the Feedback object-type's Add Action  sets the Primary Key as a UUID, and this cannot be overwritten once instantiated. (Note: An object-reference or property is also possible here, but either would also only be part of the composite key sought). That is to say, although it's possible to synthesize the above composite-key in a frontend Workshop Action Tab (using Workshop variables and forms), it's understandably not possible to overwrite an object's already-existing PK with it.

Indicentally, for completeness, I'll mention, but not necessarily recommend, a two-DataSet option for composite-key PK consisting of the following steps:

The Add Action creates rows for an initial DataSet with UUID's as its PK.
A Foundry data pipeline mirrors this DataSet to create a corresponding DataSet with alertID + userID as its PK.
And finally, the Modify Action as well as downstream application uses consume that mirror (second) DataSet.

Again, presented for completeness and not necessarily recommended since it duplicates DataSets, as well as adds propagation delay to the out-of-the-box platform propagation delay.

With that as preamble, is there a just-in-time technique to generate Objects with a composite-key PK consisting of properties from other Objects (again, at Add-Action click time)? I may have missed something. Thank you.
Answer: I came up with an interim workaround which broadly include these steps:

Create a Function (snippet below) coupled with a Function-backed Workshop variable that returns a count of Feedback objects having the same alertID and userID combination (i.e. a manually synthesized composite-key):

If 0 is returned, only the Add Action Button (in green) is visible (via display logic).
If 1 is returned, only the Modify Action Button (in amber) is visible (via display logic).
If > 1 is returned (which would only happen if a bug existed somewhere), only a Red Error Button is visible (via display logic), with its hover-over text instructing the user to take a screenshot and eMail developers. No Action or Event is attached to this button.

@Function() // Used to set a Workshop variable (0|1|>1).
public async countFeedbackRecords(alertID: string,
                                  userID: string):
                                  Promise<Integer> {

  const feedbacks = Objects.search().feedback() // Feedback object-type is imported at top-of-file.
  const count = await feedbacks.filter(obj => obj.alertId.exactMatch(alertID))
                               .filter(obj => obj.user.exactMatch(userID))
                               .count()

  return Promise.resolve(count || 0)
}

One downside to this approach are lookups against the two columns mentioned, which are neither hashed nor indexed.


Access referenced entity in Rules using hook_entity_property_info

Question: I am using the Reply module for comment threads on a custom entity (we'll call it myentity). I'd like to create a rule that triggers when certain properties of myentity are met. However, the Reply module has very minimal entity_property_info, and so there's no way for rules to reference myentity in a condition.
The Reply module creates a Reply entity, that references an entity via entity_id column and an entity_type column. So, I created a property_info_alter hook as follows:
function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['reply']['properties'];

  $properties['entity_id'] = array(
    'label' => t("Entity id"),
    'description' => t("The entity this reply is associated with."),
    'type' => 'entity',
    'getter callback' => 'entity_property_verbatim_get',
    'required' => TRUE,
    'schema field' => 'entity_id',
  );
}

When I create a condition in rules of "Entity is of Type", I expect to find my new property as an option like reply:entity-id but it doesn't. It only appears in the condition "Data Comparison".
I feel like I'm missing something very simple, but really can't put my finger on it. How do I get this property to appear as a referenced entity that I can then evaluate in Rules?
Answer: This works as-is. I actually had a typo in my code that took me a long time to catch. I'm leaving this up if anyone else has the same situation. The final code looked like this (cleaner):
function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['reply']['properties'];

  $properties['myentity'] = array(
    'label' => t("My Entity"),
    'description' => t("The entity this reply is associated with."),
    'type' => 'myentity',
    'required' => TRUE,
    'schema field' => 'entity_id',
  );
}


For which angles is inequality true

Question: My problem is from Israel Gelfand's Trigonometry textbook.
Page 48. Exercise 6:
a) For which angles $\alpha$ is $\sin^4\alpha-\cos^4\alpha > \sin^2\alpha-\cos^2\alpha$ ?
b) For which angles $\alpha$ is $\sin^4\alpha-\cos^4\alpha \geq \sin^2\alpha-\cos^2\alpha$ ?
The attempt at a solution:
I know that $$\sin^4\alpha-\cos^4\alpha=(\sin\alpha-\cos\alpha)(\sin\alpha+\cos\alpha)(\sin^2\alpha+\cos^2\alpha)=(\sin\alpha-\cos\alpha)(\sin\alpha+\cos\alpha)=\sin^2\alpha-\cos^2\alpha$$
Is this even correct?
I would appreciate some hints on how to approach the problem.
Comment: Pretty good. You proved the equality then the answer for a) is none  and for b) for every angle
Answer: You are on the right track, no errors there. As you figured out, $\sin^4\alpha-\cos^4\alpha > \sin^2\alpha-\cos^2\alpha$  is not possible.
Comment: Oh, and second is true for all angles since $\sin^4\alpha-\cos^4\alpha=\sin^2\alpha-\cos^2\alpha$ right?
Comment: Exactly my friend.

For which angles is inequality true