Where to put guitar Harmonizer in effects chain?

Question: So where should it be. First in the chain. Or Maybe somewhere near the modulation effects in amp's effect's loop? And why? what are pros and cons?
Let's assume for purpose of this question, we are talking about BOSS PS-6.
I would appreciate the answers from real users and their setups.
Answer: Well, that depends on what sound you're going for :). In all seriousness though harmonizing effects should usually be placed near the beginning of your chain and most definitely before any overdrives for several reasons, the primary of which is: that's where it will track the best. In order to harmonize with a note the unit will need to process input and produce the polyphonic tone. The closer the input is to the real note you are playing (signal degrades as it traverses your board) the more accurate it will be. Placing it behind a normalizing unit like a compressor will also increase the chances that you'll get an accurate note. Finally, it's likely a good idea to place it before any overdrives such that it doesn't have to figure out how to harmonize with distorted overtones that emanate from those units. From my personal experience, my Digitech whammy (a very famous unit that will do octaves along with many other tricks) is placed immediately after my compressor--which is second in line to my guitar after a fuzz pedal. To illustrate:
Guitar --> Fuzz --> Compressor --> Whammy  --> ... --> Amplifier.
You could place in the effects loop providing you don't use any distortion pedals pre effects loop.
Comment: Ahhh- you use compressor after your fuzz. Will need to try that...
Comment: @Jduv - i'm not sure this will cover all the aplications. If as reference we look at predefined effect chains in multi-effects processors, then Yes - Whammy like pedals are located in so called preamp section (and octavers, and wah's too), but harmonizer (and pitch-shifters) is often placed in modulation block after amp. So why is it this way?
Comment: a harmonizer tries to run fourier analysis on the isgnal to figure out what note (or notes) to base it's modulation on. With a lot of notes (or noise) this calculation can be too much so you can hear it flipping between what it thinks are the fundamental.
Comment: @Hubert Dr. Mayhem nailed it. I've never seen a harmonizer placed in a modulation block on all the boards I've worked on, built, or scoped at a concert for the reasons stated by both Dr. Mayhem and my original post. You're free to put it wherever you want of course--but the nature of the effect lends itself to being placed first as I explain in my answer.
Comment: Ok. As time goes by, there is no one else to add his 5 cents. So i accept Your answers guys. Thanks :)


Hide a connectable peripheral device

Question: I am going to program a Bluetooth Smart peripheral device, but I am not quite sure how to achieve it.
The peripheral shall only connect to one central device. Is it possible to tell during (general connectable) advertisement (using advertisement data) that this peripheral does not accept connections from everyone?
Obviously, the peripheral has to be "public" (visible and connectable for any central device) before its first connection, but after that it is only interested in connections to that central device. This is not a privacy or security concern; I just try to not pollute the scan results for other scanning central devices.
I am reading the book "Bluetooth Low Energy - the developers handbook" by Robin Heydon which covers general Bluetooth Smart. It mentions "Flags AD" advertisement data. Could this be what I am looking for? The book also mention "bonding" which I understand is just a long-term secure relationship. I don't need an encrypted link, private address or signed writes, but is it adviced to use bonding anyway in my case?
Comment: It's possible to do "directed advertising".  I haven't used it, but I think it specifies which device it's expecting to connect to it.  So, you could start with regular advertising, and then further advertising would be directed after that initial connection.
Comment: Well, then the only other way, and I'm not ever sure it's possible, is for the device to remain connectable but not advertise.  So the central just tries the connection without receiving an advertising packet because it already knows it's there.
Comment: Hi! I have looked at _directed advertising_ and I think it serves a different purpose. Its advertisement data just consists of two addresses: the advertisers address and the address it wants to connect to. It is an aggresive form for advertisement that is only allowed for 1.28 seconds, according to Robin Heydon. So the central device needs to be continuously scanning to pick up the advertisements directed to it. As far as I understand, directed advertisements lets a peripherial disconnect to save power and then instantly tell the central to reconnect when something happens (seldom).
Comment: I think that a peripheral can not be connected and do advertisements at the same time. My peripheral needs to be connectable which means it must do _general advertising_ (that is, _undirected advertising_). It also allows advertisement data, _AD_. Core Specification Supplement v6 gives some interesting fields for _AD_, which I am looking at now!
Answer: Since I have learned a lot more Bluetooth LE after writing this question, and nobody has answered it, I write an answer here.
A long time relationship between two devices is done by bonding. Bonding causes two devices to exchange and save keys, and these keys will be used for further connections to verify each other. In addition, the keys are used to encrypt the line.
If a general advertising peripheral wants to target a particular central, it does this with advertising data. The Core Specification Supplement (CSS) v6 has two datatypes that can be used for this purpose: Public Target Address (1.13) and Random Target Address (1.14). Or as a developer you can whatever you like into Manufacturer Specific Data in some way of yours.
Since the advertising peripheral targets a particular device, it will probably prevent connections from other centrals. For this purpose use the Whitelist. Put the address of the central you are targeting into the Whitelist, set the filter policy to only allow connections from devices in the Whitelist, and start advertising. But there is a catch: The peripheral needs to resolve the address of the central to ensure it is the one previously bond. Prior to Bluetooth 4.2 this had to be done manually (in application). Instead the 4.2 specification does this automatically for you: Put the bond central into the Resolve List too, and the Link Layer will also do the resolving.

Hide a connectable peripheral device


Submitting HTML Form to Struts 2 Action class

Question: I am trying to submit HTML form to Struts 2 Action class, but after submitting the form, Action class is not getting triggered.
JSP Page:
Timesheet.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Team Activity Log</title>

    <INPUT type="button" value="Add Row" onclick="addRow('matrix')" />
    <%@ taglib uri="/struts-tags" prefix="s" %>
    <s:url id="myActionUrl" action="timesheetprocess" />
    <form action=<s:property value="%{myActionUrl}" />>
    <input type="hidden" id="taskcount" value="5">

    Task Type
    Reference ID
    Description
    Efforts

  <select id="sele">
  <option value="" disabled selected>Select your option</option>
           <option value="SR">SR</option>
           <option value="CR">CR</option>
           <option value="ALM">ALM</option>
           <option value="INCIDENT">INCIDENT</option>
           <option value="OTHER">OTHER</option>
   </select>

   <INPUT type="text" placeholder="E.g:1234"/>

   <INPUT type="text" placeholder="Brief your work"/>

   <INPUT type="text" placeholder="MM min" />

  <select id="sele">
  <option value="" disabled selected>Select your option</option>
           <option value="SR">SR</option>
           <option value="CR">CR</option>
           <option value="ALM">ALM</option>
           <option value="INCIDENT">INCIDENT</option>
           <option value="OTHER">OTHER</option>
   </select>

   <INPUT type="text" placeholder="E.g:1234"/>

   <INPUT type="text" placeholder="Brief your work"/>

   <INPUT type="text" placeholder="MM min" />

  <select id="sele">
  <option value="" disabled selected>Select your option</option>
           <option value="SR">SR</option>
           <option value="CR">CR</option>
           <option value="ALM">ALM</option>
           <option value="INCIDENT">INCIDENT</option>
           <option value="OTHER">OTHER</option>
   </select>

   <INPUT type="text" placeholder="E.g:1234"/>

   <INPUT type="text" placeholder="Brief your work"/>

   <INPUT type="text" placeholder="MM min" />

  <select id="sele">
  <option value="" disabled selected>Select your option</option>
           <option value="SR">SR</option>
           <option value="CR">CR</option>
           <option value="ALM">ALM</option>
           <option value="INCIDENT">INCIDENT</option>
           <option value="OTHER">OTHER</option>
   </select>

   <INPUT type="text" placeholder="E.g:1234"/>

   <INPUT type="text" placeholder="Brief your work"/>

   <INPUT type="text" placeholder="MM min" />

  <select id="sele">
  <option value="" disabled selected>Select your option</option>
           <option value="SR">SR</option>
           <option value="CR">CR</option>
           <option value="ALM">ALM</option>
           <option value="INCIDENT">INCIDENT</option>
           <option value="OTHER">OTHER</option>
   </select>

   <INPUT type="text" placeholder="E.g:1234"/>

   <INPUT type="text" placeholder="Brief your work"/>

   <INPUT type="text" placeholder="MM min" />

    <INPUT type="button" value="Submit" onclick="convert('matrix','taskcount')" />
 </form>

Corresponding action tag in Struts.xml :
<action name="timesheetprocess" class="com.App.Controller.Timesheet.Timeprocess"
            method="execute">
    <result name="success">Time.jsp</result>
</action>

How to submit HTML form to Struts 2 action class?
Answer: To submit a form you can use input element of type submit
<INPUT type="submit" value="Submit" onclick="convert('matrix','taskcount')" />

or as of you already using Struts tags
<s:submit value="Submit" onClick="convert('matrix','taskcount')" />


Erro ao tentar executar Eclipse: Java was started but return exit code =13. A PATH ESTÁ CORRETA

Question: Apaguei versões anteriores ao Java 8  e agora o eclipse não quer rodar, aparece a seguinte mensagem de erro:

" Java was started but return exit code =13.":

