Separar o valor da string

Question: Colegas.
Ao calcular o frete do carrinho, ele está retornando da seguinte forma:

Gostaria de saber, como faço para pegar somente o valor 24.90? Pois preciso somar com o valor do carrinho. Veja abaixo os códigos referentes:
PHP
$parametros = http_build_query($parametros);
    $url = 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx';
    $curl = curl_init($url.'?'.$parametros);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $dados = curl_exec($curl);
    $dados = simplexml_load_string($dados);

    foreach($dados->cServico as $linhas) {
        if($linhas->Erro == 0) {
            echo str_replace(",",".",$linhas->Valor) .'
';
            echo "Prazo de entrega: ".$linhas->PrazoEntrega. "Dias
";
        }else {
            echo $linhas->MsgErro;
        }

JQUERY
ajax1.onreadystatechange = function() {
        if (ajax1.readyState == 4) {
           document.getElementById("result").innerHTML = ajax1.responseText;
           valorFrete = document.getElementById("result").innerHTML;

           vv = document.getElementById("total").innerHTML + valorFrete;
           valorTotal = document.getElementById("total").innerHTML = vv.toFixed(2);

        } else {
            document.getElementById("result").innerHTML = "Aguarde, calculando...";
        }
    }

Answer: Faz isso do lado cliente (no js), podes simplesmente fazer:

responseText = '24.95,  Outro texto, '; // faz de conta
valorFrete = parseFloat(responseText)
alert(valorFrete);

Desta maneira já tens o valor númerico, pronto para operações matemáticas.
Nota que isto só resulta se tiveres a certeza que o primeiro caracter será sempre um digito.
Answer: Você pode quebrar a string por vírgula nesse caso, e pegar o primeiro índice:

let texto = '24.95,  Outro texto, ';
let valor = texto.split(',');
console.log(valor[0]);

Separar o valor da string


Fourier series definition

Question: Sometimes when deriving the formulas for the coefficients of Fourier series mathematicians start with this definition:
$$f(t):=a_0+\sum_{n=1}^{\infty}\left[a_n\cos\frac{n\pi t}{L}+b_n\sin\frac{n\pi t}{L}\right]$$
But other times they start with:
$$f(t):=a_0+\sum_{n=1}^{\infty}\left[a_n\cos nt+b_n\sin nt\right]$$
The second one seems more intuitive but what's the intuition behind the first one? Are they equivalent?
Answer: The only thing that differs is the domain (or the period). In the former case, $f:[-L,L]\to\mathbb{C}$ while in the latter case, $f:[-\pi,\pi]\to\mathbb{C}$.
They are practically equivalent. One can easily transform one case into the other by scaling $f$ in the $x$-direction.
Comment: @mrk. I realized that the domains were wrong. But your question probably remains. The answer is that the given domains cover one period of the functions. You can see that $f(t+2\pi) = f(t)$ in the latter case and $f(t+2L) = f(t)$ in the former case.

Fourier series definition


Methodology for Verifying Trigonometric Identities

Question: Lets say I have an equation like:
$$\frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1$$
Our teacher said you have to verify the equality by simplifying the left hand side or the right hand side without moving(doing operations to both sides) anything from one side of the equation to the other.
I have a problem with this because I proposed that we can verify the equality by multiplying the denominator by 1 and moving it to the other side. Then you can proceed to verify the equation by substituting trig identities. My argument is that if correct algebraic manipulation is done, then the equality is the same. It won't suddenly become false or true.
My method:
**the addition to the classical method is that you can multiply the equation by both sides while preserving the equality which is specifically not multiplying by 0 or applying operators such as derivatives or squaring etc as these do not preserve equalities.
$$\sin^2x+\cos^2x = \cos^2x·\sec^2x$$
$$1=\frac{\cos^2x·1}{\cos^2x}$$
$$1=1$$ equality is true
It requires ingenuity to be able to do the right manipulations...
Is my teacher justified in requiring that nothing is moved between the sides? is there a convincing argument for my side or am I wrong?
I would be grateful if someone can enlighten me; just why is it wrong to do algebraic manipulation before verifying an equality? Keep in mind that this method is meant to be extended to the more complicated problems. I just gave a simple example to illustrate it.
For reiteration and clarity, my question is why is my method wrong? What evidence is available to back up any certain answer?
Comment: I'd advise listening to your teacher.
Comment: Why should I listen? Could you elaborate why my method is wrong for verifying an equation?
Comment: Don't think about it as "moving". Think about it as performing an operation to both sides of the equality. Here, "moving the denominator to the other side" would be "multiplying both sides of the equality by the denominator".
Comment: Yes that is what I meant, i just used what the teacher exactly said
Comment: Your method is correct if the steps are reversible.  If you multiply both sides by a nonzero expression, for example, then the original and transformed equations are equivalent.  I've always thought the reason they tell you  not to consider both sides of the equation is that in real life, you're trying to simplify the left-hand side with yet knowing the right-hand side.
Comment: @saulspatz: you might want to look at the final example in my answer; I don't think that "nonzero expression" is unambiguous enough in what you wrote. :)  In my example, $\sin x$ is certainly a nonzero expression. I'm not inclined to get more specific, because I think that it might help OP to actually look at the subtleties of that example.
Comment: In the absence of an explicit signal (like `⇐` or `⇔`) to read your sequence of equations in the reverse direction, it is natural to interpret your presentation as "A implies B, which implies C, which implies 1=1", which is certainly not a proof of A. I wrote more [here](https://math.stackexchange.com/a/4668413/21813) and [here](https://matheducators.stackexchange.com/a/24639/372).
Answer: Consider the equation $1 = -1$. Allow me to prove this equation by performing the same operation on both sides, namely squaring. Hence, $1^2 = (-1)^2$ or $1 =1 $. Therefore, the first equation must be true. Does this seem like sound logic? The key observation here is that a false statement can be turned into a true statement if you abuse properties that are true for true statements. "Do the same thing" to equal values does indeed preserve their equality, but "doing the same thing" to unequal values can make them "equal".
You may find this related queation enlightening on on the logic consequences of how you proceed with problems such as this.
Comment: The operation of squaring is raising the base to the exponent of 2, the same operation on both sides
Comment: In this case, you are squaring both quantities which is not doing the same operation to both sides of the equation because on one side it is multiplying 1 and on the other its  multiplying by negative one. I am still confused
Comment: No it is not an operation... https://math.stackexchange.com/questions/568780/why-cant-you-square-both-sides-of-an-equation To save you some of the reading, if $x=1$ then the only solution is $x=1$ but for $x^2=1$ then you introduce new solutions.
Comment: @Bandoo would you mind defining what an "operation" is? The interpretation that I, and presumably user650025, have is any mapping between real numbers. One you have a valid equality, it is perfectly valid to apply a mapping to both sides of an equation, since, by definition, two equal input values will be "mappped" to the same output value. The issues that you correctly raise is that not all mappings are injective, meaning that for some mappings, such as squaring, two input values can be "mapped" to the same output value. This can result in a false equality becoming true, as shown in my answer
Comment: @Bandoo In my answer, I purposely omitted logic symbols since they seemed mostly irrelevant to the essence of the argument. You will note that since squaring real numbers is not an injective mapping, the transition between $1 = -1$ and $1^2 = (-1)^2$ is only a logical _implication_ ($\implies$), not an equivalence ($\iff$). Hence, we can say that "if $1=-1$, then $1^ 2= (-1)^2$", but not the other way around. This is what is meant by using only "reversible" steps when proving an equality.
Answer: I think your equality should be $\displaystyle \frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1$.
When I read your work, I naturally interpret it as
$\displaystyle \frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1 \implies \sin^2x+\cos^2x=\cos^2x\sec^2x \implies 1=\frac{\cos^2x\cdot1}{\cos^2x} \implies 1=1$.
It does not make sense. I already know that $1=1$, but it is not because of $\displaystyle \frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1$.  $\displaystyle \frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1$ is what you want to show and you should not start from it.
The correct sequence should be
$\displaystyle 1=1 \implies1=\frac{\cos^2x\cdot1}{\cos^2x} \implies \sin^2x+\cos^2x=\cos^2x\sec^2x \implies\frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1$.

Let me 'prove' that $ \sin^2x+ \cos^2 x=2$.
$ \sin^2x+ \cos^2 x=2 \implies (0)(\sin^2x+ \cos^2 x)=(0)(2) \implies 0=0$
equality is true.
Can you see the danger of the approach?
Comment: To prove or to verify something is to deduce something you want to know from something you already know.  The statement to be verified is something you want to know (whether it is true or not) and should appear as a conclusion but not the starting point. And of course, we know that $1=1$.
Comment: Multiplying both sides by $0$ is not reversible.  Squaring both sides are also not reversible. That's why these steps cause problems.  If you restrict your steps to direct application of identities, adding or subtracting some quantities on both sides, multiplying or dividing some nonzero quantities on both sides, you will not obtain an absurd conclusion. That's why I said that the approach is not totally wrong.  But you can't only restrict yourself to these simple operations if you are dealing with more complicated problems.  The best way is to write your work in a logical sequence.
Comment: If you are careful enough to avoid all the problems, then you will not be in trouble.  You work is actually $\frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1 \iff \sin^2x+\cos^2x=\cos^2x\sec^2x  \iff  1=\frac{\cos^2x\cdot1}{\cos^2x}  \iff  1=1$. but we tend to read the work line by line and intepret it as $\frac{\sin^2x+\cos^2x}{\cos^2x\sec^2x}=1 \implies \sin^2x+\cos^2x=\cos^2x\sec^2x  \implies 1=\frac{\cos^2x\cdot1}{\cos^2x}  \implies  1=1$.  It is a question of bad style rather than a logical mistake, if you are carefully enough.
Comment: You don't know 1 = 1...the question is to VERIFY the equation so it could turn out to be false. Your method assumes 1 = 1 with all certainty.
Comment: The way this is taught in all textbooks and other media always ends at 1 = 1 because it only simplifies one side at a time(with the underlying goal of making both sides equal to each other). In the aforementioned 'classical' method, no operations are done to both sides of the equation just like when you solve equations, instead, substitutions from trigonometric identities. You started your proof with 1 = 1; whereas the starting step should be what the question asked:$\frac{sin^2+cos^2x}{cos^2sec^2}=1$  What I offered is a variation to the classical method.
Comment: Actually I won't start from $1=1$.  I can start from $1=\frac{\cos^2x\cdot 1}{\cos^2x}$.
Comment: Yes that is the classical method and you are going to follow as any textbook or teacher would do. However, I still do not understand your argument for why method is incorrect.
Comment: As  saulspatz pointed out, your approach is fine if the steps are reversible.  And your steps are actually reversible.  That's why I write your work reversely and obtain a correct proof.  In those textbooks that verifying statements by works ending with $1=1$, the steps should be reversible.  I won't say this approach (or your work) is totally wrong, as the steps are reversible.  If one of your steps is not reversible, you will be in trouble.  As said in Brian's answer.
Comment: Multiplication by 0 is the only exception. I should edit that into the main post.
Comment: What is wrong with such restriction? For more complicated problems,I can multiply $cosx$ by both sides if x represents a specific real quantity
Comment: you will be in trouble as $\cos \frac{\pi}{2}=0$.
Comment: Yes. But that does not matter unless you are dividing by cosine, for which the domain is restricted. This is exactly the same issue brought up by @john hughes
Comment: You can't multiply both sides by $0$. "Multiplication by 0 is the only exception."
Comment: There is no exception being made here. It is just being mindful of the domain restrictions on any equation. x/sin(x) is always restricted so that x cannot be 0. Obviously you have to take into account that when trying to verify an identity
Answer: As you observe, multiplying by zero is the only unreversable step. (Well...that's not quite true, but close enough.)
The problem with applying this in the context of proving trig identities is that it's sometimes tough to know that you are multiplying by zero.
For instance, you might multiply both sides by $2\sin^4 x + \sin^2 (2x) + 2 \cos^4  x - 1$. Are you multiplying by zero or not? As it turns out, you're multiplying by zero in this case ... but you don't know that until you've proved another trig identity, namely that
$$
2\sin^4 x + \sin^2 (2x) + 2 \cos^4  x - 1 = 0.
$$
You can see how this can lead you down a rathole pretty fast.
So your logic (with appropriate restructuring) is fine: if you apply an invertible operations to both sides of your supposed equality, and the resulting equality is true, then so was your supposed equality.
But in practice, it's almost useless, because especially in the context of trig identities, it's tough to know whether a given function is injective or not. In particular, multiplication by some trigonometric expression may turn out to be multiplication by zero, and then it's "game over."
Let me give one last example for you to consider:
$$
\frac{\sin (2x)}{\sin x} = 2\cos x
$$
If we multiply both sides by $\sin x$, we get
$$
\sin (2x) = 2 \sin x \cos x
$$
which is true. But the original statement is false. Why? Because at $x = 0$, the left hand side is undefined, while the right-hand side is $2 \cos 0 = 2$.
Notice that in this example, I did an apparently reversible operation (multiplying by $\sin x$, which is certainly not the 0 function!) and derived a true statement, but the original statement was not true.
When you can carefully explain this example, and how you might avoid situations like this one, you can probably safely start ignoring your teacher's advice.
Comment: The first equation needed the domain to be restricted because you cannot divide by 0. sin(2x) = 2sin x cos x is only true if :ℝ. But I would like to thank you for giving such example. While it does not contradict my logic, it shows a reason for why my methodology can be impractical even in completely theoretical practice.
Answer: As I think, you have obviously removed $\cos^2 x\sec^2 x$ from LHS to RHS (i.e. cross-manipulated the both sides) which may make you teacher object to you! A better and more standard way (to fit your teacher's will) is that simplify $\cos^2x\sec^2x$ and substitute it with $1$ (except when $\cos x=0$ since ambiguity happens) and get onto an always-true statement $\sin^2x+\cos^2x=1$. Therefore the answer is $$\Bbb R-\left\{k\pi+{\pi\over 2}\ |\ k\in\Bbb Z\right\}$$


Prove that $\mathbf{A} \cdot (\mathbf{A} \times \mathbf{B}) = 0$

Question: This is another question:

Question. Prove that $\mathbf{A} \cdot (\mathbf{A} \times \mathbf{B}) = 0 $.

Where $\mathbf{A}$ and $\mathbf{B}$ are vectors, "$\times$" denotes the cross product, and "$\cdot$" is the dot product.
Here if I assume that $\mathbf{A}$ lies on the $x$ axis then there are three possibilities for $\mathbf{B}$: it lies on the $x$ axis, or on the $y$ axis, or on the $z$ axis.
Therefore, there are two ways that this question can have an answer $= 0$.

If $\mathbf{B}$ lies on the $y$ or $z$ axes, then $\mathbf{A} \cdot \mathbf{C} = 0$ since then then would be perpendicular to each other.

If $\mathbf{B}$ lies on the $x$ axis, then $\mathbf{A} \times \mathbf{B}$ is already parallel and we get $= \mathbf{0}$. Thus $\mathbf{A}\cdot\mathbf{0} = 0$.

The Textbook uses point 1 as the right answer. Can both be correct?
Edit: Exact textbook quote:1)

$\mathbf{A}\times\mathbf{B}$ is perpendicular to $\mathbf{A}$. Now, the dot product of two perpendicular vectors is zero. Hence
$$ \mathbf{A} \cdot (\mathbf{A} \times \mathbf{B}) = 0. $$
Comment: The claim is trivial if you know that $\;\vec A\times \vec B\;$ is always a vector perpendicular, or normal or orthogonal, to both $\;\vec A\,,\,\,\vec B\; $ ...
Comment: @S.M.T The usual definition of the cross product $A \times B$ includes the fact that it is orthogonal to both $A$ and $B$. That is a property of the vectors, regardless of any axes or systems of coordinates. If you are using a different definition please write that into the question.
Comment: Why can't $B$ be a vector like $(1,14,-13)$, which lies in none of the axis?
Comment: is it dot product?
Comment: @Algebrology Yes. Ofc
Comment: @S.M.T "*Textbook uses point 1*" $\;-\;$ Can you quote the relevant part from the textbook literally? What you wrote doesn't make a lot of sense.
Comment: Is this in $\Bbb R^3$?
Comment: @WilliamA.Noble We are allowed to use it. But if you're asking if why I have worsen X,Y,Z axis. It is an assumption for my Q.
Comment: @S.M.T There is no mention of $X,Y,Z$ in the book, and no relationship to your "*point 1*" whatsoever. Besides, the picture shows the entire proof. Is there something not clear about it, or are you disputing it, or are you asking about something entirely else?
Comment: @dxiv If the solution says that AxB is perpendicular to A. Then , what do you think can be the axes for A,B,C. Moreover , please read the post carefully. Don't you see that there can be a choice for option 1 to be used or 2 or some other maybe. I am not at all getting what you did not get.
Comment: Indeed, the point is to think about what $A \times B$ means. What is it perpendicular to?
Comment: @MattiP. No, you can also think that if A and B lie on the same axis . Then , there is no need to think of what is it perpendicular to . A when parallel or anti parallel to B l A x B = 0
Answer: $$\bar A\times \bar B = \bar C$$
Now, $\bar C$ must be a vector that is perpendicular to both vectors $\bar A$ and $\bar B$
Now, the dot product of vector $\bar C$ with $\bar A$ or $\bar B$ must be zero
as
$\bar a. \bar b = |a|\times|b|\times \cos\theta$
which here angle between $\bar C$ and $\bar A$ is $90^0$
Answer: Using a very tricky property of Triple Product defined as $$[A\ B\ C]=A\cdot (B\times C),$$ where $A,B,C$ are vector quantities, we can prove your problem in a single line.
The property is $$[A\ B\ C]=[B\ C\ A]=[C\ A\ B].$$
Now you have given $[A\ A\ B]=[B\ A\ A]=B\cdot (A\times A)=0$ since $A\times A=0$.


How is Google analytics implemented?

Question: I mean how google analytics gathering data from client side.
My guess is that GA put js code in client side, and using the js as interceptor to send client data to data gathering server using ajax before user do anything in client side.
Do my guess right?
Comment: Try [Googling](http://tinyurl.com/antwem) for it. Which leads to [code site](http://code.google.com/intl/en/apis/analytics/docs/tracking/asyncTracking.html).
Comment: You might want to ask Google instead of guessing.
Comment: Possible dupe of http://stackoverflow.com/questions/414451/how-does-google-analytics-send-data-back-to-google
Answer: I believe that ga.js makes a request for a 1x1 .gif file, and in the request for that gif, it passes along all the parameters used by analytics, such as screen resolution, operating system etc.
Update: Screenshot from google chrome below

How is Google analytics implemented?


Anychart create graph using function as parameter

Question: I have this function with which I create AnyChart Graph. I want to make a lot of functions, for different graphs, like this one, and also to show them into different MaterialDialogs.
        private fun createChart(): Cartesian {
            val cartesian: Cartesian = AnyChart.cartesian(
            (...)
            return cartesian
        }

For this task, I made a general function, which will be called with the specific views IDs and specific function for creating the graph
private fun showDialog(layoutId : Int , chartId : Int, function: (Chart)) {

        val dialog = MaterialDialog(requireContext())
            .customView(layoutId)
            .cornerRadius(5.5f)

        val chartView: AnyChartView = dialog.findViewById(chartId)
        APIlib.getInstance().setActiveAnyChartView(chartView)
        chartView.setDebug(true)

        chartView.setChart(function) // <------ The problem is here
        //chartView.setChart(createChart() works fine
        dialog.show()
    }

I will call this function at onClick listener of some view and specify which chart to be shown and which draw function to be used
private fun showWeatherDialog() {
        showDialog(R.layout.activity_graph_test,R.id.any_chart_view,createChart())
}

If I use the normal function call, the graph is drawn normally, but when I call the function  parameter it doesn't work

   chartView.setChart(function) // <------ The problem is here
   //chartView.setChart(createChart() works fine

The error from Anychart:

E/AnyChart: Uncaught ReferenceError: cartesian43 is not defined
Answer: Here is my solution:
    private fun showWeatherDialog() {
        showDialog(R.layout.activity_graph_test, R.id.any_chart_view) { createChart() }
    }

    private fun showDialog(layoutId: Int, chartId: Int, drawingChart: (()-> Cartesian)) {
         (...)
        chartView.setChart(drawingChart.invoke())
        dialog.show()
    }


How can I create a custom form settings to my custom field formatter?

Question: I need to add form settings to my custom display format, can you provide me with an example?
To be clear I just want to add some fields to the format settings form.
Comment: What settings are you talking about? Can you provide a screenshot?
Comment: thanks for answer, I already added a image to the question.
Answer: Whenever you need to figure out how something works, look at examples that already do what you want. In your case, that's the ImageFormatter plugin.
Specifically, you are looking for the methods defaultSettings(), settingsForm() and settingsSummary(). Implement them, define the form for you settings, specificy default settings and for improved user experience, implement the summary method to give users a short summary of the current settings.
That's all, in viewElements(); you can then access your settings with getSetting().
Comment: Thanks!!! its work! before your answer I was checking that, but I was having doubt.


What happens when one side of a cube is multiplied by 7?

Question: I have a question that seens obvious, but I know the answer can't be that simple.
What happens to the volume and surface area when all sides of a cube is multiplied by 7?
At first I assumed that both the surface area and volume would just be multiplied by 7, but I know that isn't the case. Any help is appreciated, thanks.
EDIT: Fixed question to be more clear.
Comment: If by "multiplying a side of a cube by $7$" you mean make all the side lengths of the cube $7$ times longer, then the surface area will be $7^2$ times larger and the volume will be $7^3$ times larger. You might just choose a cube and do the calculation, to see. You'll likely understand why, too
Comment: Are the other two dimensions left the same (so if you started with a unit cube you now have a $1 \times 1 \times 7$ brick) or are all three dimensions multiplied by $7$, keeping it a cube?
Comment: @mixedmath That's it, thanks for your help!
Answer: Let the side of the cube be $a$.  Multiplying each dimension by $7$ gives a cube $7a \times 7a \times 7a$  The original volume was $a^3$ and the new volume is $(7a)^3$, so it gets multiplied by $7^3$. The surface area of the original cube is $6a^2$, so if you multiply the side by $7$ the area gets multiplied by ????
Comment: Sorry, I meant multiply all sides by 7. I've edited the question for clarity.


How can I use horizontal scrolling of a webview inside the viewpager?

Question: On MainActivity, there is a ViewPager, which has several Fragments. The ViewPager consists of several fragments. One of fragments is a fragment that shows WebView. This WebView presents the content as a list of vertical items. Some of these items have horizontal scrolling. (Image : Horizontal item list 1, 2)

Due to the use of horizontal swipes in the ViewPager, horizontal scrolling within the webview cannot be used. How can I solve it? (If possible, with Kotlin)
Answer: You can check this demo on Git with horizontal scrolling of webview inside the viewpager.
https://github.com/plusinfosys-global/Webview-Inner-Horizontalscroll-with-Viewpager
Answer: its very possible, you must to define custom scroll on your view Pager, i have sample like this. just call method canScrollHorizontally from you webview on TestViewPager class
class TestViewPager(context: Context, attrs: AttributeSet?) : ViewPager(context, attrs) {
    override fun canScroll(v: View?, checkV: Boolean, dx: Int, x: Int, y: Int): Boolean {
        return if (v is WebView) {
            v.canScrollHorizontally(-dx)
        } else {
            super.canScroll(v, checkV, dx, x, y)
        }
    }
}

Comment: Any luck with ViewPager2?
Answer: You can use this method to lock any other scrolling view while scrolling current view. Try this,
public static void LockScrollViewOnViewTouch(final ScrollView scrollView, View view) {
    view.setOnTouchListener(new android.view.View.OnTouchListener() {
        @SuppressLint("ClickableViewAccessibility")
        public boolean onTouch(View p_v, MotionEvent p_event) {
            scrollView.requestDisallowInterceptTouchEvent(true);
            return false;
        }
    });
    scrollView.setOnTouchListener(new android.view.View.OnTouchListener() {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            scrollView.requestDisallowInterceptTouchEvent(false);
            return false;
        }
    });
}

This disable scroll on touch, first parameter "scrollview" is View you want to lock that could be your viewPager. Let me know if it works.


Como abrir outra tela em Flutter?

Question: Tenho um app para scanner QRCODE e tenho a seguinte verificação:
// Executa função para o scanner
Future _scan() async {
  String barcode = await scanner.scan();
  if (barcode.contains("cx-")) {
  // this._outputController.text = barcode;
    onPressed: (){
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ScanCx()
        ),
      );
    };
  }else {
    print("Código não encontrado!");
  }
}

Porém, quando cai no if contém cx, chega no onPress ele não está fazendo a navegação para a tela de ScanCx.
O que estou fazendo de errado?
Answer: Uma dica, caso sua aplicação comece a crescer para não ter que digitar essa linha "enorme" e para ficar mais organizado, você pode criar rotas.
Para isso, basta inserir as rotas para as telas no build do main.dart como no exemplo abaixo:
Widget build(BuildContext context) {
 return MaterialApp(
    debugShowCheckedModeBanner: false,
    title: 'Teste',
    routes: <String, WidgetBuilder>{
        '/homepage' : (BuildContext context) => new HomePage(),
    },
 );}

Em seguida basta usar a linha abaixo para poder chamar a tela desejada.
Navigator.pushNamed(context, '/homepage');

Bons estudos!
Answer: Olá! Ao que me parece, o que está sobrando no seu código é justamente o OnPressed.
Como está chamando em uma função _scan, deve apenas executar a função Navigator.push( ... ).  Pois, o onPressed é um evento, normalmente usado para vincular a um widget, associado a ação de apertar do usuário.
Com a mudança o código deve ficar +/- assim:
// Executa função para o scanner
Future _scan() async {

String barcode = await scanner.scan();
if (barcode.contains("cx-")) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ScanCx()
      ),
    );
} else {
  print("Código não encontrado!");
}

}