Tem um tópico semelhante: já fiz o que dizia a solução do tópico: Erro ao tentar executar Eclipse: Java was started but return exit code =13
Ou seja:
Eu já instalei de novo a JDK 1.7 e coloquei o caminho para ela na variável de ambiente "Path": C:\Program Files (x86)\Java\jdk1.7.0_80\bin
E o erro continua o mesmo.
O que eu posso fazer pra consertar?
Comment: Abrindo o seu terminal de comandos, `java -version` retorna o quê? E `which java`? E `where java`? (eu não lembro se no Windows é `where` ou `which`, mas se você estiver usando `bash` a resposta correta é a contrária da resposta do Windows, então botei as duas opções)
Comment: Aparentemente a VM apontada pelo argumento `-vm` que está no caminho `.../Oracle/Java/javapath` não é a versão 7 da JVM
Comment: estranho, pensei que esses argumentos que pedem pelo Java 7 fosse requerimento mínimo...
Comment: Parece que seu eclipse é 64 bits. Por que instalou o Java 32 bits? [Essa pergunta](https://pt.stackoverflow.com/q/34238/64969) relata o mesmo erro e a resposta foi por todo mundo no mesmo esquema de 64 bits.
Comment: Hmmm, o java -version retorna a versão 1.8....
Comment: Mas como eu altero a VM apontada pelo -vm?
Comment: No diretório onde está instalado o eclipse, tem um arquivo chamado `eclipse.ini`. É nesse rapaz que você altera. Recomendo antes guardar um backup dele, para só depois alterar e por a path desejada.
Answer: Veja se a versão do seu eclipse é a mesma do JDK que você instalou, 64bits ou 32bits, veja a versão no prompt com o java -version.
Verifique se as variáveis de ambiente estão configuradas corretamente, executando o javac no prompt
Caso esteja no windows 10, configurar as variáveis de ambiente é um pouco diferente, se for o caso, siga os passos:
1.Em Pesquisar, procure e selecione: Sistema (Painel de Controle)
2.Clique no link Configurações avançadas do sistema.
3.Clique em Variáveis de Ambiente. Na seção Variáveis do Sistema, localize a variável de ambiente PATH e selecione-a. Clique em Editar. Se a variável de ambiente PATH não existir, clique em Novo.
4.Na janela Editar Variável de Sistema (ou Nova Variável de Sistema), especifique o valor da variável de ambiente PATH. Clique em OK. Feche todas as janelas restantes clicando em OK.
5.Reabra a janela Prompt de comando e execute o código Java.

Fonte Configuração das variáveis PATH
Comment: Pode ser que tenha ficado falhas no registro do Windows, aqui tem um "reparador" que tenta ajustar os registros - https://www.java.com/pt_BR/download/help/manual_regedit.xml
Comment: Eu fiz tudo isso. Só que o problema é que aparece a version 1.8 quando eu dou o comendo java -version
Answer: Eu precisei remover as versões 1.7 x86 e 1.8 x86 do jdk instaladas, com este programa do windows: https://support.microsoft.com/pt-br/help/17588/fix-problems-that-block-programs-from-being-installed-or-removed , e então baixei a jdk 1.7 64 bits (x64), o que resolveu meu problema.


Measuring statistical significance of machine learning algorithms comparison

Question: Let us consider a comparison of two machine learning algorithms (A and B) on some dataset. Results (root mean squared error) of both algorithms depend on randomly generated initial approximation (parameters).
Questions:

When I use the same parameters for both algorithms, "usually" A slightly outperforms B. How many different experiments (with different parameters / updated /) have I to perform to make "sure" that A is better than B?
How to measure significance of my results? (To what extent I am "sure"?)

Relevant links are welcome!
PS. I've seen papers in which authors use t-test and p-value; but i'm not sure if it is ok to use them in a such situation.
UPDATE.
The problem is that A (almost) always outperforms B if initial params and learning/validation/testing sets are the same; but it doesn't neccessarily hold if they differ.
I see the following approaches here:

split data into disjoint sets D_1, D_2, ...; generate parameters params_1; compare A(params_1, D_2, ...,) and B(params_1, D_2, ...,) on D_1;
 generate  params_2; compare A(params_2, D_1, D_3,...) and B(params_2, D_1, D_3,...) on D_2 and so on.
 Remember how often A outperforms B.
split data into disjoint sets D_1, D_2, ...; generate parameters params_1a and params_1b; compare A(params_1a, D_2, ...,) and B(params_1b, D_2, ...,) on D_1; ....
 Remember how often A outperforms B.
first, do cross-validation for A. Then, independently, for B. Compare results.

Which approach is better? How to find significance of the result in this best case?
Comment: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.37.3325
Comment: In that case, I'd probably use the bootstrap, but generate a different initial matrix for each iteration, so that the resampling procedure averages over the variability due to the partitioning of the dataset and due to the initialisation, but I would use the same initialisation in each iteration for both methods.  I'd then use the Wilcoxon signed rank test for performance evaluation (fewer assumptions).
Comment: It would be helpful if you could give a bit more detail about the nature of the machine learning algorithms, in particular what is meant by "randomly generated initial approximation (parameters)" - does this mean something like a random set of initial weights for a neural network, or do you mean somplething like a random choice of kernel parameters for an SVM?  The correct evaluation protocol may depend on the nature of these "parameters".
Comment: This initial approximation is a couple of matrixes filled in with random values drawn uniformly & independently from [0;0.02]. (In fact, I'm comparing matrix factorizations via SGD with different loss functions; this matrixes are initial approximation of factors). So, it's closer to weights for NN
Comment: @YaroslavBulatov The link is no longer available. Can you mention the name of the article and it's author?
Answer:
You have two biases to remove here -- the selection of the initial parameters set and the selection of train/test data.
So, I don't think it is good to compare algorithms based on the same initial parameters set; I would just run the evaluation over few different initial sets for each of the algorithms to get more general approximation.
The next step is something that you are probably doing already, so using some kind of cross-validation.
t-test is a way to go (I assume that you are getting this RMS as a mean from cross validation [and evaluation over few different starting parameters set, supposing you decided to use my first suggestion], so you can also calculate the standard deviation); more fancy method is to use Mann-Whitney-Wilcoxon test.

Wikipedia article about cross validation is quite nice and have some references worth reading.
UPDATE AFTER UPDATE: I still think that making paired test (Dikran's way) looks suspicious.
Comment: Note that if you adjust parameters of an algorithm after seeing its performance on the test set, test set error is no longer guaranteed to be an unbiased estimate of true error.
Comment: I thought so; then stick to paired test, yet don't hide this fact. This is because in a sense you can say that they are equivalent -- B can be better than A when started with luckily picked seed.
Comment: Thank you for your answer!

But I have some doubts. The problem is that A always outperforms B if initial params and learning/validation/testing sets are the same; but it doesn't neccessarily hold
if they differ.
See question update.
Comment: Yaroslav! Actually, I've got learn,validation and test sets. I use validation set to tune some params like regularization term weight and optimization step (via simplex [meta]optimization), while initial weights (the parameters I was talking about before) are not adjusted at all... surely, the test set is used only to calculate quality metrics
Comment: mbq, I'm not sure if I was clear enough =| I do not want to nail this weight
Comment: @bijey It is only that you will get a stronger result showing that A>B in unpaired test.
Comment: ...I do understand that it's better to show that A>B in unpaired test. But I'm afraid, it is very unlikely to show since (informaly) [quality(A) - quality(B)] << variance(quality(A))


Playing a Video and grabbing frames using a timer

Question: I am having trouble playing a video and grabbing frames. I need to grab frames to perform change detection among other things...Is there a way of playing a video and grabbing frames periodically (using a timer) such as using Windows Media Player control on a windows form?
N.B:

I have looked over DirectShow.NET, seems too complicated & involved for such a simple requirement. So don;t want to head that route, unless i absolutely must.
The AVIFile lib won't cut it since I need to support multiple video formats (other than AVI)
Comment: Found this one: http://blog.andrewnurse.net/2008/10/21/VidSpeakPart1ExtractingFramesFromVideoInC.aspx you could try with that otherwise in code project there are samples wrapping DirectShow with c# classes, your task is not trivial so don't be scared of complexity...
Answer: I have done something similar to this in the past with DirectShow.
You are going to get much better results with DirectShow, since you can do you calculations frame by frame rather than on a timer.
These are both examples of motion capture, that use DirectShow:
A
B
Comment: Great! I will look into aforge.net. Thanks.
Comment: Hope this helps someone else in a similar predicament, but I used Aforge.net Motion Detection sample and built my algorithms atop it - it came with video playing, frame capturing etc. Easy peesy.


helloworld in play framework in eclipse

Question: i am new to PLAY frame work , if some one could just help me how to create a simple helloworld application in PLAY in eclipse IDE.
I have already put the play jar file to eclipse dropins.
I have these "new controller", "new view", "new model", "fo to route" options in Eclipse.
How to write HelloWorld in Play (with eclipse).
Thanks
Answer: you should have a look at
'Hello World' tutorial — Your first Play application
http://www.playframework.org/documentation/1.0/firstapp (Play 1.0)
and
http://www.playframework.org/documentation/latest/IDE
if you speak spanish go to http://playdoces.appspot.com
If you are intrested in using play with activator then check this out -
https://quintupledev.wordpress.com/2016/03/01/play-framework-intro-hello-world/

helloworld in play framework in eclipse


Edit Text not allowing to enter value when the value entered is within the range

Question: Below is the code which i use in my edit text to take value only within a certain range
 EditText.setFilters(new InputFilter[]{ new InputFilterMinMax(Min, Max)});

this is my fuction:
 public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int input = 0;
        try {
            input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) {
        }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

This code works when min is 1 and max is 10, but it is not working when min is 20 and max is 30
please help,thanks in advance
Comment: Use `TextWatcher`
Answer: This is because when you start typing '20', the first number is 2, and 2 is not between 20 and 30.
I suggest you to use TextWatcher instead :
TextWatcher textWatcher = new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if(s.length() > 0) {
            int num = Integer.parseInt(s);
            if (num >= Min && num <= Max)
            {
                // Place your logic here. EG : save the number.
            }
            else{
                // Your are not in the desired range.
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
};

EditText.addTextChangedListener(textWatcher);

Answer: public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int input = 0;
        try {
            **if(end==1){
               min = Integer.parseInt(source.toString());
            }**
            input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
            } catch (NumberFormatException nfe) {
        }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

Appending if (end==1) { min = Integer.parseInt(source.toString()); } works fine for me.
However, a better approach for what you are trying to implement is to use TextWatcher as mentioned by Thomas
Comment: When i set min = 20 and max = 25 then it should not allowed 5 as input in edittext.
Comment: As mentioned, it is recommended to use TextWatcher to handle this case. filter will only restrict user to enter a value while using TextWatcher, we can validate if the value lies in the allowed limit.


Is a reconfiguration of running Ingress in Kubernetes possible without downtime?

Question: We are currently facing the following situation:
Ingress1_legacy: service.domain.com
  / >> service_legacy

Ingress2_new: service_one.domain.com, service_two.domain.com
  /one >> service_new_one
  /two >> service_new_two

Our plan is to seamlessly redirect service.domain.com to service_new_one. The idea was now to edit Ingress1 to point to service_new_one like this:
Ingress1_legacy (updated): service.domain.com
  / >> service_new_one

What we experience is, that as soon as we change the configuration of Ingress1_legacy, calls to service.domain.com result in 502. This situation persisted long enough for us to better roll back to the original configuration.
So is this a feasible strategy? Is our assumption right, that the changed configuration of the service-route in the Ingress should allow for a seamless, immediate migration to the other service? Or would a change of an Ingress configuration normally lead to some downtime of the loadbalancing?
Answer: Short Answer: when you update the ingress resource there is a small  downtime due to the process needed both in the Google Cloud Platform and in the Kubernetes one.
I do not exclude that there are way to minimise or cancel the downtime, but if you simply update the ingress you will experience it.

Small experiment
We have the following ingress:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /index.html
        backend:
          serviceName: httpd
          servicePort: 80
      - path: /apache
        backend:
          serviceName: nginx
          servicePort: 80

And 4 service nginx, nxing2, httpd and httpd2 ponting to 4 different deployment each of them on a different node.
Run:
kubectl run nginx2 --image=nginx
kubectl run nginx2 --image=nginx
kubectl run httpd --image=httpd:2.4
kubectl run httpd2 --image=httpd:2.4

and create:
kind: Service
apiVersion: v1
metadata:
  name: httpd
spec:
  selector:
    run: httpd2
  type: LoadBalancer
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
---
kind: Service
[...]

We connect to http://ingress-ip/index.html and we visualise the classical "It works!"
As soon as you change the ingress to point nginx2 and httpd2:

~ 1 minute continue to serve old service
~ 1 minute /nginx leads you to "Error: Server Error" and /index.html "default backend - 404"
after 3 minutes finally we go back to a stable situation


About direct limit of groups

Question: Let $G_i$ be sequence of groups for $i\in \mathbb N$ and Let $\phi_i$ be a monomorphism from $G_i$ to $G_{i+1}$.
Let $\Sigma$ be the direcet limits of $G_i$ under the embeddings of $\phi_i$.
Let $\varphi_i$ be another monomorphism from $G_i$ to $G_{i+1}$ s.t.
$$\phi_i(G_i)=\varphi_i(G_i)$$
i.e their image are same. (but not element wise).
If $\Sigma '$ is the direct limits of $G_i$ under the embeding of $\varphi_i$ then can we say that $\Sigma\cong \Sigma '$ ?
Comment: Clearly, if for all $i$, we had an automorphism $\theta_i:G_i\to G_i$ such that $\theta_{i+1}\circ\phi_i=\varphi_i$ (with $\theta_0=id_{G_0}$), then both whole diagrams $G_0\to G_1\to G_2\to \dots$ would be isomorphic, hence their limit would be isomorphic too.

So, for a first step towards a counterexample let's find $H\le G$ with an automorphism $\vartheta:H\to H$ that doesn't extend to an automorphism of $G$.
Comment: I found this similar to: If a direct limit exists, it is unique up to C-isomorphism
Comment: Cross-posted on MO: http://mathoverflow.net/questions/198766/about-direct-limit-of-groups/198772#198772
Answer: Another simple example (abelian torsion free of rank 2).
Let $G_i=\mathbf{Z}^2$, $\phi_i(x,y)=\phi(x,y)=(px,y)$ and $\varphi_i(x,y)=\varphi(x,y)=(py,x)$. Then $\Sigma_\phi=\mathbf{Z}[1/p]\times\mathbf{Z}$ while $\Sigma_\varphi=\mathbf{Z}[1/p]^2$ (note that $\varphi^2(x,y)=(px,py)$).
[Let us observe that the condition that $\phi_i$ and $\varphi_i$ have the same image is somewhat unstable, since it does not imply that $\phi_{i+1}\circ\phi_i$ and $\varphi_{i+1}\circ\varphi_i$ have the same image.]

About direct limit of groups


Directions of sublevel sets ofa convex function

Question: Let $f:\mathbb R^n \rightarrow \mathbb R$ be a convex (continuous ) function.
Let's assume that some sublevel set $L_a:=\{x\in \mathbb R^n : f(x) \leq a\}$, where $a \in \mathbb R$,   contains a halfline $\{p+tu: t\geq 0\}$ with an initial point $p\in L_a$ and a direction $u\in \mathbb R^n$.
How to show that if $b\in \mathbb R$, $b<a$,  $ L_b \neq \emptyset$ and $q\in L_b$ then also a halfline $\{q+tu: t\geq 0\}$ (with the same direction $u$ as previous) is contained in $L_b$ ?
Answer: I think this is best explained by a picture. The points $P$ and $Q$ are as in your post. The two rays are parallel. We are trying to show that $f(C)\le f(Q)$, given that $f$ is bounded on the ray beginning at $P$.

Using continuity, take a small neighborhood of $Q$ in which $f\le f(Q)+\epsilon$. Draw a line through $C$ which passes through a point in this neighborhood and also meets the ray out of $P$. By convexity,
$$
f(C)\le \frac{|AC|}{|AB|}f(B) + \frac{|BC|}{|AB|}f(A) \tag1
$$
Here $f(A)$ is uniformly bounded, and the fraction $\frac{|BC|}{|AB|}$ can be made as small as we wish by moving $A$ out along the ray. Thus, by taking $A$ far away and $B$ close to $Q$, we get $f(C)$ bounded above by a number arbitrarily close to $f(Q)$.


How to apply scalePagesToFit in another lifecycle moment in Swift?

Question: I am making some simple view based on webView. I wanted to call scalePagesToFit = true simply in viewDidLoad but this didn't work properly. The views that I wanted to fit - were ok, but views that were already showed properly (with no need to resize), have been resized and stretched - and this is what I wanted to avoid. That's the reason I added checking if loaded content is wider than screen.
private var needsResize: Bool = false {
        didSet {
            if self.needsResize == true {
                self.webView.scalesPageToFit = true
            } else {
                self.webView.scalesPageToFit = false
            }}}

 override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        self.webView.scrollView.maximumZoomScale = 20
        self.webView.scrollView.minimumZoomScale = 0.5

       (...)
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        let scrollWidth = self.webView.scrollView.contentSize.width
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenWidght = screenSize.width

        if scrollWidth > screenWidght {
            self.needsResize = true
        }
    }

The main problem is the lifecycle is not working in my favor here. I can measure the content just before viewWillAppear and after viewDidLoad.
I tried to put it in viewWillAppear or viewDidAppear but it didn't seem to work - mainly because the scalesPagesToFit didn't work. The only working so-so solution was putting viewDidLoad in didSet. But You can guess how it was working - the whole view was blinking and reloading for content wider than screen.
Do You have any ideas or hints for me?
Answer: I solved that by moving making new method called e.g. loadWebContent().
I move everything webview loading related here so it's like that
loadWebContent(){
 self.webView.loadHTMLString(text, baseURL: NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath))
}

Then it's called once in viewDidLoad than second time in didSet. And didSet has been rewritten and simplified.
  didSet {
     self.webView.scalesPageToFit = self.needsResize
     loadWebContent()
}

Simple as that! I hope that will help someone.


Proving the highest product of two numbers with a fixed sum

Question: How to prove that any two numbers with a fixed sum have the highest product when both equal half of the sum?
Example:
Given sum equals $10$.
Why is then $5\times5$ more than $6\times4, 7\times 3, 8\times2$, etc.?
Comment: Note that $(5+x) + (5-x) = 10$.  Now consider $(5+x)(5-x)$ and remember that the square of a number is always non-negative.  Adapt this to the general case.
Comment: As an aside, the observation you are asking to prove is a special case of the [AM-GM Inequality](https://en.wikipedia.org/wiki/Inequality_of_arithmetic_and_geometric_means).
Comment: As a further aside, this generalises. To maximise the product of $n$ (positive) numbers $x_1, \dots, x_n$ subject to the constraint that $x_1 + \dots + x_n = c$ for some constant $c$, you want to take all of the $x_i$ to be equal to $\frac{c}{n}$
Comment: Looks like a duplicate of this: https://math.stackexchange.com/questions/403077/proving-the-product-of-two-real-numbers-is-maximum-when-the-numbers-are-equal-gi/4221332#4221332
Answer: $4xy=(x+y)^2-(x-y)^2$ so since $x+y$ is fixed the product is maximum when $x=y$ so that $x-y=0$
Comment: Mark.In 1 line! Very nice.
Answer: Hint: Let $$a+b=s$$ then $$ab=a(s-a)=-a^2+sa$$ where $s$ is given.
Answer: Suppose  $x+y=k $, where $k $ is a fixed real number. We want to maximise $x\cdot y =x(k-x)=f(x)$. Differentiation w.r.t. $x$ will give us $f'(x)=k-2x$. Equating $k-2x $ to $0$ gives $x=\frac k2 \implies y=\frac k2$.
Answer: Sometimes a figure is worth 1000 words.
Given others answerers are providing hints:  Can you see the answer in these (tan) plots of $A = x(n-x)$ for various values of $10 \leq n \leq 20$?
Answer: You want two numbers which give a particular sum and you want to maximize their product:
$$m+n = c \tag{1}$$
$$m(n) = ? \tag{2}$$
You can rewrite the first equation in terms of either $m$ or $n$. For instance, if you choose to express it in terms of $n$, you get $n = c-m$. Plugging this in $(2)$, you get
$$m(c-m) = -m^2+cm$$
If you know about quadratics, functions in the form $y = ax^2+bx+c$, you could use the fact that $a$ is negative here, so the quadratic has a maximum, which occurs at $h = -\frac{b}{2a}$. Using $a = -1$ and $b = c$, you get $-\frac{c}{2(-1)} = \frac{c}{2}$, so the maximum product occurs when both $m$ and $n$ are half their sum (and are equal to each other).
Answer: $$ \left( \;\left( \frac{a+b}{2} \right) - t \; \right) \; \; \left( \; \left( \frac{a+b}{2} \right) + t \; \right) \; = \; \left( \frac{a+b}{2} \right)^2 \; - \; \;  t^2     $$


Active Server Pages error 'ASP 0126' classic asp pls help

Question: our company have a a old classic asp application, we have no choice but to host it. I just moved it to another server. It was perfectly running fine in old server but in this new server it's continuously giving this error. I am running windows 2003 server with IIS 6. Why I am geting this error ? please help.
Active Server Pages error 'ASP 0126'
Include file not found

/application/unprocessed_application.asp, line 56

The include file '../../_fplclass/pdblib.inc' was not found.

Answer: I would change the code to use virtual path instead of file. Also make sure the application pool's user account has read access on that file.
#include virtual=/_fpclass/pdblib.inc
Answer: The path to pdblib.inc is outside of the document root for your site based on the path /application/unprocessed_application.asp.  Make sure you have parent paths enabled on the new server, it is disabled by default in IIS6.
In IIS Manager,

Right-click your web site and click Properties
On the Home Directory tab click the Configuration button
Click Options and then make sure Enable Parent Paths is checked

EDIT:
You'll also get this error if you're using and #include virtual=<path_to_file> instead of #include file=<path_to_file>
Comment: I did it, still facing same problem
Comment: @sagarmatha see my edit


Search View em uma ListView

Question: Estou tentando implementar um Search View em uma List View do meu projeto. Vi alguns tutoriais mas não consegui implantar nenhum pois sempre ocorria um erro aqui e ali pelas peculiaridades de cada lista e código. Por isso venho aos melhores perguntar se alguém pode me ajudar. Peço que sejam o mais específico pois não tenho muita experiência. Obrigado.
 ........

public class ListClientes extends AppCompatActivity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {
ListView lista;
ArrayList<Cliente> clientes;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_clientes);

    lista = (ListView) findViewById(R.id.listview);

    lista.setOnItemLongClickListener(this);
    lista.setOnItemClickListener(this);

    atualizar(null);

}

public void atualizar(View view) {
    ClienteDao cliDao = new ClienteDao();

    clientes = cliDao.getListagem();
    lista.setAdapter(new ClienteAdapter(getBaseContext(), clientes));

}

public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Intent cadClienteIntent = new Intent(this, CadCliente.class);
    cadClienteIntent.putExtra("Cliente", clientes.get(position));
    startActivity(cadClienteIntent);
    return true;
}

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent cadPedidoIntent = new Intent(this, CadPedido.class);
    cadPedidoIntent.putExtra("Cliente", clientes.get(position));
    startActivity(cadPedidoIntent);

}

}

Meu cliente adapter
 .......

 public class ClienteAdapter extends BaseAdapter {

private Context context;
private List<Cliente> clientes;

public ClienteAdapter(Context context, List<Cliente> clientes) {
    this.context = context;
    this.clientes = clientes;

}

public int getCount() {
    return clientes.size();
}

public Object getItem(int position) {
    return clientes.get(position);
}

public long getItemId(int position) {
    return clientes.get(position).getId();
}

public View getView(int position, View convertView, ViewGroup parent) {
    Cliente cliente = clientes.get(position);

    LayoutInflater layout = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = layout.inflate(R.layout.linhacli, null);

    Log.i("AULA", "Montou:" + cliente.getNome());
    Log.e("ERRO", "Valor da variavel estava nullo!");

    ImageView imgImageView = (ImageView) view.findViewById(R.id.imgCliente);
    imgImageView.setImageBitmap(BitmapFactory.decodeFile(cliente.getPathImagem()));

    TextView edNome = (TextView) view.findViewById(R.id.textView1);
    edNome.setText(cliente.getNome());

    TextView lblTelefone = (TextView) view.findViewById(R.id.textView2);
    lblTelefone.setText(cliente.getTelefone());
    lblTelefone.setText(Mask.addMask(cliente.getTelefone(), "(##)####-####"));

    return view;
}

}