Como abrir outra tela em Flutter?


Porque margin-top afeta a div pai

Question: Porque quando dou um margin-top no elemento filho isso afeta o elemento pai? Veja exemplo abaixo:

body{
  background-color: #aaaaaa;
}
.topo{
 width: calc(100% - 20px);
 max-width: 1200px;
 height: 130px;
 display: block;
 margin: 0 auto;
 background-color: #000000;
}
.topo_caixa{
 width: calc(100% - 20px);
 height: calc(100% - 20px);
 display: block;
 margin: 0 auto;
 margin-top: 10px;
 position: relative;
 background-color: #eeeeee;
}

E qual a melhor forma de fazer isso que quero? Alinhar essa caixa de dentro ao centro, sei que tem inúmeras formas, mas existe alguma mais indicada?
Comment: Amigo, dê uma olhada neste [link do SOe](https://stackoverflow.com/questions/79461/vertical-alignment-of-elements-in-a-div)
Comment: Valeu, então a resposta é que é um bug mesmo, certo? Não é algo errado, não tem uma explicação lógica, é isso?
Comment: Caio vou copiar parte dessa resposta e colocar aqui pra vc com mais uns detalhes, vou remover o voto para fechar
Comment: Acora a resposta ficou mais completa :) tmj
Answer: Vc está tendo um problema conhecido como Colapso de Margem ou Margin Collapsing. Esse "bug" já foi descrito e é bem documentado inclusive. Vc pode se informar mais sobre esse assunto nessa documentação da própria Mozilla. https://developer.mozilla.org/pt-BR/docs/Web/CSS/CSS_Box_Model/margin_collapsing

Pai e primeiro/último filho
*Se não houver border, padding, parte inline, contexto de formatação de bloco criado ou livre para separar o margin-top de um bloco do margin-top do seu primeiro bloco filho, ou nenhum border, padding, conteúdo inline, height, min-height, ou max-height para separar o margin-bottom de um bloco do margin-bottom do seu último filho, então essas margens colapsam. A margem colapsada acaba fora do pai.*

Já as margens laterais, na horizontal nunca vão colapsar! Veja o que diz a documentação oficial da W3C https://www.w3.org/TR/CSS21/box.html#collapsing-margins

Horizontal margins never collapse.

Veja esse exemplo, repare que a margem só empurra para os lados quando o elemento é inline e nos elementos block empurra tb para os lado e na vertical. Veja que a margem horizontal não colapsa ela se soma a margem do elemento ao lado.

Leia essa pergunta e a resposta: Por que a Borda só afasta o elemento Horizontalmente e não Verticalmente?

Sobre as práticas para resolver o problema
Existem sim várias formas de resolver esse problema, porém a maioria delas sempre tenta mudar o tipo do display do filho ou do pai. Mas a dica que eu te dou é usar o overflow: auto; assim vc não precisa se preocupar com o model-box e display dos elementos, o que pode gerar efeitos colaterais indesejados. Essa a a minha dica, pode ter gente que descorde, mas eu prefiro não mexer com o display do elementos, nem colocar padding ou border transparente para resolver isso...
Veja o seu exemplo aplicando o overflow:auto no pai

body{
  background-color: #aaaaaa;
}
.topo{
  width: calc(100% - 20px);
  max-width: 1200px;
  height: 130px;
  display: block;
  margin: 0 auto;
  background-color: #000000;
  overflow: auto;
}
.topo_caixa{
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  display: block;
  margin: 0 auto;
  margin-top: 10px;
  position: relative;
  background-color: #eeeeee;
}

Artigo interessante sobre margin collapse https://css-tricks.com/what-you-should-know-about-collapsing-margins/
Answer: Você pode fazer assim:

body{
  background-color: #aaaaaa;
}
.topo{
  width: 100%;
  height: 200px;
  display: flex;
  background-color: #000;
}
.topo_caixa{
  margin: auto;
  text-align:center;
  background-color: #c0c0c0;
  width: 90%;
  height: 90%;
}

Porque margin-top afeta a div pai


slack slash command with node-slack-sdk

Question: I'm facing Slack API for the first time.
I'm trying to implement a slash command; I found this tutorial:
https://github.com/slackapi/template-slash-command-and-dialogs
but it seems it doesn't use the slack node-slack-sdk. After some hour I wasn't able to find anything in the SDK about the slash commands.
Did I missed something or actually the Slack SDK doesn't offer a slash command SDK?
BTW I was able to successfully configure a slash command, I just want to know if it would be possible to do it with slack node-slack-sdk to keep coherence in the code.
Answer: Slash commands are added in the Slack app's settings page.
https://api.slack.com/apps/A1234567/slash-commands?

(where A1234567 is your app ID)
These generate events similar to the Block elements and send POST data to your designated end node.
I don't use an SDK (my CGI is BASH) so I can't speak to how/if they differentiate events generated by slash commands versus other events.
To answer the question, I believe the slash command handling should be documented in here:
https://slack.dev/node-slack-sdk/interactive-messages

Comment: +F "slash" and/or +F "command" are enough to see that page doesn't speak about slash commands.
Comment: Is it this?
https://slack.dev/java-slack-sdk/guides/slash-commands
Comment: Nope @frinklabs , that is Java Bolt SDK, not node-slack-sdk for Node.js (JavaScript)
Comment: How about this?
https://scotch.io/tutorials/create-a-custom-slack-slash-command-with-nodejs-and-express

slack slash command with node-slack-sdk


Exercise in Folland on extending a closed subspace of a Banach space

Question: Folland gives the following problem on page $159$ of his book Real Analysis:

Let $\mathcal X$ be a normed space.
If $\mathcal M$ is a closed subspace and $x\in \mathcal X \setminus \mathcal M$ then $\mathcal M + \mathbb C x$ is closed.