Comment: Não se você já fez isso, pelo menos você não comentou. Falta arquivo de layout base para a ListView. por exemplo, você tem o seu activity_main.xml que é o layout onde terá o view ListView e um arquivo a parte xyz.mlx que contem a estrutura de como os dados serão apresentados dentros da view main_activity.xml. E mais uma coisa, é necessário a implementação de um outro adaptador? talvez ArrayAdapter resolvesse seu problema no caso descrito acima
Comment: Sim.. o restante já fiz.. tenho o layout da linha "cliente" no meu caso, acredito que não é necessário outro adaptador..
Answer: Tente assim
na pasta menu
item_menu_pesquisa.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/search"
    android:actionViewClass="android.widget.SearchView"
    android:icon="@android:drawable/ic_menu_search"
    android:showAsAction="always"
    android:title="@string/search_title"/>

</menu>

Na activity
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    // Carrega o xml do menu Pesquisa.
    getMenuInflater().inflate(R.menu.item_menu_pesquisa, menu);
    SearchView sv = (SearchView) menu.findItem(R.id.search).getActionView();
    sv.setOnQueryTextListener(new SearchFiltro());

    return (true);
}

public class SearchFiltro implements OnQueryTextListener {

    @Override
    public boolean onQueryTextSubmit(String query) {
        // TODO Auto-generated method stub
        //Log.i("Script", "onQueryTextSubmit-> " + query);
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {

        if (newText.toString() != null && !newText.toString().equals("")) {
            SeuAdapter adpter = new SeuAdapter(MainActivity.this,
                    new ControleBanco(MainActivity.this).lista_pesquisa(newText.toString()));
            listView.setAdapter(null);
            listView.setAdapter(adpter);
        }

        return false;
    }
}

Search View em uma ListView


Reporting results of linear mixed-effects model

Question: Linear mixed-effects models aren't commonly used in my corner of biology, and I need to report the statistical test I used in a paper I'm trying to write.  I know that awareness of multilevel modeling is starting to appear in some areas of the biosciences (A solution to dependency: using multilevel analysis to accommodate nested data), but I'm still trying to learn how to report my results!
My experimental design, in brief:
*Subjects were assigned to one of four treatment groups
*Measurements of the dependent variable were taken on various days after the start of treatment
*The design is unbalanced (unequal numbers of subjects in the treatment groups, and missing measurements for some subjects on some days)
*Treatment A is the reference category
*I centered the data at the final day of treatment
I want to know whether Treatment A (the reference category) yields significantly better results than the other treatments (at the end of treatment).
I did my analysis in R, using nlme:
mymodel <- lme(dv ~ Treatment*Day, random = ~1|Subject, data = mydf, na.action = na.omit,
+ correlation = corAR1(form = ~1 |Subject), method = "REML")

And the output (in part; truncated for brevity) is:
>anova(mymodel)
              numDF denDF  F-value p-value
(Intercept)      1   222 36173.09  <.0001
Treat            3    35    16.61  <.0001
Day              7   222     3.43  0.0016
Treat:Day       21   222     3.62  <.0001

>summary(mymodel)
Fixed effects: dv ~ Treatment * Day
                       Value Std.Error  DF  t-value p-value
(Intercept)         7.038028 0.1245901 222 56.48945  0.0000
TreatmentB          0.440560 0.1608452  35  2.73903  0.0096
TreatmentC          0.510214 0.1761970  35  2.89570  0.0065
TreatmentD          0.106202 0.1637436  35  0.64859  0.5208

So, I know that the effect of Day differs by Treatment, and that, on the final day of treatment (where the data are centered), dv is significantly different in Treatment A than Treatments B or C.
What I want to say is:  "As predicted, we found that Dependent Variable was significantly lower in subjects receiving Treatment A (mean +/- SE) than in subjects receiving Treatment B (mean +/- SE, p=0.0096) or Treatment C (mean +/- SE, p=0.0065), as measured on the final day of treatment."
But, I have to indicate what statistical test was done.  Would this be an acceptable way to describe the analysis?  "[Measurement Method] was performed on days indicated and Dependent Variable (units) was determined; we analyzed the log-transformed data using a linear mixed-effects model centered at [final day of treatment].  Symbols represent mean dv; error bars are standard error.  On the final day of treatment, dv was significantly lower in Treatment A (mean +/- SE) than Treatment B (mean +/- SE, p=0.0096)..."
Specifically,
*Does that say enough about the statistical test used?  (Readers are used to seeing something more like "mean +/- SE, p=0.0096, Student's t-test," but it seems weird to write "p=0.0096, coefficient for Treatment B vs. Treatment A from linear mixed-effects model at [final day of treatment].")
*Is there a better way to put this?
(The methods section will include more information about the stats: "[Measurement Method] data were analyzed using R and the R packages... We analyzed the log-transformed Dependent Variable data by using linear mixed effects models using Subjects as random effects and an autocorrelation structure of order 1 (AR1).  As fixed effects, we included Treatment and Day, and the interaction of Treatment and Day.  We checked for normality and homogeneity by visual inspections of plots of residuals against fitted values.  To assess the validity of the mixed effects analyses, we performed likelihood ratio tests comparing the models with fixed effects to the null models with only the random effects.")
Any advice on how to report results of a linear mixed effects model for an often stats-averse audience (and written by a relative stats novice) would be greatly appreciated!
Comment: can you explain more regarding what you mean by 'centered' on the last day of the study? why not just pump in day as 0 through number of days on the last day of the study? Also- in your summary table- where are the interaction effects?
Answer: This may not help answer your question, but I noticed that you have a repeated measure (Day) in your experiment, but you did not indicate that this was a repeated measure in your model. I would have thought the random term in your model to be as such:
mymodel <- lme(dv ~ Treatment*Day, random = ~1|Subject/Day,
               data = mydf, na.action = na.omit,
               correlation = corAR1(form = ~1 |Subject/Day), method = "REML")

As for reporting the results, did you intend to report on the day on which you start seeing significant differences between the treatments? If so, then I think you'll need to look at/report on the contrasts on the interaction term as well. I'm a stats novice myself and basically have the same question as you do :-)
Andy Field's "Discovering Statistics Using R" explains how to report results from a linear mixed effects model in Ch14. I don't have the book at hand but can edit this post once I get my hands on it again.
Comment: that depends, if the Day is the same for all Subjects, I guess it is a crossed rather than a nested random factor, right? Then it's $random=~Day|Subject$ because day is continuous it is placed in front of the vertical line. Comments appreciated!


Spark benchmark setup

Question: I would like to do a benchmark on Spark which consists in:
Have 10TB of uncompressed data where each line is at this format: float;float;string.
The job will basically do :

map on lines to split
filter on the string
reduceByKey where key is based on the two floats.
store result in HDFS

Question are :
 - how much disk space should I have
 - how much memory
 - what are the parameters for the job (#exec, #core, #mem) and for yarn-site.conf
Currently I have 15To of storage on 10 nodes (16Cores, 16GB, 1.5To of storage) and it fails like :

ERROR client.TransportClient: Failed to send RPC 6631382768729976966 to benchophadoopslaves1/A.B.C.D:43365: java.nio.channels.ClosedChannelException
  java.nio.channels.ClosedChannelException
  17/07/06 17:05:42
WARN netty.NettyRpcEndpointRef: Error sending message [message = Heartbeat(41,[Lscala.Tuple2;@4f4d418,BlockManagerId(41, benchophadoopslaves1, 34521))] in 3 attempts
  java.io.IOException: Failed to send RPC 6631382768729976966 to benchophadoopslaves1/A.B.C.D:43365: java.nio.channels.ClosedChannelException
          at org.apache.spark.network.client.TransportClient$3.operationComplete(TransportClient.java:239)
          at org.apache.spark.network.client.TransportClient$3.operationComplete(TransportClient.java:226)
          at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:680)
Answer: A friend gave me an hint: give 10GB to the driver. And it works

Spark benchmark setup


Different prediction score for two SVM-based classifiers

Question: As a validation study, I use two libsvm-based svm classifier against the same data set.
One classifier is libsvm implementation in Rapidminer. Another classifier is Libsvm itself. Both of them assume the same parameter setting.  However, the prediction score of these two classifiers are different.  What might be reason to cause this kind of difference?
Comment: By prediction score you mean $f(x)=(w,x)+b$? What about data normalization, is it used/not used in both cases? What about default parameters of the functions that you are calling, do they have the same values in both cases?
Answer: All:

Rapidminer
WEKA
milions of more

use the libsvm library, which are the same implementations. The only actual difference is how they use it. As underlying code of libsvm is just a numerical optimizator, there is a number of thing that can influence the quality of resulting classifier.
First of all, libsvm requires definition of a eps parameter that is used in the optimisation process as a threshold value - this is the most common difference between libraries. The second thing is use (or lack of it) of shrinkage heuristics, which guides the optimisation process, and with previously mentioned eps variable can lead to different results.
Those were "deep" reasons for such behaviour. The most simple explanation is... data preprocessing - SVM does not work well on the raw data (which have large disproportions in the input data dimensions), there are at least few possible ways of dealing with it:

squashing the data linearly to the [-1,1] dimension-wise
transform the data through C^(-1/2) where C is adata covariance matrix

and again - each "meta library" can use its own method of such preprocessing. And the way it is done greatly influences the results.
Answer: I know this is a late answer to your question, but I've recently come across a similar situation in my own research. Just out of curiosity, I did a parameter optimization experiment for the c-parameter in a linear svm, in which I wanted to compare the performance of svmlight and the Weka svm implementation. For both approaches, I was classifying the same textual data in 5x2 cross-validation, using binary feature modeling, and bag-of-words unigrams. My findings surprised me: svmlight consistently performed at least 0.10 better (in terms of area under the curve), compared to Weka! I bring this up here, because I think your question raises an interesting point that people don't always think about: not all implementations of svm are the same, and perhaps they should not be treated as such! I think a lot of people will try out the Weka svm on their data (either because it Weka is commonly used, or because it's easier than using a specific implementation like svmlight or libsvm), and falsely conclude, "svms are not good for my data." As to why this is, I am as yet unclear. Perhaps there are differences in the quality of the code, or the optimization routines used in each? I'm going to look into this further!
Comment: The outcome of SVM training is not subject to change for a given problem. If the training problems for two solvers, e.g. svmlight and libsvm, are exactly the same, their respective solutions should be too. The solution to an SVM training problem is a global optimum and is therefore unique. If you get different solutions, there *must* be something else happening to the data.


Is there a sharing library for programmed drums for musicians to play along with that are like the real song they are playing?

Question: I'm in a hobby basement band we use a drum machine, Dr. Boss. We play Rock music. We program the drums to sound as close as possible to whatever song we are playing which is very tedious. Does anyone know if there is a sharing library of drums that we can borrow. We could share ours too, ours are on floppy discs. Know where we could purchase drum tracks for our machine?
Comment: Have you thought about actually getting a drummer?
Comment: I'm guessing that you won't find many people in this century that will be excited about trading floppy disks in the mail. :)
Comment: What is the model number on your machine?
Answer: Well, I can't advice a concrete library for a specific hardware you're specified there, but I can advice you next thing:
There's a lot of sites on the internet which have tabulatures in Guitar Pro or power tab format. If you can a bring a PC to your rehearsal place, and connect it to a speakers, your problem would be solved.
For example, you can look at the site http://ultimate-guitar.com, which have tabs in guitar pro format for almost every widely (and not really widely) known songs. Those tabulatures often (in 90 of cases) contain a drum track. You can buy needed software, open that tab, select to play only a drum track, turn on the RSE (realistic sound engine), and probably you'll receive a quite good drum backing track.
Or, also, you can export that drum track in midi format to FL studio or some other sequencer and run it with  plugin like EZDrummer (for example) or some other wave table plugin which have real drum sounds. So that option also would give you a quite well drummer sound too.
Comment: As I said, he can extract a drum track from the tab, export it to a midi, then import it into a FL studio, run it in Ez Drummer and a receive a quite good sound.


Interpreting dispersion for Inverse Gaussian GAM (log linked)

Question: After reading Wood (2006), Zuur et al. (2009) and all questions related to GAMs here, I still haven't found the following:

Should I calculate the dispersion for an inverse.gaussian GAM (link = 'log') with the following formula: $${\rm dispersion}=\frac{\sum({\rm residuals})^2}{N-p}$$ in which $N$ is the amount of samples and $p$ is the length of the coefficients of the GAM?
How to interpret the result? In my case 0.001154391.

I understand that for Poisson and binomial distribution the dispersion is or should be 1 and that this is not the case for Gaussian families, but I don't understand what this dispersion calculation will actually tell me.
Answer: I asked somebody in my research institute with statistical knowledge and he said that you should only calculate the dispersion for Poisson and binomial distributions.
Comment: I wonder if you may be caught up in a semantic blurring of the word "dispersion" which has a specific meaning in count-based models, but is also sometimes used as a synonym for "variability". The formula you gave in your question is a measure of **variance** specifically, which speaks to the latter concept, but not necessarily the former.


*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Start date cannot be later in time than end date!'

Question: I am using Alamofire and after several hours of my app running on the simulator I got a crash with this error.

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Start date cannot be later in time than end date!'

I got this stack trace in console:
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000111186d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000110be821e objc_exception_throw + 48
    2   Foundation                          0x00000001107f0e3c -[_NSConcreteDateInterval dealloc] + 0
    3   CFNetwork                           0x00000001131a18e8 -[__NSCFURLSessionTaskMetrics _initWithTask:] + 868
    4   CFNetwork                           0x00000001131a1497 -[NSURLSessionTaskMetrics _initWithTask:] + 100
    5   CFNetwork                           0x0000000112f77bc7 -[__NSCFURLLocalSessionConnection _tick_finishing] + 351
    6   libdispatch.dylib                   0x00000001128e3978 _dispatch_call_block_and_release + 12
    7   libdispatch.dylib                   0x000000011290d0cd _dispatch_client_callout + 8
    8   libdispatch.dylib                   0x00000001128eae17 _dispatch_queue_serial_drain + 236
    9   libdispatch.dylib                   0x00000001128ebb4b _dispatch_queue_invoke + 1073
    10  libdispatch.dylib                   0x00000001128ee385 _dispatch_root_queue_drain + 720
    11  libdispatch.dylib                   0x00000001128ee059 _dispatch_worker_thread3 + 123
    12  libsystem_pthread.dylib             0x0000000112cbc736 _pthread_wqthread + 1299
    13  libsystem_pthread.dylib             0x0000000112cbc211 start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Did someone get the similar crash?
Thanks
Comment: Post some code you are dealing with dates
Comment: Yes, I use some dates in my app but I am unable to know what dates cause this crash as you can see on the stack trace.
Comment: Post the code where you are using dates and how
Answer: I had the same crash and did some research today and found this:
http://www.openradar.me/28301343
It looks Apple fixed the issue in iOS 10.2. just thought it may help you!
Comment: This is perfect. Thanks.
Answer: Yes I just got the same exact crash. It happened in a background thread and it seems to have to do with making a URL session network request. I wonder if it's some sort of multithreading bug having to do with the fact that I'm making two network requests at the same time. I'm using Alamofire as well but not sure if the bug lies in Alamofire or in Apple's code. I've been unable to reproduce it as of now. Maybe you can figure out how to reproduce it and then file an issue in Apple's bug radar or in the Alamofire GitHub repo.
Comment: Seems really similar. Thanks!
Answer: This is a bug in Apple's NSURLSessionTaskMetrics code and happens during a network request when the user's clock gets moved far enough backwards that the request start timestamp is after the request end timestamp. This is reproducible using a network debugging proxy and manually adjusting the clock, and only occurs from iOS 10.0 up to but not including iOS 10.2
If you're using Alamofire, and you don't need NSURLSessionTaskMetrics, you can work around this by using a custom SessionDelegate for your SessionManager and overriding the responds(to aSelector..) function e.g:
class MySessionDelegate: Alamofire.SessionDelegate {
    override public func responds(to aSelector: Selector) -> Bool {
        let result: Bool = super.responds(to: aSelector)
        if #available(iOS 10.2, *) {
            // NSURLSessionTaskMetrics date crash is fixed
            return result
        } else if #available(iOS 10.0, *) {
            // NSURLSessionTaskMetrics date crash is not fixed, turn off metric collection
            if aSelector ==  #selector(self.urlSession(_:task:didFinishCollecting:)) {
                return false
            } else {
                return result
            }
        } else {
            // NSURLSessionTaskMetrics doesn't exist
            return result
        }
    }
}

If you're using the default SessionManager (e.g. calling Alamofire.request(...)) you can create your own SessionManager instead in order to use your custom SessionDelegate:
let sessionManager: Alamofire.SessionManager = {
    let configuration: URLSessionConfiguration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
    return Alamofire.SessionManager(configuration: configuration, delegate: MySessionDelegate(), serverTrustPolicyManager: nil)
}()

And now instead of calling Alamofire.request(...) you'd call sessionManager.request(...)
Comment: Hey did this work for you? Unfortunately this doesnt fix it for me, the only way to stop crashing is if i go into SessionDelegate and remove didFinishCollecting method., what crash are you having?
Comment: This worked for me, and should be the same as removing the didFinishCollecting method (without having to modify Alamofire). I was getting/reproducing the exact same crash as in the original question.
Are you perhaps using AlamofireImage, or not using this SessionDelegate for all your requests?
Comment: Yes i still get the error. I am using Alamofire, and just upgraded to XCode8.2, i dont see the issue in 10.2 just between 10.0 and 10.1 as people mention it here.
I have added your code, and tbh i agree with you that the code should work, however it seems URLSession is looking for the metrics method in some other way it seems. I am still getting this error. I will do furher debugging and i will look to see i can find a fix around this without removing the metrics method.
Answer: I have been struggling with this problem in an os x application for the last few months and have found a workaround.
Background:
Like the OP am using Alamofire to request JSON data via a Timer to send requests several times per second.  The data comes in as expected however I get random crashes at irregular intervals with the same message as the OP i.e. Start date cannot be later in time than end date! etc etc.
Solution:
Rather than send Alamofire requests at a regular interval I added some logic which checks for a return of the previous request before sending the next one.  This completely eliminated the random crashes.
Hope it helps :)
@thierryb


How to write `performSelectorInBackground: afterDelay:` in one line of code?

Question: There are methods performSelectorInBackground: and performSelector: afterDelay: in NSObject. How to combine them in one line of code?
Maybe somehow with NSTimer?
Comment: your intent is to:
- a) perform a selector on a background thread after a delay, or
- b) to perform a selector on a background thread *and* perform it on the current thread after a delay
Comment: Justin, did you pay attention to question title?
Answer: Have you considered using blocks for that?
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),
^(void){
    //your code here
});

Also, if it seems like too much writing, there's already a snippet for it, start typing "dispatch_after" and you'll see it.
Answer: NSTimer
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:NO];

Comment: This will still execute on the current runloop.


Struggling with getting data from another activity