The only way I know how to do this is to consider the projection $\mathcal X \rightarrow \mathcal X/ \mathcal M$, note that the subspace generated by $x$ in the quotient space is closed, then note the inverse is exactly the space we want. The inverse is closed because it is the inverse of a closed set by a continuous map, so we're done.
However, the hint given by Folland asks the reader to use the fact that given a closed subspace $\mathcal M$ and point $x$ not in $\mathcal M$, there is a bounded functional $f$ that vanishes on $\mathcal M$ and is nonzero at $x$. (This is an easy consequence of Hahn-Banach.) How can this hint be used to solve the exercise?
This question is part a of the problem. The next part asks the reader to show that finite-dimensional spaces are closed, so I would like to avoid using that fact.
Comment: I have deleted my answer, in case anyone goes looking, since a fatal flaw was pointed out.
Answer: By multiplying the functional $f$ with a constant, we can assume $f(x) = 1$.
Then let $y \in \overline{\mathcal{M} + \mathbb{C}\cdot x}$. Let $\xi_n$ a sequence in $\mathcal{M} + \mathbb{C}\cdot x$ converging to $y$. Then $f(\xi_n) \to f(y)$, and that means the $\mathbb{C}x$ components of $\xi_n$ converge. Then $\xi_n - f(\xi_n)x \to y - f(y)x$ converges too, but $\xi_n - f(\xi_n)x \in \mathcal{M}$, so $y - f(y)x \in \mathcal{M}$, and $y = (y - f(y)x) + f(y)x \in \mathcal{M} + \mathbb{C}x$.
Comment: Ah, nice. +1. $\textbf{}$


estimating beta parameter

Question: I have data on 500 examinees with responses to 20 questions. Because the response is dichotomous, I use Beta(1,1) as the conjugate prior. Now I'm interested in using Beta(alpha, alpha) as the prior. How can I estimate alpha? I hope to do it in R.
Comment: I tried to fix up your grammar so that it is more understandable, but perhaps I failed. What is your dependent variable? What are your independent variables?
Answer: If I've understood you right, you're trying to come up with parameters for the prior beta distribution of a binomial probability - often that's called elicitation rather than estimation.
Garthwaite, Kadane, & O'Hagan discuss this in 'Statistical Methods for Eliciting Probability Distributions' (JASA 2005).  Obviously few people are familiar enough with probability distributions to be able to come up stright away with parameters that represent their beliefs.  But you can think about (1) quantiles, (2) hypothetical future samples, (3) equivalent prior samples, or (4) relative values of probability density functions. The paper's worth reading.

estimating beta parameter


Member function not work in cons structure

Question: I write two program one is to takeoutAllButLast , other is  takeoutSecondLast.
I initially use the member function to determine whether there is more X behind.
And I try some data and find that:
If the first argument is a symbol, they both work!
But if it is cons structure, they both fail.
1.// `(a b)   `((b b)(a b)(b c)(a b)) ==>  `((b b)(b c)(a b))

(defun takeoutAllButLast (X L)
(cond ((null L) nil)
       ((equal X (first L))
           (if (member X (rest L))
               (takeoutAllButLast X (rest L))
               L))
       (t (cons (first L) (takeoutAllButLast X (rest L))))
)
)

2.//`(a b)   `((a b)(b b)(a b)(b c)(a b)) ==>  `((a b)(b b)(b c)(a b))
(defun takeoutSecondLast (X L)
(cond ((null L) nil)
       ((equal X (first L))
           (if (member X (rest (member X (rest L))))
    (cons (first L) (takeoutSecondLast X (rest L)))
    (rest L)
           )
    )
   (t (cons (first L) (takeoutSecondLast X (rest L))))
 )

What I want to ask is how to determine whether there is still one element is X behind, and can be used like member function?
And why member function cannot be used to compare cons structure?
Thx for you reading my question!
Answer: member defaults to using eql as its equality predicate. That works fine on symbols, numbers and a few other things (that is (eq 'a 'a) is always true, (let ((cons (cons 'a 'a))) (eql cons cons)) is always true, but (eql (cons 'a 'a) (cons 'a 'a)) is almost never true).
You can pass an alternative equality checker to member using the :test keyword and if you use #'equal you will (probably) get what you want.
If you want to call member with the custom equality checker foo, simply do:
(member thing-to-check-for the-list-to-check :test #'foo)

Comment: Try (member X (rest L) :test #'equal)
Comment: Can you give a example to pass an equality checker to member? Thank you.


R scatterplot matrix with nonparametric density

Question: I normally use MATLAB, or JMP but right now am working with R.
I have ~150 dimensional data with a few hundred thousand rows.  Some of the columns are non-informative, they only have one value.  This makes some of the descendants of "pairs" to fail.
I wish that I could say "pairs(mydata)" but that doesn't work well.
I know a few (~18) higher value variables that I think are more informative so I can, if I like, enter "pairs(mydata[,indices])" and get an 18x18 scatterplot matrix plot.  I don't get the nonparametric density on top of them.  Can you tell me how to get this?
Now JMP has a switch that allows adding what they call a nonparametric density to scatterplots.  (link, link,)  I want to do that for my data.
Here are things that I have looked out but they have not been helpful:

(pairs) http://www.statmethods.net/graphs/scatterplot.html
(ggpairs) http://www.r-bloggers.com/five-ways-to-visualize-your-pairwise-comparisons/
http://learnr.wordpress.com/2009/07/15/ggplot2-version-of-figures-in-lattice-multivariate-data-visualization-with-r-part-5/

I really want something like this, with my data, as each of the scatterplot panes in the scatterplot matrix:
Comment: Do you really plan to look at over 22,000 of these plots after you have waited for them all to be computed? Instead of creating such detailed images, you would seem to have a pressing need to screen the data first for "interesting" pairs of variables and to display their covariation in an extremely succinct and simplified fashion.
Comment: Of course I am doing pre-filtering to reduce the variable size.  I'm going to look at the scatterplot matrices in subgroups, probably less than 20x20, but maybe larger than that.
Answer: One option is the hexbin package, the display is different from what you show, but will convey the similar information and there already exists a function in the package to do the hexbin equivalent to the scatterplot matrix.
The other option is to write your own custom panel function to use with the pairs function.  You could use the kde2d function from the MASS package to estimate the density and then use the output with one of the contour routines to draw the lines.
Here is some example code of the 2 ways I mentioned (neither use ggplot2, someone with more expertise there may be able to show a way to do this using ggplot2).
library(hexbin)
hexplom(iris[,1:4])

library(MASS)
library(colorspace)
myfunc <- function(x,y) {
    points(x,y)
    k <- kde2d(x,y)
    cnt <- contourLines(k$x, k$y, k$z)
    n <- length(cnt)
    cols <- rev(sequential_hcl(n))
    for( i in seq_len(n) ) lines(cnt[[i]], col=cols[i])
}

pairs(iris[,1:4], panel=myfunc)

Comment: @EngrStudent, I added some sample code to the answer above.
Comment: can you give me sample r-code?
Comment: That is beautiful.


Compress Videos using android MediaCodec api

Question: I want to compress locally saved video file to a smaller size in order to upload to a server.
Since i used  MediaCodec , i have found some tips to compress video . Here are the steps that i followed
1) . Extracted the media file using MediaExrtactor and Decoded it.
   2) . Creates the Encoder with required file format
   3) . Create muxer to save file in local storage. (not complete)
Question : But i dont know how to encode the already decoded stream and save the stream in to the local storage using MediaMuxer.
public class CompressMedia {

    private static final String SAMPLE = Environment
            .getExternalStorageDirectory() + "/DCIM/Camera/20140506_174959.mp4";

    private static final String OUTPUT_PATH = Environment
            .getExternalStorageDirectory()
            + "/DCIM/Camera/20140506_174959_REC.mp4";

    private MediaExtractor extractor;
    private MediaCodec decoder;
    private MediaCodec encoder;
    String mime;

    private static final String MIME_TYPE = "video/avc";

    public void extractMediaFile() {

        // work plan
        // locate media file
        // extract media file using Media Extractor
        // retrieve decoded frames

        extractor = new MediaExtractor();
        try {
            extractor.setDataSource(SAMPLE);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            // file not found
            e.printStackTrace();
        }

        // add decoded frames
        for (int i = 0; i < extractor.getTrackCount(); i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("video/")) {
                extractor.selectTrack(i);
                decoder = MediaCodec.createDecoderByType(mime);
                decoder.configure(format, null, null, 0);
                break;
            }
        }

        if (decoder == null) {
            Log.e("DecodeActivity", "Can't find video info!");
            return;
        }

        // - start decoder -
        decoder.start();
        extractor.selectTrack(0);