Question: I can transfer my array-data from an activity to the other, but not my string-data, and I don't know why.
This is my mainActivity:
protected void onClickCityBreak(View v) {
    persons = (EditText) findViewById(R.id.txtPerson);
    days = (EditText) findViewById(R.id.txtDays);
    String p = persons.toString();
    String d = days.toString();
    String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
    Intent myintent = new Intent(MainActivity.this, TripActivity.class);
    myintent.putExtra("PERSONS", p);
    myintent.putExtra("DAYS", d);
    myintent.putExtra("PLACES",arrayCityBreak);
    startActivity(myintent);
}

This is my other activity I am sending to:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trip);

    String person = getIntent().getStringExtra("PERSONS");
    String day = getIntent().getStringExtra("DAYS");

    TextView txtPerson = (TextView) findViewById(R.id.txtViewPersons);
    txtPerson.setText("Persons travelling: " + person);
    TextView txtDay = (TextView) findViewById(R.id.txtViewDays);
    txtDay.setText("Days of traveling: " + day);

    String[] arrayCityBreak = getIntent().getStringArrayExtra("PLACES");
    ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
    ListView myview = (ListView) findViewById(R.id.lstView);
    myview.setAdapter(adapterCityBreak);
}

I get this on my TextView in the application:
android.support.v7.widget.AppCompactEditText{13e7726VFED...CL. ........563,56....#7f0c0059 app:id/txtDays\

The same for txtPerson.
I have also tried using Bundle
Answer: Getting the content of an EditText should be done in this way :
 String p = persons.getText().toString();
 String d = days.getText().toString();

Comment: Do you know how to add subitems to the array aswell?
Comment: @guliing Create a separate question with your code snippet and what you are trying to accomplish.
Answer: Also if you have another problems with putExtra, you can do something like this:
MainActivity:
protected void onClickCityBreak(View v) {
    persons = (EditText) findViewById(R.id.txtPerson);
    days = (EditText) findViewById(R.id.txtDays);
    String p = persons.getText().toString();
    String d = days.getText().toString();
    String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
    Intent myintent = new Intent(MainActivity.this, TripActivity.class);
    AnotherActivityClass secondactivity = new AnotherActivityClass();
    secondactivity.persons = p;
    secondactivity.days = d;
    secondactivity.places = arrayCityBreak;
    startActivity(myintent);
}

Create public string persons and days, also create public String[] in SecondActivity:
public String days;
public String persons;
public String [] places;

And then in SecondActivity use this values:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trip);

    TextView txtPerson = (TextView) findViewById(R.id.txtViewPersons);
    txtPerson.setText("Persons travelling: " + person);
    TextView txtDay = (TextView) findViewById(R.id.txtViewDays);
    txtDay.setText("Days of traveling: " + day);

    ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
    ListView myview = (ListView) findViewById(R.id.lstView);
    myview.setAdapter(adapterCityBreak);
}


Find the smallest natural number k such that between k different and in pairs relatively prime natural numbers less than 2021 there's a prime number

Question: Find the smallest natural number $k$ such that between $k$ different and in pairs relatively prime natural numbers less than $2021$ there's a prime number.
Honestly have no idea how to start here so if anyone could share a hint that'd be great.
Answer: Hint: Suppose that you have a maximal set $S$ (in terms of cardinality) of non-prime natural numbers such that any two numbers in $S$ are relatively prime. Then, show that you can obtain a set $S'$ of non-prime natural numbers satisfying the given condition such that $S'\subseteq T:=\{1\}\cup\{p^2<2021|p \text{ is prime}\}$ and $|S|=|S'|$. To see this, take an element $s\in S$ that is not in $T$. Then, $s={p_1}^{r_1}{p_2}^{r_2}\ldots{p_n}^{r_n}$ for some $n\geq1$, $\;\;r_1,\ldots,r_n \in\mathbb{N}$ and primes $p_1<p_2<\ldots<p_n$. Now, observe that you could replace $s$ by $p^2$ and have all the required properties satisfied. Inductively, you can obtain $S'$. Now observe that $T$ is a set of non-prime natural numbers such that any two numbers in $T$ are relatively prime and $|S|=|S'|\leq|T|$. Infer that $k=|T|+1$.
Comment: No @Cookie count 1 and primes. That is $|\{1,2,3,5,...,41,43\}|$+1=16
Comment: So from there the solution should be $45$? As $45^2=2025>2021$


Select entity to display using drop down list

Question: My problem is that I want to add a drop down list to a node that selects an entity from that node based on its name, and display it.
I am wondering if there is a module that does that; if there isn't, what the best approach is.
So far, I can only think of creating a custom node template to display the entities using JavaScript.
Unless I am mistaken, the Entity reference module won't work in my case; if it does, please clarify.
I have 4 tables in a single node; each table represents a week in a month. I want just a simple drop down list to select which week to display, and display that week's table.
Comment: Try http://drupal.org/project/entityreference
Answer: Checkout the Entity reference module.

Provides a field type that can reference arbitrary entities.
Comment: this will not work with my case
Comment: Why won't this work?  This is the defacto standard for referencing one node from another.
Comment: @MPD I am not referencing a node from another node I just want to hide and show entities in the node view based on a select list
Comment: @Sari  Actaully, this is how you would build out the content type.  You would add in your entity refs, configure the display (probably want rendered entity, and then write some custom JS to make your select work.
Comment: @MPD Why would I use reference to reference entities from the same node and then add JS to hide the not selected entities when I can add a select list in the template or using node_view and add the same JS to it.
Answer: seems no one can answer so I did what I first thought of for the sake of documentation
I added this to my node template node--NODENAME.tpl.php
<code><?php drupal_add_js('sites/all/themes/MYTHEME/scripts/scripts.js');?>
    <select id='showmethemoney'>
        <option selected="selected" value="field-name-field-week1">week1</option>
        <option value="field-name-field-week2">week2</option>
        <option value="field-name-field-week3">week3</option>
        <option value="field-name-field-week4">week4</option>
    </select>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content['field_week1']);
      print render($content['field_week2']);
      print render($content['field_week3']);
      print render($content['field_week4']);
      print render($content);
    ?>
</code>
and Created a js file "sites/all/themes/MYTHEME/scripts/scripts.js" with the following code :
<code>(function ($) {
Drupal.behaviors.MYTHEME = {
attach: function(context, settings) {

 $(function() {
        $('#showmethemoney').change(function(){
            $('.field-type-text').hide();
            $('.' + $(this).val()).show();
        })
     .change();
    });

}
};
}(jQuery));
</code>
this will show the selected field by default and will display the field I want from the select list
thanks for your time


Upper bound on real roots of depressed cubic

Question: Given a depressed cubic equation
$$x^3+px+q=0,$$
with $p$ and $q$ negative real numbers, is there an easy upper bound for its real roots in terms of $p$ and $q$? The sharper the better, of course.
EDIT: I had little clue how to approach this problem. I tried substituting polynomials of low degree in $p$ and $q$ for $x$, such as $x=p+q$ and $x=\sqrt{-p}$ to see whether the result would be positive or negative in general, but to little avail. I don't see how to approach this constructively, or how to find simple expressions to plug in that will always yield a positive result.
Comment: There is exact values which are kind of both upper and lower bounds at the same time? What exactly are you looking for?
Comment: If $q, p$ are positive then an easy bound is $q/p$
Comment: @vrugtehagel From what I recall these expressions are somewhat unwieldy involving many choices of signs, and it is not immediately clear which choices of signs yield the largest value. Do please correct me if I am overlooking something obvious.
Comment: @MathUser_NotPrime Coincidentally the examples I am looking at have $p$ and $q$ both negative.
Answer: There is a general bound $M$ on the moduli of the (real or complex) roots $\,\xi_i\,$ in $\mathbf C$ of a polynomial of any degree  $n$ in $\mathbf C[x]$, $ a_n x^n+a_{n-1}x^{n-1}+\dots+a_1x+a_0\enspace (a_n\ne 0)$:
$$|\xi_i|\le M=\max\biggl(1, \frac{|a_{n-1}|}{|a_n|}+\dots+\frac{|a_{0}|}{|a_n|}\biggr). $$
For a depressed cubic, this yields the bound $\; M=\max(1,|p|+|q|)$.
On the other hand, Sturm's algorithm yields the exact number of distinct real roots in a given interval.


T-Test or Wilcoxon Rank Sum Test?

Question: So, for an experiment I analyzed behavioral data of two different treatment groups with $n = 30$ for each of two groups, so 60 subjects in total. I used a computational model to analyze the data and calculate a specific score that describes the motivation to obtain a specific reward.
This score is a continuous variable, but according to a Shapiro-Wilk test, the distribution of the data is non-normal. According to a two-sided Wilcoxon rank sum test, the difference between both groups is not significant ($p \approx .08$).
However, after performing an alternative (model-free) analysis by using logistic regression, I actually found a significant effect of treatment group on behavior.
Additionally, after performing a two sided t-test with the computational data, I also found a significant difference between both groups ($p \approx .04$).
Now the information that I have are quite contradictory. Some say that a sample size of 30 is sufficient to use a t-test, even if the data is not normally distributed. Other sources say that I still should use a u-test, even for "larger" sample sizes.
So I'm a bit confused. Of course, the results of the t-test fit with my hypothesis and the model-free findings. On the other hand, I want to use the "appropriate" test, not the one that confirms my hypothesis.
What do you think? Is my sample size big enough to use a t-test? Or should I go with the u-test, even though it contradicts the results of my alternative method?
EDIT: This is how the boxplot of my data looks like (adapted to the code below)
Comment: I am afraid that, by running so many tests in search of significance, you may have tainted your analysis. [XKCD](https://xkcd.com/882/) has a good cartoon along these lines.
Comment: Your two p-values, .04 and .08 really aren't that much different.  Both the t-test and the Wilcoxon test work fine at any sample size, though a practical minimum might be 4 or 5 observations per group for both tests. The Wilcoxon test doesn't really fix the problem of unequal variances; it works best when the the variances are equal but the distribution of the tails is higher than for the normal distribution. You might consider Welch's modification of a t-test, designed for unequal variances. You might describe the distribution of your values a little more.
Comment: The plot was made in R and R's `t.test` function defaults to Welch correction so chances are, that the t test result already was a Welch test result.
Comment: Depending of the units of the x-axis it may be that a difference between means of approx. 0.6 is not worth a discussion about its statistical significance.
Answer: You should not expect an accurate result from a two-sample
t test on samples that are sufficiently far from normal to
fail Shapiro-Wilk tests of normality. The P-value about 4%
would be just barely significant even if accurate.
If the two samples have approximately the same shape, a
Wilcoxon rank sum test might tell you whether population
medians are significantly different. However, this test
is not quite as powerful as a t test. In any case a P-value
about 8% is not impressive evidence for a significant difference between population locations.
@Dave has a good point that you have done too many tests
on the data. Cherry picking the smallest P-value of two
2-sample tests would be "P-hacking."
Consider the following fictitious data:
set.seed(1234)
x1 = rexp(30, 1/10);  x2 = rexp(30, 1/15)
mean(x1); mean(x2)
[1] 9.384906
[1] 17.75834

Means are quite different. The issue is whether the difference
is statistically significant at, say, the 5% level. Boxplots show strongly right-skewed samples and apparently different dispersions.
x = c(x1,x2);  g = rep(1:2, each=30)
boxplot(x~g, horizontal=T, col="skyblue2")

Normal probability plots are clearly not linear, so the
data should not be assumed normal. The Welch t test may or may not give useful results with sample sizes as large as $n_1=n_2 = 30.$

R code for figure:
par(mfrow=c(1,2))
 qqnorm(x1); qqline(x1, col="blue")
 qqnorm(x2); qqline(x2, col="blue")
par(mfrow=c(1,1))

My first (and only) test would be a permutation test using the Welch t statistic as metric. This test does not assume that data are
normal, nor that the t statistic has a t distribution. It approximates the distribution of the t statistic for our data.  [We look at
P-values here because the Welch t test tends to have slightly
different degrees of freedom at each iteration.]
pv.obs = t.test(x~g)$p.val; pv.obs
[1] 0.02797518
pv = replicate(10^5, t.test(x~sample(g))$p.val)
mean(pv <= pv.obs)
[1] 0.02633  # Sim. P-value of permutation text

So the permutation test finds a significant difference
at the 3% level.
Because the boxplots show different shapes (dispersions), I would stop there.
If you want to know what the pooled t test, and Wilcoxon rank sum test would have given, here are the results. But we have done a valid test already, so
these results are to satisfy curiosity, not as valid test results.
t.test(x1,x2, var.eq=T)$p.val # Pooled
[1] 0.02622975
wilcox.test(x1,x2)$p.val      # Wilcoxon SR
[1] 0.2358858

Note: My fictitious right-skewed data for this Answer were sampled from exponential populations.
If you know that data are exponential, then there
is an exact test. See this Q&A, where it is stated
that means of two independent exponential samples, each of size $n$ have $\frac{\bar X_1}{\bar X_2} \sim \mathsf{F}(2n,2n).$ So, for our data with $\bar X_2 > \bar X_1,$ the P-value of an exact 2-sided test is
$0.015.$
f = mean(x2)/mean(x1); f
[1] 1.892223
2*(1 - pf(f, 60, 60))
[1] 0.01470998

Comment: For normal data the sample mean $\bar X$ and the sample SD $S$ are independent. So, with non-normal data it is not quite enough to have $\bar X$ approx normal. The t statistic can fail to have a t dist'n because of correlation of it's numerator and denominator. A t test may have 5% rej. rate for exponentials with equal population means, yet have poor power because num. and denom. of t stat are highly correlated. Of course, the exact F-test behaves better. For my fictitious data Welch t rejected with P-val 0.027 and the exact test with P-val 0.015. Robustness of t is '"legendary," not ideal
Comment: We don't actually care whether the samples are Normally distributed, only whether the sample mean (difference, in this case) is close to Normally distributed, because it is what is being tested.   For example, a sample mean from 12 Uniform variates was at one time close enough to Normally distributed to be used as a random number generator...  If I generate two sets of size 30 iid Exponential variates and take their difference, the t-statistic for testing that the mean $\neq 0$ (in my run of 100K experiments) rejected H0 5.023% of the time.
Comment: @jbowman "We don't care whether the samples are Normally distributed, only whether the sample mean is close to Normally distributed" - not quite true. If you have a certain percentage of outliers but finite variance in the underlying distribution, the mean will be asymptotically normal about the distribution mean, but the distribution mean will be affected by outliers and therefore usually not be a sensible estimation target.
Comment: There are fundamental problems with the way the issues were set up.  Testing for normality is bad statistical practice.  The Wilcoxon test works fine if the data are normality distributed.  Running multiple tests of a hypothesis is a no-no.  Logistic regression is not model-free but is a viable way to test group differences.
Comment: @BruceET - oh, sure, if you can construct an exact test that's going to be better.  My point was with specific reference to the statement about the Normality of the data, but as you observe the robustness of the t-test at the null hypothesis is no guarantee of near-optimal power.
Comment: Thank you very much for your comments, I really appreciate your help.
So I basically adapted your code to my behavioral data. The boxplot with my data actually strongly resembles your boxplot with the fictitious data (right-skewed and different variance (~1.43 vs. ~2.6). However, according to the qq plot the non linearity is not as obvious as in your case (in fact, according to Shapiro Wilk, only the data of group 1 is non-linear, whereas the data of group 2 is actually linear).

I repeated the permutation test and found a significant difference at the 4% level
Comment: Only thing I'm curious about: What is your argumentation to prefer the permutation test over Wilcoxon rank sum test? Is it only because the rank sum test is less powerful?
Comment: @ChristianHennig -If the actual data generating process isn't what we think it is, so we are modeling the wrong thing, we have a bigger problem than the appropriateness of the t-test!

T-Test or Wilcoxon Rank Sum Test?


Can i get rid of the 'default' site in multisite?

Question: I have a multisite (sub directory style), and am wondering if i can delete the default site (sites/default)? I just want to get a 404 if the site doesn't exist, no fallback.
Answer: You can leave the default directory in place. Just make sure there is no settings.php file in the default directory, and only the sites/www.yoursite.com directories will be accessed.
When you upgrade core, the default directory will always be replaced and will receive a new copy of default.settings.php, so it makes no sense to delete it.
Comment: that works, but now when i go there i get the install page, how can i avoid this then?


Update table value when inserting to other table

Question: I'm working on Laravel and my question is: How can I update value in one table when inserting data to another? Do I have to write new function in controller or update existing or maybe its done on form level in eloquent (view?)?
For example:
That's my OrderController.php function handling inserting:
public function insert(Request $request){

        $order = new order;

        $order->material_id = $request->material_id;
        $order->invoice_id = $request->invoice_id;
        $order->count_order = $request->count_order;

        $order->save();
        return redirect('/order');
    }

order.blade.php form that inserts data looks like:
<form method="POST" action="/order">

        <input list="invoices" name="invoice_id" autocomplete="off">
        <datalist id="invoices">
        @foreach($invoices as $invoice)
        <option value="{{$invoice->id}}">{{$invoice->number}}</option>
        @endforeach
        </datalist>

        <input list="materials" name="material_id" autocomplete="off">
        <datalist id="materials">
        @foreach($materials as $material)
        <option value="{{$material->id}}">{{$material->name}}</option>
        @endforeach
        </datalist>

        <input type="count" name="count_order" placeholder="Ilość zamówiona" autocomplete="off">

        <button type="submit" class="btn btn-primary">Dodaj zamówienie</button>

{{ csrf_field() }}
</form>

Orders table has:
| id | count_order | material_id | invoice_id |

Materials table has:
| id | name | count_all | count_current | price_unit |

Now I want to update column (add value) count_all in Materials when I post value in a form when inserting to count_order column in Orders table.
Comment: You will have to do a separate query to update this value. That's why storing computable data is usually avoided. Whenever you can get a value, such as the count of other elements, it is recommended to do so via the query (e.g. by doing a join). That saves you from inconsistencies across your database and potential sources of bugs.
Comment: Ok. But I wonder... if I have inserted to Orders: 10 Pens how can I capture this amount and pass it to that query so it will update the count_all for that exact value?
Answer: you can use if
$query = $order->save();

if($query){
  //do update data
}

Comment: While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
Comment: Thanks for answer! I achived it by using "if($query){
            DB::table('materials')
                ->where('id', $request->material_id)
                ->increment('count_all', $request->count_order);
        }"
Now I have to figure out how to apply this to edit but you gave me a good understanding where to start. Once again thank you.
Answer: You can extend the save() function in Order model, there you would have the value you need and you can perform an update in Materials


Debian 9 build PHP7.0 with --with-fpm-acl fails

Question: I need to enable support for POSIX ACL in PHP-FPM. I can get ACL list with getfacl and set them with setfacl -m from shell so my kernel support it. I've downloaded sources of PHP7.0_7.0.19 with
$ cd /tmp/
$ apt-get source php7.0

and updated the debian/rules file to enable ACL support:
$ cd php7.0-7.0.19/
$ vim debian/rules

and then around line 238 (export fpm_config = \) I've added --with-fpm-acl=yes so this config looks like:
export fpm_config = \
         --prefix=/usr --enable-fpm --enable-cli --disable-cgi --disable-phpdbg \
         --sysconfdir=/etc/php/$(PHP_NAME_VERSION)/fpm \
         --with-fpm-user=www-data --with-fpm-group=www-data \
         --with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/fpm \
         --with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/fpm/conf.d \
         --with-fpm-acl=yes \
         $(COMMON_CONFIG) \
         --with-libevent-dir=/usr \
         $(CONFIGURE_SYSTEMD)

and i run
dpkg-buildpackage -us -uc | tee /tmp/php_build_log.log

but I get this error:
configure: exit 1
    cd /tmp/php7.0-7.0.19
debian/rules:327: recipe for target 'override_dh_auto_configure-arch' failed
make[1]: Leaving directory '/tmp/php7.0-7.0.19'
debian/rules:275: recipe for target 'binary' failed

Here is the /tmp/php_build_log.log
Answer: OK, found the culprits. First one:
[...]
checking sys/acl.h usability... no
checking sys/acl.h presence... no
checking for sys/acl.h... no
checking for acl_free in -lacl... no
[...]

solution
$ apt-file search /usr/include/sys/acl.h
libacl1-dev: /usr/include/sys/acl.h
$ sudo apt-get install libacl1-dev

next one (I think this was main cause of failure)
## --------- ##
## Platform. ##
## --------- ##

hostname = eva02
uname -m = x86_64
uname -r = 4.9.0-3-amd64
uname -s = Linux
uname -v = #1 SMP Debian 4.9.30-2+deb9u2 (2017-06-26)

/usr/bin/uname -p = unknown
/bin/uname -X     = unknown

/bin/arch              = unknown
/usr/bin/arch -k       = unknown
/usr/convex/getsysinfo = unknown
/usr/bin/hostinfo      = unknown
/bin/machine           = unknown
/usr/bin/oslevel       = unknown
/bin/universe          = unknown

As the error was mentioning override_dh_auto_configure-arch, I think rules script couldn't determine architecture as /bin/arch didn't exists and /usr/bin/arch does not have -k switch but calling /usr/bin/arch gives x86_64 so I've made a symlink
$ sudo ln -s /usr/bin/arch /bin/arch

and now
$ debuild

finished successfully and I have signed deb packages.


Valor default do TextField Select no Material-ui

Question: É uma dúvida básica, estou tentando deixar o valor default como vazio, mas ele acaba sempre preenchendo com o primeiro item:
<TextField
        select
        id="letter"
        name="letter"
        label="Letra"
        defaultValue=""
        SelectProps={{
          native: true
        }}
        variant="outlined"
        margin="normal"
        fullWidth
      >
        <option key={1} value={1}>
          A
        </option>
        <option key={3} value={2}>
          B
        </option>
        <option key={3} value={3}>
          C
        </option>
</TextField>

Segue o codesandbox com o exemplo citado
https://codesandbox.io/s/material-ui-select-2jw0c?file=/src/App.js
Answer: Não sei se é a melhor forma, mas adicionei isso e funcionou aqui:
<option disabled selected value={""}></option>


Drupal Commerce - Reference Product in another product

Question: I am building a Drupal Commerce based site and now I am facing the following issue.
I have created some T-Shirt Products like,

T-Shirt (White)
T-Shirt (Black)
T-Shirt (Blue)

And also created a product display called "Shirts". In that product display I created a new node "T-Shirt". Since The "size" is an attribute to the product type so I am having a select box to select the color while viewing the "T-Shirt" content.
But the problem comes here. As per my need, if the user selects "Color - White" while viewing
the product display, we need to add another product "Blue-Jeans" to it. So that means, White Shirt and Blue Jeans will go together in cart if selected.
I am using inline_entity_form to reference products in a Product display (Same as Commerce Kickstart Demo "Tops" product display). How can I achieve this functionality?
Answer: What you are looking for is bundling of products.
Take a look at Commerce Product Bundle Module
The project page says

You can define products that consists of other products. They are all
  combined in one add to cart form. The form works like the core add to
  cart form with all the fancy selection and ajax magic. So the
  customers can make their selections as usual. The difference is, that
  the products from mulitple reference fields were presented on one add
  to cart form.
Comment: thanks but this module is not working for me giving error https://www.drupal.org/node/2199979.
Also tried Commerce Product Add-on but this only adds the add-ons price to cart not the whole. Any further ideas? I think I'll try commerce custom products.


Multiple timeline series in ExtJS4 chart with one store

Question: The data, that comes from the server looks like this:
<code>[
  { date: 123456789, browser: 'firefox', clicks: 123, ... },
  { date: 123456789, browser: 'chrome' , clicks: 456, ... },
  { date: 123456790, browser: 'firefox', clicks: 678, ... },
  { date: 123456790, browser: 'chrome' , clicks: 453, ... },
  { date: 123456791, browser: 'firefox', clicks: 234, ... },
  { date: 123456791, browser: 'chrome' , clicks: 555, ... },
  ...
]
</code>
I generate my models from this, pack them into a store and show them in a grid, which works fine.
But now I want to show a timeline chart for this table, and it should have one series for every browser.
Is it possible to filter series?
Something like this:
<code>series: [
  {
    type  : 'line',
    title : 'Chrome',
    xfield: 'clicks',
    yfield: 'date',
    filter: { browser: '*chrome*' }
  }
]
</code>
Answer: You can only filter a store, but when you filter the store your grid will get filtered aswell. You could make a copy of the store, or create a new store with filtered data from the first store.


Erro no select usando mysqli_query

Question: Eu fiz um php para listar os quartos, mas estou a ter dificuldade em puder os listar, se alguém me poder ajudar, agradecia
<?php
$link = mysqli_connect("localhost","root","","hotel");
$result = mysqli_query("SELECT descricao FROM quartos WHERE nome_quarto=Quarto Ibiza");
$row = mysqli_fetch_array($result);
?>

            Descrição:

            <?php
            echo $row['descricao'];
            ?>

            <button type="submit" id="button1id" name="button1id"                 style="border:3px double black;" class="btn btn-primary" >Reservar</button>

Erros:

Warning: mysqli_query() expects at least 2 parameters, 1 given in F:\XAMPP\htdocs\Pap2\quartos.php on line 67
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in F:\XAMPP\htdocs\Pap2\quartos.php on line 69
Comment: Para colocar o código, da próxima vez, selecione todo o seu código e aperte no botão com o ícone "{}". Ou então, coloque quatro espaços antes de cada linha. Isso é importante especialmente com códigos começando com `<?`, pois isso é o que e engine de formatação de textos interpreta como o início de um texto invisível.
Comment: Por favor, coloque seu código aqui, removendo informações confidenciais que possam comprometer seu sistema. Apenas o código que contém o problema e partes relevantes. Assim poderemos te ajudar melhor.
Comment: já esta, pode ajudar pfv
Comment: Qual o problema? valores string precisam de aspas simples no sql.
Answer: O erro informado:

Warning: mysqli_query() expects at least 2 parameters, 1 given in F:\XAMPP\htdocs\Pap2\quartos.php on line 67

É porque está faltando passar o link do MySQLi por parâmetro, antes inexistente nas funções MySQL:
Corrija passando a variável $link da seguinte forma:
$link = mysqli_connect("localhost","root","","hotel");
$result = mysqli_query($link, "SELECT descricao FROM quartos WHERE nome_quarto='Quarto Ibiza'");

E o segundo:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in F:\XAMPP\htdocs\Pap2\quartos.php on line 69

É porque faltou o parâmetro do tipo de fetch:
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

As opções de fetch são:

MYSQLI_NUM (trás em um array numérico $row[0])
MYSQLI_ASSOC (trás em um array associativo $row['descricao'])
MYSQLI_BOTH (trás dos dois modos anteriores)

Também recomendo utilizar o MySQLi Orientado a Objetos, assim:
$link = new mysqli("localhost","root","","hotel");
$result = $link->query("SELECT descricao FROM quartos WHERE nome_quarto='Quarto Ibiza'");
$row = $result->fetch_array(MYSQLI_ASSOC);

Outro erro na sua consulta sql:
SELECT descricao FROM quartos WHERE nome_quarto=Quarto Ibiza

Tem um problema na clausura WHERE onde uma string deve ser passada dentro de aspas simples:
SELECT descricao FROM quartos WHERE nome_quarto='Quarto Ibiza'

Fica assim o código PHP:
$result = mysqli_query($link, "SELECT descricao FROM quartos WHERE nome_quarto='Quarto Ibiza'");

Tenho uma classe de conexão que ajuda bastante na hora de gerenciar a conexão: ConnectionMSi
Comment: Da-me os seguintes erros :( Warning: mysqli_query() expects at least 2 parameters, 1 given in F:\XAMPP\htdocs\Pap2\quartos.php on line 67

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in F:\XAMPP\htdocs\Pap2\quartos.php on line 69
Answer:
Warning: mysqli_query() expects at least 2 parameters, 1 given in
  F:\XAMPP\htdocs\Pap2\quartos.php on line 67

Esse erro diz que a função espera dois argumentos e apenas um foi passado, logo, é
obrigatorio passar dois argumentos para a função [mysqli_query()][1] o primeiro a conexão e o segundo a query, é necessário passar os valores na query entre aspas simples quando esses valores são do tipo string.
$result = mysqli_query($link, "SELECT descricao FROM quartos WHERE nome_quarto='Quarto Ibiza'");

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
  null given in F:\XAMPP\htdocs\Pap2\quartos.php on line 69

Normalmente esse erro indica que a sua consulta possui um erro de sintaxe(sql state 1054 mysql)
Comment: MUITO OBRIDADO, PROBLEMA RESOLVIDO ! OBRIGADO MESMO
Answer: Acredito que seja isso o que você precisa:

            Descrição:

            <?php
                $conn = mysqli_connect("localhost","root","","hotel");
                $sql = "SELECT descricao FROM quartos WHERE nome_quarto='Quarto Ibiza'"
                $result = mysqli_query($conn, $sql);

                while($row = mysqli_fetch_assoc($result)) {
                    echo $row['descricao'];
                }

                mysqli_close($conn);
            ?>

            <button type="submit" id="button1id" name="button1id" style="border:3px double black;" class="btn btn-primary" >Reservar</button>

Erro no select usando mysqli_query


What type of statistical test to use on ordered (e.g., time or position) observations?

Question: I have 2 samples where one is using water as treatment (in black) and one using a test treatment (teal).  The x axis is position on a gene and y axis is the coverage which is basically the number of times that region had a hit on the detecter.
Is there a statistical test I can use to say the test treatment has higher or lower coverage than the water treatment?  I guess a t-test or wilcoxon could technically work but it's not incorporating the position information which I think is important.
Also, is there a way to incorporate segments? For example, is the (mean/median) "coverage" on region X to Y significantly different between the 2 samples compared to the other regions?
Are there any tests that come to mind when looking at this type of data? These types of plots remind me of time series data so I feel that tests used on time series data would be applicable here.
Comment: Do you mean testing if the `water` and `nu-c-12` treatments both have the same impact on the coverage? // Your work may lead you to be interested in [tag:functional-data-analysis] and functional ANOVA.
Comment: Yes, both may have an impact on "coverage".  How would you recommend structuring functional ANOVA for this problem?
Comment: if you have 2 samples, I don't think you can statistically say much about that, unless you assume that those facilities or what are they are the same, except for the treatment
Comment: This is one observation.  I have 4500 others.  Was hoping there would be a way test differences per observation, generate p values, and then FDR correct.
Answer: You say "I guess a t-test or wilcoxon could technically work but it's not incorporating the position information which I think is important". Why do you believe position is important? Does the position on the gene actually affect the means by which you are measuring coverage? In other words, does the fact that (arbitrary) position 200 has 10 coverage have any impact on whether position 201 has, e.g., 9 coverage? Or is it possible for bp 201 to have 1 coverage while position 200 has 100 coverage given the general trends we're seeing here? In other words, are the coverages of individual base pairs independently and identically distributed? Even if there is a dependency, you only lose power by treating them as independent, but won't increase your risk of Type 1 errors.
I am noticing some error bars on your plot. What do they represent? 2*Standard error? If so, then the statistics are being done for you. Base pairs around positions 420 and 720 have non-overlapping error bars between conditions, and are hence statistically different if these are indeed standard error bars plotted.
It appears you should also be concerned with correction for multiple comparison since each base pair is a separate (hopefully independent) statistical test. False discovery rate (FDR) is a well enough correction if you have the p-values, or you can construct the p-values from the (presumably average) coverage values and their standard errors at each base pair.
Comment: Yes, the detector detects fragments that ~150 units long so nearby regions should have similar coverage profiles.  The error bars are standard error of the mean from 3 conditions.
Comment: I only see two conditions in the plot, though. Are you saying that each line in the plot is an average of only 3 data points at each position within the two conditions?
Comment: Yes, typically biological experiments are done in triplicates (I know the statistical power of that is terrible).  The halo around is the mean +/- standard deviation.