        // - decoded frames can obtain in here -

    }

    private void createsEncoder() {

        // creates media encoder to set formats
        encoder = MediaCodec.createDecoderByType(MIME_TYPE);

        // init media format
        MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, /* 640 */
                320, /* 480 */240);
        mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 400000);
        mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 25);
        mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,
                MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar);
        mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
        encoder.configure(mediaFormat, null, null,
                MediaCodec.CONFIGURE_FLAG_ENCODE);
        encoder.start();

        // - encoded data format is avaiable in here

    }

    private void createMuxer() {

        // creates media muxer - media muxer will be used to write the final
        // strem in to a desired file :)

        try {
            MediaMuxer muxer = new MediaMuxer(OUTPUT_PATH,
                    OutputFormat.MUXER_OUTPUT_MPEG_4);

            int videoTrackIndex = muxer.addTrack(encoder.getOutputFormat());

            //muxer.writeSampleData(videoTrackIndex, inputBuffers, bufferInfo);
            muxer.start();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Here are the links that i follwed
Android MediaCodec: Reduce mp4 video size and
Video compression on android using new MediaCodec Library
Comment: Hi Mr. G. I need one help from you. I want to compress the video. Can you tell me how to compress the video using MideaCodec. Or show a sample for compressing the video?
Comment: @NewDeveloper  i used intel transcode pack to the compression, it worked from kit-kat , havent tried from mediacodec , i think the easiest way to do it , using ffmepg , u can get ffmpeg suport to android studio using precompiled FFPEG libs
Comment: Thanks for the reply..
Answer: You can try Intel INDE on https://software.intel.com/en-us/intel-inde and Media Pack for Android which is a part of INDE, tutorials on https://software.intel.com/en-us/articles/intel-inde-media-pack-for-android-tutorials. It has a sample that shows how to use media pack to transcode=recompress video files. You can set smaller resolution and\or bitrate to output to get smaller file
in ComposerTranscodeCoreActivity.java
protected void setTranscodeParameters(MediaComposer mediaComposer) throws IOException {

    mediaComposer.addSourceFile(mediaUri1);
    mediaComposer.setTargetFile(dstMediaPath);

    configureVideoEncoder(mediaComposer, videoWidthOut, videoHeightOut);
    configureAudioEncoder(mediaComposer);
}

protected void transcode() throws Exception {

    factory = new AndroidMediaObjectFactory(getApplicationContext());
    mediaComposer = new MediaComposer(factory, progressListener);
    setTranscodeParameters(mediaComposer);
    mediaComposer.start();
}


Irreducible lattices in $G=G_1\times G_2$

Question: First, we shall recall the definition of an irreducible lattice.

Let $G$ be a Lie group which admits a direct product decomposition into simple non-compact factors $G_1\times\dots\times G_k$.  A lattice $\Gamma$ in $G$ is irreducible if the intersection of $\Gamma$ with any factor $G_{i_1}\times\dots\times G_{i_j}$ is not a lattice [Wikipedia].

Now, let $G$ be a Lie group which admits a direct product decomposition into simple factors $G_1\times G_2$.  Let $\Gamma$ be a lattice in $G$ and assume that $\Gamma\cap G_1$ is not a lattice in $G_1$.  What conditions are sufficient to say $\Gamma$ is irreducible?
Obviously we can simply satisfy the above definition, but in the case of two factors of $G$ are there other equivalent conditions which could hold that would not in the case of $3$ or more factors?
Comment: There's no consensus on the definition of "irreducible" in such a generality. But when each $G_i$ is simple and non-compact it sounds like the standard definition.
Comment: Assume each $G_i$ is simple and non-compact, can we then say anything?
Answer: Let $G_1,G_2$ be simple, noncompact connected Lie groups with finite center.
For a lattice $\Gamma$ in $G=G_1\times G_2$, the following are equivalent:

$\Gamma\cap G_1$ is infinite
$\Gamma\cap G_2$ is infinite
$\Gamma\cap G_1$ is a lattice in $G_1$
$\Gamma\cap G_2$ is a lattice in $G_2$
the projection of $\Gamma$ on $G_1$ is dense
the projection of $\Gamma$ on $G_2$ is dense
There exist lattices $\Lambda_1,\Lambda_2$ in $G_1$ and $G_2$ such that $\Lambda_1\times\Lambda_2$ is contained in $\Gamma$ as a finite index subgroup.

(The negation of either of these conditions is called being "irreducible".)
With more factors, the definition is a little more tricky. Let $I$ be a finite set, $G_i$ be simple noncompact connected Lie groups with finite center. For $J\subset I$, write $G_J=\prod_{j\in J}G_j$, and $G=G_I$. Let $\Gamma$ be a lattice in $G$.  The following are equivalent

there exists a subset $J\notin\{\emptyset,I\}$ of $I$ such that $\Gamma\cap G_J$ is a lattice in $G_J$
for every $i$, the projection of $\Gamma$ on $G_{I\smallsetminus\{i\}}$ is dense
for every proper subset $J$ of $I$, the projection of $\Gamma$ on $G_J$ is dense
there exists a partition $I=J\sqcup K$ with $J,K$ both nonempty, and lattices $\Lambda_J,\Lambda_K$ in $G_J$ and $G_K$ such that $\Lambda_J\cap\Lambda_K$ is contained in $\Gamma$ as a finite index subgroup.

Note that the condition "for every $i$, the projection of $\Gamma$ on $G_i$ is dense", sometimes abusively called "irreducible" by confusion with the case $|I|=2$, is not equivalent: it is false for $|I|=1$, and strictly weaker if $|I|\ge 4$.
I think all this material is more or less covered in Raghunathan's book.
Comment: No. In the first version (2 factors), (1) and (7) are not equivalent. I have to think more about other conditions.
Comment: Thank you!  If you allow one of the $G_i$ to be the automorphism group of a tree, does all of this still hold?
Comment: If it helps, I'm particularly interested in the equivalence of 5 and 6 in the case where one of the $G_i$ (say $G_1$) is $Aut(T)$ for T an n-regular infinite tree.  If you think this should be a separate question that is fine.  Cheers.


Employee Shift Scheduling with Multiple Work Centers over time horizon

Question: I'm new to ORTools and trying to implement an algo for employee scheduling problem involving multiple shifts and work centers over month using ORTools,
https://notebook.community/google/or-tools/examples/notebook/sat/schedule_requests_sat,
https://github.com/google/or-tools/blob/master/examples/python/shift_scheduling_sat.py,
etc....
For a given work center, the demand for employees during a given shift is required (for ex.: 3 employees on am shift, 2 employees on pm shift and 1 employee on evening shift. The objective is to assign the selected employees to shifts and work centers.
i did something like this below for 40 employees, 10 work centers and month but the solution ends with some employees with 42 hours and others with like 7 hours....
            shift = {}
            for n in all_nurses:
                for s in all_shifts:  # range(num_shifts):
                    for d in all_days:
                        for l in all_sites:
                            shift[(n, s, d, l)] = model.NewBoolVar(
                                'shift_n%is%id%il%i' % (n, s, d, l))

Each nurse works at most one shift per day.
            for n in all_nurses:
                for d in all_days:
                    model.Add(sum(shift[(n, s, d, l)]
                                  for s in range(num_shifts) for l in all_sites) <= 1)

Each nurse works 5 days week
            for n in all_nurses:
                week = []
                for l in all_sites:
                    for s in all_shifts:
                        for d in all_days:
                            week.append(shift[(n, s, d, l)])
                        # week.append(sum(shifts[(n,d,s)] for s in all_shifts))
                # print(week)
            model.Add(sum(week) == 5)

the  numbers of nurses on day d in shift s at site l should be less or equal to weekly_cover_demands[l][d][s]
      for l in all_sites:
                for d in all_days:
                    for s in range(num_shifts):
                        model.Add(sum(shift[(n, s, d, l)]
                                      for n in all_nurses) <= weekly_cover_demands[l][d][s])

            model.Maximize(
                sum(shift[(n, s, d, l)]
                    for l in all_sites for d in all_days for n in all_nurses for s in range(num_shifts)))

Comment: Please provide toy data thus a minimum reproducible example.
Comment: Can you share the whole algorithm? `weekly_cover_demands` what values does it have (to run exactly please share dataset)
Comment: Algorithm here it is...https://gitlab.com/-/ide/project/pointerxyz/algoshift/tree/master/-/algo_shift_scheduler.py/ thanks....
Answer: There are some problems in your source code.

You want the algorithm to run weekly, but you provided a monthly input as an input. You should either run weekly or add the week numbers.

a) You can change end date with 7 days
dates = {'start': '2021-02-01T00:00:00.000Z',
         'end': '2021-02-08T00:00:00.000Z'}

b) Or you can use week numbers. This option can be more difficult.
all_weeks = range(4)
all_days = range(7)
for n in all_agents:
    for s in all_shifts:
        for w in all_weeks:
            for d in all_days:
                for l in all_sites:
                  ...

model.Add(sum(week) <= 5) line missing tab space.

for n in all_agents:
    week = []
    for d in all_days:
        for l in all_sites:
            for s in all_shifts:
                week.append(shift[(n, s, d, l)])
    model.Add(sum(week) <= 5)

Day range set for only in 7 days, other 21 days there are no constraints. You should add week number iteration described in 2. problem. Or consider the problem as only weekly.

for l in all_sites:
    for d in range(7):
        for s in range(num_shifts):
            model.Add(sum(shift[(n, s, d, l)]
                          for n in all_agents) == weekly_cover_demands[l, d, s])

I recommend to write outputs method as below. Append method increases file size after every run. In each iteration, file is opening again and again, it is not convenient.

with open('___output.txt', 'w') as f:
    for l in all_sites:
        for d in all_days:
            for s in all_shifts:
                for n in all_agents:
                    if solver.Value(shift[(n, s, d, l)]) == 1:
                        print("nurse {} covers shift {} on day {}  at site {}".format(
                            agents[n], s, startschedule + datetime.timedelta(days=d), l), file=f)

Conclusion, the ortools can not find any feasible solution. Please check your constraints or input parameters. I think you should keep the algorithm is simple and think weekly instead of monthly.
Comment: Thanks and happy new year İsmail...il give it try...and keep you posted


What does "three on four, five on seven, etc" mean?

Question: I kinda know they have something to do with polyrhythms, but most search results on google tell me the time signature 3/4 instead of more detail on what that phrase translates to in music..
Is 3 on 4 like playing 3 notes in a 4/4 piece? And does 4 on 3 mean you play 4 notes in for example 3/4? Forgive me for my lack of certainty, I just would appreciate some clarification if it's given to me :)
Answer: There seem to be two separate concepts being conflated in the question: "time signature" and "polyrhythm".
Time signature
In a time signature, the upper number denotes how beats are grouped. An upper number of 4 indicates a cycle of four beats; an upper number of 3 indicates a cycle of 3 beats.
The lower number designates the musical notation corresponding to a single beat. A lower note of 4 means the "quarter note" represents one beat; a lower note of 8 means the "eighth note" represents one beat.
So a time signature of 3/4 means that the musical will be made up of three-beat cycles, with the quarter-note representing a single beat. A time signature of 3/8 also indicates three-beat cycles, but with the eighth-note representing a single beat.
Polyrhythm
Polyrhythm is different. It means that there are two different beat groupings happening simultaneously but in the same amount of total time. A 3:4 polyrhythm would mean that three pulses and four pulses are happening simultaneously within the same total duration. A 5:7 polyrhythm would mean that simultaneous groupings of 5 and 7 beats occur within the same overall amount of time. That is, one grouping divides the total time equally into fifths while the second grouping divides the total time equally into sevenths.
Answer: I'm going to use the British note-duration names, because I think (certainly at times like this) they are less confusing. In 3 4 time the beat isn't a 'quarter' of anything; it's far easier to say "3 4 time is 3 crotchets per bar"
Here are some normal bars in 4 4 time:
X:1
M:4/4
L:1/4
K:C
C C C C | D D  D D | E E E  E ||

You ask

Is 3 on 4 like playing 3 notes in a 4/4 piece?

Yes, it's exactly that:
X:1
K:C
M:4/4
L:1/4
%%staves {(RH) (LH)}
V:RH clef=treble
(3:2:3 C2 C2 C2 | (3:2:3 D2 D2 D2  | (3:2:3 E2E2E2 ||
V:LH clef=bass
C, C, C, C, | D, D,  D, D, | E, E, E,  E, ||

Those treble clef notes are written as minims, but the 3 above is an instruction that they are 'out of time', and you have to look at the context to understand the total time they occupy. By convention, with triplets, the understood total duration is of two of the note-type contained.

And does 4 on 3 mean you play 4 notes in for example 3/4?

You've got it. Here are some normal bars in 3 4 time:
X:1
K:C
M:3/4
L:1/4
C C C | D D D | E E E ||

And here is some "4 on 3" :
X:1
K:C
M:3/4
L:1/4
%%staves {(RH) (LH)}
V:RH clef=treble
(4:3:4CCCC | (4:3:4DDDD | (4:3:4EEEE  ||
V:LH clef=bass
C, C, C,  | D, D,  D,  | E, E, E,   ||

Typically all such constructs are found only briefly in the middle of otherwise 'in time' music:
X:1
K:C
M:3/4
L:1/4
%%staves {(RH) (LH)}
V:RH clef=treble
CCC | (4:3:4DDDD | EEE  ||
V:LH clef=bass
C, C, C,  | D, D,  D,  | E, E, E,   ||

but there's nothing to stop someone writing an entire piece like this:
X:1
K:C
M:4/4
L:1/4
%%staves {(RH) (LH)}
V:RH clef=treble
(5:4 CCCCC | (5:4 DDDDD | (5:4 EEEEE ||
V:LH clef=bass
C, C,C,C,   | D, D, D,D,   | E, E, E, E,  ||

Comment: @BrianTHOMAS https://music.meta.stackexchange.com/questions/3737/abc-shows-up-scrambled-on-first-loading-correct-only-after-page-refresh?rq=1 And the "solution" is found here https://music.meta.stackexchange.com/questions/3556/abcjs-cant-set-clef-in-k-info-field-if-mode-not-fully-specified-and-image-is-c?noredirect=1&lq=1
Comment: @BrianTHOMAS refresh your browser. It's probably ABC not rendering well on SE.
Comment: Er, your first 4/4 sample contains 19 quavers. And your first 3/4 sample is the same 19-quaver 4/4 snippet.


Unable to simultaneously satisfy constraints - UIScrollViewAutomaticContentSizeConstraint

Question: I recently added constraints to my prototype cell on a uitableview view and have run in to this warning when running my application (no errors but see this exception in the console log). I am adding objects to a mutable array dynamically based on specific conditions and inserting to the top of my uitableview. The insert rows also have variable heights.
The issue doesn't occur when I initialize an array with predetermined value, only when I add objects dynamically and push new view controllers.
I understand uitableview contains a scroll view and I have constrained the uitableview, but for some reason the error below says I have a scroll view constraint issue. I am not quite sure what it means.
All of my constraints were created using storyboard on Xcode 5. Dynamically changing height or the cell is done programmatically.
<_UIScrollViewAutomaticContentSizeConstraint:0x17597a10 UITableView:0x18416000.contentHeight{id: 79} == -110.000000>"

)
Will attempt to recover by breaking constraint

<_UIScrollViewAutomaticContentSizeConstraint:0x17597a10 UITableView:0x18416000.contentHeight{id: 79} == -110.000000>

Answer: I had a similar error. I my case I solved it by returning UITableViewAutomaticDimension for the estimated row height, instead of a fixed number:
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath     *)indexPath
{
    return UITableViewAutomaticDimension;
}

I found the solution here: Autolayout Error with UITableView
Answer: Same error with same circumstances, when i changed an entry of the MutableArray (_detailColumns). The error only appeared once, not at following changes!
I had included the Update in
[self.tableView beginUpdates];
[[_detailColumns objectAtIndex:tag]setValue:textViewText forKey:@"content"];
[self.tableView endUpdates];

After removing beginUpdates and endUpdates, the message was gone (?!)


power analysis for multiple logistic regression via simulation vs power.prop.test()

Question: I am using simulation for a power analysis of an experiment tested with a multiple logistic regression model. I find substantial improvements in power for my model with covariate vs without covariate.
# packages
if (!require("pacman")) install.packages("pacman")
pacman::p_load(broom, tidyverse)

Simulating Data with Binary outcome
set.seed(42)

N <- 1000
B_INT <- -.5
B_COV_MC <- .1
B_COND <- 0.43

df <-
  tibble(
    x_int = 1,
    x_cond = rbinom(n = N, size = 1, pr = .5),
    x_cov = rnorm(n = N, mean = 40, sd = 15), # extract from your baseline data
    x_cov_mc = x_cov - mean(x_cov), # mean centering covariate
    y_lor = B_INT*x_int + B_COND*x_cond + B_COV_MC*x_cov_mc,
    y_pr = 1/(1+exp(-y_lor)),
    y = rbinom(N, 1, y_pr)
  )

cor(df$x_cov_mc, df$y) # strong correlation of covariate with outcome

Fitting 1000 models with covariate
set.seed(42)
N_SAMPLING_DIST <- 1e3
p_vector <- vector(length = N_SAMPLING_DIST, mode = 'numeric')

for (i in 1:N_SAMPLING_DIST) {
df_cond_cov <-
  tibble(
    x_int = 1,
    x_cond = rbinom(n = N, size = 1, pr = .5),
    x_cov = rnorm(n = N, mean = 40, sd = 15), # extract from your baseline data
    x_cov_mc = x_cov - mean(x_cov),
    y_lor = B_INT*x_int + B_COND*x_cond + B_COV_MC*x_cov_mc,
    y_pr = 1/(1+exp(-y_lor)),
    y = rbinom(N, 1, y_pr)
  )

m <- glm(y ~ x_cond + x_cov, family = 'binomial', data = df_cond_cov)

p <- tidy(m) %>%
  filter(term == 'x_cond') %>%
  pull(p.value)

p_vector[i] <- p
}

cond_cov_power <- mean(p_vector < .05)
cond_cov_power

81% of simulated models with N = 1000 observed a significant effect for x_cond when controlling for covariates.
Fitting 1000 models without covariate
set.seed(42)
p_vector <- vector(length = N_SAMPLING_DIST, mode = 'numeric')

for (i in 1:N_SAMPLING_DIST) {
df_cond_cov <-
  tibble(
    x_int = 1,
    x_cond = rbinom(n = N, size = 1, pr = .5),
    x_cov = rnorm(n = N, mean = 40, sd = 15), # extract from your baseline data
    x_cov_mc = x_cov - mean(x_cov),
    y_lor = B_INT*x_int + B_COND*x_cond + B_COV_MC*x_cov_mc,
    y_pr = 1/(1+exp(-y_lor)),
    y = rbinom(N, 1, y_pr)
  )

m <- glm(y ~ x_cond, family = 'binomial', data = df_cond_cov)

p <- tidy(m) %>%
  filter(term == 'x_cond') %>%
  pull(p.value)

p_vector[i] <- p
}

cond_power <- mean(p_vector < .05)
cond_power

67% of simulated models with N = 1000 observed a significant effect for x_cond when NOT controlling for covariates.
This improvement in power is in the expected direction, but I am surprised that I have higher reported power from power.prop.test() in base R (see below).
power.prop.test() results
group_means <-
    df_cond_cov %>%
    group_by(x_cond) %>%
    summarise(mean = mean(y))

group_means

Group means are 41% & 53%.
power.prop.test(p1 = group_means$mean[1], p2 = group_means$mean[2], n = N/2)

How can I have 97% power using just my treatment condition in power.prop.test(), when my logistic regression with covariates only achieved 81% power?
Answer: The group means you are using (41%, 53%) depend strongly on the seed.
These appear to be not actually the true marginal average probabilities of your model - note that these were averages of only 1000 samples.
I expect if you instead computed group means over a df_cond_cov that had e.g. 1 million rows, this would fix the issue and probably give you a more reasonable-seeming answer
-
Comment: Thank you @mike, Indeed creating a base sample of 1 million rows estimated more accurate marginal means for the treatment and control groups (e.g., .413 & .488) regardless of seed, and the power.prop.test() output for these marginal means is now in line with my bootstrapped power calculations.


How do I study the "correlation" between a continuous variable and a categorical variable?

Question: What's a meaningful "correlation" measure to study the relation between the such two types of variables?
In R, how to do it?
Comment: @Tomas, if you do that, the estimated strength of the relationship depends on how you've decided to label the points, which is kind of scary :)
Comment: before you ask "how do you study", you should have the answer to "how do you define" :-) BTW, if you project the categorical variable to integer numbers, you can do correlation already.
Comment: @Macro, you are right - another solid argument for having a good definition!
Comment: @Macro Unless I have misunderstood your point, nope. Correlation is insensitive to linear transformations. So cor(X,Y) = cor(a+bX,Y) for finite a and b. The relabeling of a 0/1 as 1/11 does nothing to correlations using that var or its linear transformation.
Comment: @Curious see my comment to Macro above. And note: (1) `X <- sample(c(0,1),replace=TRUE,size=100)` (2) `Y <- X + rnorm(100,0.5)` (3) `corr(Y,X)` (4) `X <- 1 + 10*X` (5) `corr(X,Y)` : same results for both correlations!
Answer: For a moment, let's ignore the continuous/discrete issue.  Basically correlation measures the strength of the linear relationship between variables, and you seem to be asking for an alternative way to measure the strength of the relationship.  You might be interested in looking at some ideas from information theory.  Specifically I think you might want to look at mutual information.  Mutual information essentially gives you a way to quantify how much knowing the state of one variable tells you about the other variable.  I actually think this definition is closer to what most people mean when they think about correlation.
For two discrete variables X and Y, the calculation is as follows: $$I(X;Y) = \sum_{y \in Y} \sum_{x \in X}
                 p(x,y) \log{ \left(\frac{p(x,y)}{p(x)\,p(y)}
                              \right) }$$
For two continuous variables we integrate rather than taking the sum: $$I(X;Y) = \int_Y \int_X
                 p(x,y) \log{ \left(\frac{p(x,y)}{p(x)\,p(y)}
                              \right) } \; dx \,dy$$
Your particular use-case is for one discrete and one continuous.  Rather than integrating over a sum or summing over an integral, I imagine it would be easier to convert one of the variables into the other type.  A typical way to do that would be to discretize your continuous variable into discrete bins.
There are a number of ways to discretzie data (e.g. equal intervals), and I believe the entropy package should be helpful for the MI calculations if you want to use R.
Comment: Thanks. But how high an MI is corresponding to the corr=1 and how low an MI corresponds to corr=0?
Comment: MI has a minimum of 0, and MI = 0 if and only if the variables are independent.  MI has no constant upper-bound though (the upper-bound is related to the entropies of the variables), so you might want to look at one of the normalized versions if that is important to you.
Answer: If the categorical variable is ordinal and you bin the continuous variable into a few frequency intervals you can use Gamma.  Also available for paired data put into ordinal form are Kendal's tau, Stuart's tau and Somers D.  These are all available in SAS using Proc Freq.  I don't know how they are computed using R functions.  Here is a link to a presentation that gives detailed information:
http://faculty.unlv.edu/cstream/ppts/QM722/measuresofassociation.ppt#260,5,Measures of Association for Nominal and Ordinal Variables
Answer: A categorical variable is effectively just a set of indicator variable.  It is a basic idea of measurement theory that such a variable is invariant to relabelling of the categories, so it does not make sense to use the numerical labelling of the categories in any measure of the relationship between another variable (e.g., 'correlation').  For this reason, and measure of the relationship between a continuous variable and a categorical variable should be based entirely on the indicator variables derived from the latter.
Given that you want a measure of 'correlation' between the two variables, it makes sense to look at the correlation between a continuous random variable $X$ and an indicator random variable $I$ derived from t a categorical variable.  Letting $\phi \equiv \mathbb{P}(I=1)$ we have:
$$\mathbb{Cov}(I,X) = \mathbb{E}(IX) - \mathbb{E}(I) \mathbb{E}(X) = \phi \left[ \mathbb{E}(X|I=1) - \mathbb{E}(X) \right] ,$$
which gives:
$$\mathbb{Corr}(I,X) = \sqrt{\frac{\phi}{1-\phi}} \cdot \frac{\mathbb{E}(X|I=1) - \mathbb{E}(X)}{\mathbb{S}(X)} .$$
So the correlation between a continuous random variable $X$ and an indicator random variable $I$ is a fairly simple function of the indicator probability $\phi$ and the standardised gain in expected value of $X$ from conditioning on $I=1$.  Note that this correlation does not require any discretization of the continuous random variable.

For a general categorical variable $C$ with range $1, ..., m$ you would then just extend this idea to have a vector of correlation values for each outcome of the categorical variable.  For any outcome $C=k$ we can define the corresponding indicator $I_k \equiv \mathbb{I}(C=k)$ and we have:
$$\mathbb{Corr}(I_k,X) = \sqrt{\frac{\phi_k}{1-\phi_k}} \cdot \frac{\mathbb{E}(X|C=k) - \mathbb{E}(X)}{\mathbb{S}(X)} .$$
We can then define $\mathbb{Corr}(C,X) \equiv (\mathbb{Corr}(I_1,X), ..., \mathbb{Corr}(I_m,X))$ as the vector of correlation values for each category of the categorical random variable.  This is really the only sense in which it makes sense to talk about 'correlation' for a categorical random variable.
(Note: It is trivial to show that $\sum_k \mathbb{Cov}(I_k,X) = 0$ and so the correlation vector for a categorical random variable is subject to this constraint.  This means that given knowledge of the probability vector for the categorical random variable, and the standard deviation of $X$, you can derive the vector from any $m-1$ of its elements.)

The above exposition is for the true correlation values, but obviously these must be estimated in a given analysis.  Estimating the indicator correlations from sample data is simple, and can be done by substitution of appropriate estimates for each of the parts.  (You could use fancier estimation methods if you prefer.)  Given sample data $(x_1, c_1), ..., (x_n, c_n)$ we can estimate the parts of the correlation equation as:
$$\hat{\phi}_k \equiv \frac{1}{n} \sum_{i=1}^n \mathbb{I}(c_i=k).$$
$$\hat{\mathbb{E}}(X) \equiv \bar{x} \equiv \frac{1}{n} \sum_{i=1}^n x_i.$$
$$\hat{\mathbb{E}}(X|C=k) \equiv \bar{x}_k \equiv \frac{1}{n} \sum_{i=1}^n x_i \mathbb{I}(c_i=k) \Bigg/ \hat{\phi}_k .$$
$$\hat{\mathbb{S}}(X) \equiv s_X \equiv \sqrt{\frac{1}{n-1} \sum_{i=1}^n (x_i - \bar{x})^2}.$$
Substitution of these estimates would yield a basic estimate of the correlation vector.  If you have parametric information on $X$ then you could estimate the correlation vector directly by maximum likelihood or some other technique.
Comment: There is no guarantee that correlation is non-negative, so don't worry if you are getting some negative values.  For error-checking purposes, you should bear in mind that correlation is between $-1$ and $1$ (so if you are getting values outside that range then something has gone wrong).
Comment: Thank you for your answer. I don't have strong statistics background, but is there any guarantee $\hat{\mathbb{E}}(X\vert C=k)\geq \hat{\mathbb{E}}(X)$ (which makes correlation unnegative)? I implemented your approach with some synthetic data, it turns out that some correlations are negative. I am not sure if my implementation is correct. Would it be possible a numerical example provided in your answer?
Comment: Thanks for your clarification. I mistaken correlation for  $R^2$.
Comment: Can you take a look at my another [question](https://stats.stackexchange.com/questions/488035/interpretation-the-correlation-between-continuous-and-categorical-variables) on how to interpret the correlation value?
Answer: If $X$ is a continuous random variable and $Y$ is a categorical r.v., the observed correlation between $X$ and $Y$ can be measured by

the point-biserial correlation coefficient, if $Y$ is dichotomous;
the point-polyserial correlation coefficient, if $Y$ is polychotomous with ordinal categories.

It should be noted, though, that the point-polyserial correlation is just a generalization of the point-biserial.
For a broader view, here's a table from Olsson, Drasgow & Dorans (1982)[1].

[1]: Source: Olsson, U., Drasgow, F., & Dorans, N. J. (1982). The polyserial correlation coefficient. Psychometrika, 47(3), 337–347
Answer: R package mpmi has the ability to calculate mutual information for the mixed variable case, namely continuous and discrete.
Although there are other statistical options like (point) biserial correlation coefficient to be useful here, it would be beneficial and highly recommended to calculate mutual information since it can detect associations other than linear and monotonic.


Solving the Gobblet game

Question: In 1995 the Connect-4 Game was solved with a brute force approach. Using the standard 6 high / 7 wide grid, first player can force a win in 41 moves.
Complexity of the Connect-4 game could be considered as the number of possible disc configurations, which is 4,531,985,219,092 (wiki source).
Gobblet is a zero-sum game with very simple rules and similar goal (rules here).
I would like to write a program which solves the Gobblet Game, but before trying I would also estimate the game complexity. Considering
1,2,3,4

white goblets from the smallest to the greatest and
A,B,C,D

black goblets, if my calculation is fine, a square can be occupied in 81 different ways
empty = 1

1,2,3,4,
A,B,C,D = 8

12,13,14,1B,1C,1D,23,24,2C,2D,34,3D,
A2,A3,A4,AB,AC,AD,B3,B4,BC,BD,C4,CD = 24

123,124,12C,12D,134,13D,1B3,1B4,1BC,1BD,1C4,1CD,234,23D,2C4,2CD,
A23,A24,A2C,A2D,A34,A3D,AB3,AB4,ABC,ABD,AC4,ACD,B34,B3D,BC4,BCD = 32

1234,123D,12C4,12CD,1B34,1B3D,1BC4,1BCD,
A234,A23D,A2C4,A2CD,AB34,AB3D,ABC4,ABCD = 16

e.g the configuration A3D means the smallest black goblet is under a greater white goblet, which is under the biggest black goblet.
But, since we have only 24 pieces total, I expect possible board configurations are much lower than 81^16.
So I wonder how complex the game is, if calculation can be done with accuracy, or at least I would like to know if Gobblet is more or less complex than Connect-4.
Comment: The rules you linked say there are 24 pieces total, are there actually 32 in the version you're considering?
Comment: @MarkS. my bad, 24 pieces total. I was giving 4 complete sets to each player instead of 3.
Answer: Here's a start on improving the $81^{16}$ upper bound.
The total number of ways that gobblets can be placed on the board is no more than
$$\left({16\choose0}+2{16\choose1}+4{16\choose2}+8{16\choose3}+14{16\choose4}+20{16\choose5}+20{16\choose6}\right)^4\\=277{,}993^4\approx5.97\times10^{21}$$
That is, a state of the board is determined by specifying, for each size gobblet, how many of that size are on the board, where they are, and which of those positions are occupied by white gobblets (and which by black).  For example, there are $16\choose4$ ways to pick squares on which to place $4$ small gobblets, and for each of those choices there are ${4\choose1}+{4\choose2}+{4\choose3}=4+6+4=14$ ways to pick which squares are occupied by white gobblets.
This is still only an upper bound, because some of these states are not realizable in actual play, for various reasons.  In particular, it ignores the fact that there cannot be more small gobblets on the board than larger ones (because of the way that gobblets are allowed to enter into play).  It also ignores the fact that the game may end before a given state could be reached.  Nonetheless, $6\times10^{21}$ is several orders of magnitude smaller than $81^{16}\approx3.4\times10^{30}$, so at least it's a start.
Answer: Did you ever complete your project? I am interested in hearing your results.
Building on @Barry's answer: for practical purposes, you can eliminate "equivalent" positions - i.e. all the pieces are in the same place except the board is rotated.
If you imagine a 4x4 board labeled like a chessboard (letters on bottom, numbers on side) then this holds true:
0 | 90 | 180 | 270
__________________
a1 = d1 = d4 = a4
b1 = d2 = c4 = a3
c1 = d3 = b4 = a2
b2 = c2 = c3 = b3

Where the 1st column are the squares when the board is rotated 0 degrees, the 2nd column is the corresponding squares when the board is rotated 90 degrees, and so on.
This means the # of actual positions you must search is on 25% of the total number of possible positions!

Solving the Gobblet game


Should I source control contribed modules in my project?

Question: I've been told that while developing I should source control everything under sites/ into my code repository (e.g SVN).
Assuming I'll never touch any of the contrib modules I use (ctools, views etc) but will only create my own theme, should I still do that?
Or should I just source control everything under sites/all/themes/?
thanks
Answer: In my team, we have moved to only sourcing what is specific to our current project. If we are using Views for example, we add the appropriate entry to our drush make-file, and version that, but not the module itself.
This leaves us with a very small repository, consisting of any custom modules specific to the current site, the current theme, and features exports.
Unless you absolutely can't use drush and drush make, I don't see why one should version control code that is well versioned somewhere else. And if you intend to hack on one of modules, then you should add that as a submodule, again, not versioning the code in your own repo. (I believe this is called a vendor branch in SVN).
Edit: For more details and a more advanced setup, you can take a look at this repository: firstname.lastname@example.com:letharion/Drupal-build-scripts.git The scripts are written in bash to support my teams workflow which includes a building a base-install profile (NodeStream), then our site-specific profile on top of that, a make file for each profile, hooks for applying patches or making other changes on individual build steps etc. I hope I will find the time to re-write it as a drush extension in the near future.
Comment: @Letharion I don't quite understand how this works when developing the same site with various developers at the same time? AFAIK drush make always downloads all dependencies and tries to overwrite sites/default, even if those modules already have been D/L'd, or is there some undocumented option to only download updated/new modules?
In other words: I understand the benefit of using Drush make for installing afresh, but how do you use it for keeping module dependencies synced in a distributed team?
Comment: Thanks for your detailed explanation. Yes, I do use drush and plan to automate as much as possible. And I don't plan to change any code in core or contrib modules.
Comment: +1 versioning the make file is a great idea, think I'll be doing that in future ;)
Comment: I've been using this approach for over a year now but I'm now questioning whether it's really better than just having everything in a repo when working with other developers who may not be re-building the platform every day. Additionally, this approach is not really compatible with the way Acquia structures their repos for their cloud hosting.
Answer: As a counter to @Letharion's answer, putting everything in SVN makes sense for some organizations and it really depends on how you do your rollouts.  Putting contrib modules and themes in SVN can make sense if you ever need to go "back in time" and look at an old version of a site.
One example of this is handy when you suspect a bug in a contrib module, or are seeing different behavior.  Being able to restore a full version from the past can help.
I have also found it handy to have a full site snapshot in SVN when I need to figure out what a client did to a site.  I can take a full snapshot of their version, and stick it in SVN as a branch and compare.
Comment: Using this method enables you to clone an entire installation from version control and a backup, which can be very helpful for development or debugging live sites.
Comment: In order to go "back in time" I'd also need the corresponding full database backup as well. Because some settings and configurations are in the DB. Is that right?
Comment: Yes.  The Backup and Migrate module and/or drush archive-backup is your friend here.


Get value of field attached to the file entity in a view

Question: I extended the file entity of type video, which ships with the media/file_entity module, with an extra field "tags". How can i get the values of this attached field in views?
Answer: You should just need to add a relationship with your file field, then the fields on your file entity should be available when adding fields to your view.
Comment: Yes, that's it!


Error message says 'class' is deprecated, source does not contain 'class'

Question: I've just installed Idris v.1.0 and run the sample code from the Proof section of Rosetta Code, piece by piece. Everything works fine up to the following fragment, which produces the The 'class' keyword is deprecated. Use 'interface' instead. error.
-- 3.1, Prove that the addition of any two even numbers is even.

evensPlus1 : {a : MyNat} -> {b : MyNat} -> (EvNat a) -> (EvNat b) -> (EvNat (a :+ b))
evensPlus1 ea eb = ?proof31

There's not a single piece of 'class' in the source. What could be behind this issue?
Comment: Removing the annotations has solved the initial problem. I still get an error message (Proof 3.1/congS is not accepted) but that seems to be a different matter; probably the Rosetta code was written for a previous Idris version. Thank you for the help, Anton.
Answer: Those are just warnings. The %elim-annotations are described in this deprecated chapter of the manual. You can safely delete them and finish the proof, e.g. like this:
evensPlus1 : (EvNat a) -> (EvNat b) -> (EvNat (a :+ b))
evensPlus1 EvO eb = eb
evensPlus1 (EvSS y) eb = EvSS (evensPlus1 y eb)

congS : {a : MyNat} ->  {b : MyNat} -> (a = b) -> (S a = S b)
congS Refl = Refl

Comment: Everything is fine now, thank you. 'Refl' was written as 'refl' in the Rosetta code.


The depth sensitivity of the Koszul complex

Question: Assume $R$ is a local ring and $M$ a finitely generated $R$-module. Call $K^R$ the Koszul complex of $R$ (over a minimal set of generators of the maximal ideal) and call $K^M$ the complex $K^R\otimes M$. I know the $H_i(K^R)=0$ if $i>\mathrm{edim}\;R-\mathrm{depth}\;R$ (where edim means the minimum number of generators of the maximal ideal).

How can I prove that $H_i(K^M)=0$ if $i>\mathrm{edim}\;R-\mathrm{depth}\;M$?
Comment: Let $R=k[[x]]$ and $M=k[[x]]/(x)$. Let $K^R$ be $R\rightarrow^x R$. Then $K^R\otimes M$ is $M\rightarrow^0 M$, which has higher cohomology.
Comment: Sorry, I did not read the question carefully. So, what I would do is the following. Take a regular sequence to M, and just expand it to have a minimal set of generators of the maximal ideal. Then "the regular sequence does not give you any cohomology", so $H^i(K^M)=0$ if $i>edim R-depth M$.
Comment: I'd say that this property is better known as the [*rigidity of the Koszul complex*](http://books.google.ro/books?id=foG0rKKKXboC&pg=PA278&lpg=PA278&dq=%22rigidity+of+the+koszul+complex%22&source=bl&ots=zmqbMx1a3J&sig=tJzSOK8dkF55VlW--umPQLAcgsw&hl=ro&sa=X&ei=6DfZUdPSMM3XPOS4gaAM&ved=0CFoQ6AEwBg#v=onepage&q=%22rigidity%20of%20the%20koszul%20complex%22&f=true) rather than "depth sensitivity".
Answer: Your claim is an immediate application of Theorem 1.6.16 in Bruns and Herzog, Cohen-Macaulay Rings.


What happens to the Gaussian as $\sigma \to \infty$ at $x \to \infty$?

Question: Does the Gaussian $N(0, \sigma^2)$ have a limiting distribution as $\sigma \to \infty$? And does the density in fact decay to 0 as $x \to \infty$?
If we want the ratio of the density at the mean over the density as $x$ also approaches infinity, we can set up the following iterated limit:
$$L := \lim_{\sigma \to \infty, x \to \infty} f(x)/f(0) = exp(-x^2/2\sigma^2)$$
$$\log L = \lim_{\sigma \to \infty, x \to \infty} -x^2/2\sigma^2$$
But can we solve for L or is it indeterminate? A cursory reading of Ivlev and Shilin (2014) suggests it is in fact indeterminate.
Reference:
Ivlev, V. V., and I. A. Shilin. "On a generalization of l'Hopital's rule for multivariable functions." arXiv preprint arXiv:1403.3006 (2014).
Comment: This question might be more suited to Math Stack  See discussion here https://math.stackexchange.com/questions/177067/lhospital-rule-for-two-variable/177083 There is also paper of Lawlor https://arxiv.org/abs/1209.0363  My understanding that the limit ($\sigma \to \infty, x \to \infty$) may not exist as there is also no simple change of variables.
Answer: The limit $\log L$ is indeterminate because it will depend on the path that $(\sigma,x)$ takes to go to $(\infty,\infty)$.
Below are two examples where both $x$ and $\sigma$ approach infinity while the limiting value of the loglikelihood is different.

If we use $x = n^2$ and $\sigma = n$ then $$\log L = -x^2/(2\sigma^2 )= -n^2/2$$ and the limit will go to minus infinity.

If we use $x = n$ and $\sigma = n^2$ then $$\log L = -x^2/(2\sigma^2)= -1/(2n^2)$$ and the limit will go to zero.

Note that the limiting function of the normal distribution for $\sigma \to \infty$ is not a proper probability density function (because the limit is zero everywhere). What do you wanna do with it? What is it supposed to mean in practice?


How to create a javascript date from 12 hour format

Question: How can I create a Date object from a date with this format:

03/23/2016 02:00:00 PM
Comment: This question has been asked [*many, many times*](http://stackoverflow.com/search?q=%5Bjavascript%5Dparse+date+string). Manually parse strings, either write a function or use a library. **DO NOT** use the Date constructor or Date.parse (they are equivalent for parsing strings). If you wan a simple parser and formatter, consider [*date-format.js*](https://github.com/barbir/js-date-format/blob/master/js/date-format.js).
Comment: Thanks @RobG! Sorry I didn't know what to search honestly.. tried too specific I guess and didn't find what I needed.
Answer: The Date object can parse strings: new Date('03/23/2016 02:00:00 PM')
For example:
var date = new Date('03/23/2016 02:00:00 PM') // => "Wed Mar 23 2016 14:00:00 GMT-0700 (PDT)"
date.getFullYear() // => 2016

However, I would recommend using a library that someone else has already spent time considering the edge cases, like time zones, etc. (a good one I've used is moment.js).
Keep in mind (from the moment.js docs):

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
Comment: The moment.js documentation is not an authority on ECMAScript, please use ECMA-262 for that. In this case, the moment.js documentation is wrong, support for a limited selection of ISO 8601 formats was introduced in ES5, however support is still inconsistent and not to be relied upon. Also, even current browsers do not correctly parse ISO formats, so **always** specify the format or use a bespoke parser.
Answer: var date = new Date("3/23/2016 02:00:00 PM");
console.log(date);

You can then access all the methods of the Date object.
Comment: No, do not do that. Parsing of strings with the Date constructor (and Date.parse, it is equivalent) is unreliable. Just don't do it.
Comment: @RobG - Thank you, you make an excellent point.  Where the code will be used is an important consideration.  If it is a small project for learning, the most expeditous solution may well be the best.  If it is targeted for any professional solution, it should be implemented with strict adherence to standards and best practices.
Answer: Looking at MDN
var date = new Date('03/23/2016 02:00:00 PM')
Comment: MDN is not an authority on anything, it's a (very helpful) public wiki that anyone can contribute to. There is no requirement in the language specification for that format string to be parsed at all.
Answer: You can use something like date.js:
First use script, then write date:

....
document.write(new Date().toString("dd:MM:yyyy hh:mm:ss tt"));

Comment: Parsing **must** include the format too, otherwise the results are unreliable.


Date Picker Jquery exibir em formato d/m/Y e gravar no banco formato Y-m-d

Question: Estou usando este datepicker em meu projeto, já esta configurado como podem ver abaixo o DateFormat no formato d/m/Y, mais gostaria que quando eu fosse salvar no banco ele converteria para o formato Y-m-d, como poderia fazer isso?

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />

<form action="#" method="post">
<input type="text" name="calendario" id="calendario"/>
<input type="submit" value="Enviar">
</form>

<?php
$anos = isset($_POST['calendario']) ? $_POST['calendario'] : '';
echo $anos;
?>
Answer: Tenta utilizar isso:
$dataEnviadoPorPost = str_replace("/", "-", $_POST["calendario"]);
echo date('Y-m-d', strtotime($dataEnviadaPorPost));


Unable to update the table of SQL Server with BCP utility

Question: We have a database table that we pre-populate with data as part of our deployment procedure.  Since one of the columns is binary (it's a binary serialized object) we use BCP to copy the data into the table.
So far this has worked very well, however, today we tried this technique on a Windows Server 2008 machine for the first time and noticed that not all of the columns were being updated.  Out of the 31 rows that are normally inserted as part of this operation, only 2 rows actually had their binary columns populated correctly.  The other 29 rows simply had null values for their binary column.  This is the first situation where we've seen an issue like this and this is the same .dat file that we use for all of our deployments.
Has anyone else ever encountered this issue before or have any insight as to what the issue could be?
Thanks in advance,
Jeremy
Comment: SQL Server I assume... 2005 or 2008?
Comment: Yes, sorry SQL Server 2005.  We've actually run this on Developer and Enterprise Edition so far without issue.  The machine we're seeing issue on is actually running Standard Edition.  I'm not sure if that's contributing to the issue or not.
Answer: My guess is that you're using -c or -w to dump as text, and it's choking on a particular combination of characters it doesn't like and subbing in a NULL. This can also happen in Native mode if there's no format file. Try the following and see if it helps. (Obviously, you'll need to add the server and login switches yourself.)
bcp MyDatabase.dbo.MyTable format nul -f MyTable.fmt -n
bcp MyDatabase.dbo.MyTable out MyTable.dat -f MyTable.fmt -k -E -b 1000 -h "TABLOCK"

This'll dump the table data as straight binary with a format file, NULLs, and identity values to make absolutely sure everything lines up. In addition, it'll use batches of 1000 to optimize the data dump. Then, to insert it back:
bcp MySecondData.dbo.MyTable in MyTable.dat -f MyTable.fmt -n -b 1000

...which will use the format file, data file, and set batching to increase the speed a little. If you need more speed than that, you'll want to look at BULK INSERT, FirstRow/LastRow, and loading in parallel, but that's a bit beyond the scope of this question. :)