Wooden Saxophone Project

Question: So my friend was planning on making an all wooden saxophone. I thought it was a pretty good idea but had some doubts in it like the piston valves and such. I saw this being a problem because of the springs. My friend suggested just making air-holes such as on a flute but I thought that it wouldn't make it as much as a regular saxophone. To add onto that, I'm worried that if we do the springs, it will dig into the wood and mess it up. I need some advice. (Note: We haven't started on the project yet, we are in the brainstorming stage at this moment.)
Comment: Saxophones do not have pistons.  Why are you thinking of that?
Comment: Entirely wooden? As in wooden springs? Wooden linkage and pads? Or just wooden body? How will you achieve the curved airway typical of the saxophone family? Compared with other woodwinds that have straight bore, or a series of connected straight bore sections, many saxophones have a curved and gradually flaring bore. You might be OK if you were to craft just the bell section in wood, but I think forming the entire body from wood would be problematic.
Comment: The wooden (or plastic) instrument with tenor sax mouthpiece and recorder-like finger holes already exists. It's called Xaphoon and it sounds bigger than its size. I'd like to say that the cross fingerings take some getting used to to me they're more like impossible.
Comment: I'll jump in with another non-answer:  In Lithuanian folk music, a wooden, keyless saxophone is a [Birbynė](https://www.balticshop.com/cgi-bin/item.cgi?item=10041).
Comment: So piston valves (which I picture as being like a trumpet) are like a saxophone, but air holes (like a flute or clarinet) aren't?
Comment: I'd also point out the enormous challenge of making a round tube out of wood and have it not crack in half.  Then add the complexities of a round tapering tube that curves at the bottom and you have yourself a big project.
Comment: Also you'd have to consider wall thickness. Most wooden woodwinds have a wall significantly thicker than their wooden counterparts, so you'd have to consider sound hole formation too, so you wouldn't be able to cannibalize a metal saxophone's key work, because all the spacing would be different.
Comment: Well we were planning on making the entire airway out of wood and just carving the inside out. I have no idea if its even possible to acheive wooden springs.
Comment: Woodwinds made of wood invariably have metal keys, if they have keys.  If you want the sax to be playable as a modern chromatic sax, it needs keys.  You might be able to invent a "baroque" sax by analogy with the modern flute and baroque flute, using cross fingerings for chromatic notes, though I don't know how successful that would be given the differences between flutes and saxophones.
Comment: "I built a wooden saxophone, but it wooden saxophone ...." Somehow that doesn't have [the same ring](https://www.reddit.com/r/Jokes/comments/5zlq67/i_bought_a_wooden_whistle/) to it....
Comment: @Theodore and that's a wooden saxophone rather than a clarinet because ... ?  Does it overblow the octave?
Comment: @phoog It's a "wooden saxophone" because the OP didn't make a big deal out of the distinction between saxophone and clarinet. The birbynė is made of wood, has a single reed, and holes instead of mechanical valves.  I presented it as a "non-answer" example of how a similar instrument might end up.  At least I didn't suggest a [duduk](https://en.wikipedia.org/wiki/Duduk) (which is double-reed).
Answer: I'll be "that guy" and ask, isn't a wooden sax just a clarinet? I know, obviously the bore and fingering are all different. But I mean something a bit serious by that: maybe you should just consider an instrument that is usually wooden.
This is a great project if you go into it with the right expectations. If the goal is "I'd like to have an innovative and great-sounding instrument, so I'll save money by making it myself," then there's a lot of frustration and disappointment ahead. If it is "I'd like to use trial-and-error to get a lived-experience personal understanding of the way wind instruments are put together," then it's a great goal. As such, you might have to get really flexible with your definition of "saxophone" (arguably you already are?).
I'd suggest that you start with much simpler wind instruments, which would still be plenty challenging as woodworking experiments. You might start with no moving parts: ocarina, recorder, maybe a wooden natural horn or cornett. Maybe the next step—if you dare—and if you don't want to be arrested for weapons of mass disturbance of the peace—would be to make the jump to reeds with a homemade crumhorn. (Or—really—just don't get into such degenerate and dangerous activities.)
If you're particularly interested in the engineering challenge of working with keys, you might try something like a baroque oboe, with mostly open holes but a mere 1 or 2 metal keys for the harder-to-reach holes.
Comment: No, a wooden sax is not a clarinet.  The clarinet is cylindrical, and it doesn't have even harmonics, so it overblows the 12th.  A saxophone is conical and overblows the octave, so its fingering is basically the same as the flute.  Baroque flutes also typically have keys.
Comment: @CarlWitthoft hence "it doesn't have even harmonics."
Comment: @phoog I confess I read it at first as "doesn't even have harmonics." ("Do you even overtone, bro?") Let the record show that, yes, I understand the difference between a clarinet and a sax. My point was "as long as we're redefining the parameters, let's redefine them so hard that you're attempting a totally different instrument." I particularly heart the suggestion of the Birbyne from the comments.
Comment: A wooden saxophone is a tárogató.  Or better said: the tárogató is the only somewhat extant example of a wooden conical bore single reed instrument with keys (as far as I know).
Comment: The bore profile determines sound much more than material. For example: There are metal clarinets. At first sight, they might look a lot like a soprano sax, but they sound... just like a clarinet.
Comment: @phoog well, a clarinet has harmonics, just not all of them :-) .
Comment: @phoog  apologies -- as Andy wrote, I misread the word order
Answer: Yes you could do it - tho' I would very VERY strongly recommend you use metal rods,keys, and pad-holders, just as is done for clarinets and flutes.
BTW, there are wooden flutes and piccolos, and there are metal clarinets (tho' these are mostly cheapos with limited sound quality).  In fact, there are even some metal oboes and bassoons!
So, other than some rather large hunks of wood required to handle the bell-end of your saxophone,  there's nothing fundamental stopping you from building one.   Be prepared for it to sound ugly.
Comment: "rather large hunks of wood" it occurred to me last night that it could (potentially) be made in sections out of steamed plywood, much like the famous Eames chairs.  But I agree, it would sound awful.

Wooden Saxophone Project


Como mudar a source de um image control a partir de um ResourceDictionary

Question: Tenho o ResourceDictionary seguinte:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:semaforo.imagens">
<BitmapImage x:Key="semaforoVerde" UriSource="green.png" />
<BitmapImage x:Key="semaforoAmarelo" UriSource="yellow.png" />
<BitmapImage x:Key="semaforoVermelho" UriSource="red.png" />

Sempre que quero mudar a cor do semáforo procedo assim:
semaforo.Source = new BitmapImage(new Uri("pack://application:,,,/imagens/red.png"));

Em vez do Uri utilizado acima é possível utilizar algo mais simples como a x:Key="semaforoVerde" ou algo assim?
Comment: Você quer fazer isso no código ou no *xaml*?
Comment: No código. Ainda estou a usar a sintaxe do ""pack://application:,,,/imagens/red.png" sem ter a certeza do que é!
Answer: Via código pode aceder aos resources declarados/definidos num Control de duas formas:
1 - Usando a propriedade Resources
semaforo.Source = (BitmapImage) Control.Resources["semaforoVerde"];

2 - Usando o método FindResource()
semaforo.Source = (BitmapImage) Control.FindResource("semaforoVerde");

Substitua Control pelo respectivo nome do objecto onde foi declarado/definido o resource.
Caso tenha sido ao nível da aplicação use Application.Current
Comment: No meu caso era Application.Current ... funcionou na perfeição e é mais simples do que eu estava a fazer.


RxJs6 - Static merge an array of observables

Question: I have a list of objects created dynamically by the user. Each object has a click$ observable, I want to merge all this click$ streams in one stream.
I've tried the merge static operator from rxjs import. With the direct references to the stream:
sub = merge(list[0].click$, list[1].click$)
    .subscribe(e => {
       console.log('My click event', e);
    })

all goes as expected.
But when I use an array of click$ in the subscribe next call I received an Observable object and not my click event.
const streams= [];
list.forEach(o => { streams.push(o.click$); });

sub = merge(streams).subscribe(e => {
  console.log(e); // e is an observable ???
});

Why? What am I doing wrong?
Here a similar implementation with the same error: https://stackblitz.com/edit/typescript-ohq6rx?file=index.ts&devtoolsheight=100
Answer: Since it's an array. You can spread an array with the ... operator in JavaScript. If you do this all should work well.
More information can be found at MDN
I added code so you have an idea what I mean. List is the array of objects that have click$ properties. this array is mapped to just the click$ and then spread with the ... operator.
sub = merge(...list.map(item => item.click$)).subscribe(console.log)


Requisições ajax encadeadas

Question: Meu objetivo é transmitir uma requisição para um php, e posteriormente retornar listar dados em um modal[bootstrap 5], para após realizar um UPDATE.
Encontrei algumas soluções para resolver a questão com [session, variável global, entre outras... porém achei um pouco "gambiarra" o resultado final];
É possível fazer algo neste sentido? Enviar uma requisição, obter uma resposta, e encadear outra requisição com ajax? Ou o conceito fica master gambiarra!
Obrigado amigos
$.ajax({
        type: 'POST',
        url: 'x.php',
        data: {getIdUpdate: getId},
        success: function(response){
          alert(response);
          $.ajax({
            type: 'POST',
            url: 'y.php',
            data: dados,
            success: function(response2){
              alert(response2);
            }
          });
        }//success
      });//ajax

Answer: Se voce consegui alterar o código da pagina que esta acessando x.php, o certo seria ja enviar a variável dados junto com a primeira requisição {getIdUpdate: getId, dados} e tratar tudo junto.  Agora se esta acessando um api externo ou algo do tipo, não vejo um problema com a sua função.
Não e difícil seguir o código com so duas requisições, mais se no futuro vai adicionar outras requisições neste promise chain acho que fica mais fácil de entender usando o formato abaixo.
const funcao1 = (getId) => {
  return $.ajax({
     type: 'POST',
     url: 'x.php',
     data: {getIdUpdate: getId}
  });
}

const funcao2 = (dados) => {
  return $.ajax({
     type: 'POST',
     url: 'y.php',
     data: dados,
  });
}

funcao1(id).then((resultado1) => {
    alert(resultado1);
    return funcao2(dados);
 }).then((resultado2) => {
    alert(resultado2);
 });

Requisições ajax encadeadas


extjs/c# Yes saves to the database

Question: I have a simple question.
I have a FormView, with a save button. When the button is clicked, it saves to databse.
I've added an EXT message box to confirm if user wants to save the data or not. when he click yes on the messagebox yes button, then it should save the data.
I can't find where to write the yes button logic in the ext.
Here is my code :
     <asp:FormView ID="myform" runat="server" DataSourceID="mydatasource" DefaultMode="Edit"  DataKeyNames="Id" >

      <EditItemTemplate>
       <asp:TextBox ID="myText" runat="server" TextMode="MultiLine" ClientIDMode="Static"
        Text='<%#Bind("xx") %>' />
       <ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false"  CommandName="Update" Text="Speichern" StyleSpec="float: left; margin-left:10px;">                                                                               <DirectEvents>
<Click OnEvent="btnUpdateClick"></Click>
 </DirectEvents>
                                                              </ext:Button>

protected void btnUpdateClick(object sender, DirectEventArgs e)
        {
           X.Msg.Confirm("Confirm", "Are you sure you want to save?", new JFunction { Fn = "showResult" }).Show();

        }

Comment: Please provide a example/rephrase your question. The message box can't update anything. So it is not clear what you are asking.
Comment: the message box has yes and no buttons (do you want to save the data), when user click Yes, it should save the data, I just dunno how I can do it, I will provide the code now.
Answer: I guess you are looking for this: (Can be placed in any Demo-Box of the Sencha API)
Edit 2
I have totally overseen that you are using Direct. You should mention such things.
Is there any reason for using DirectEvent? I couldn't test it but how about this (the wrapping function may be unnecessary, but a normal ExtJS handler get button reference as first argument):
<form runat="server">
        <ext:ResourceManager runat="server" />

        <ext:TextField ID="TextField" runat="server" FieldLabel="Label"/>
        <ext:Button ID="Button" runat="server" Text="Click Me" Icon="Lightning">
            <Listeners>
                <Click Handler="function() {Ext.Msg.show({title: 'Save?', msg: 'Do you want to save the data?:', buttons: Ext.Msg.YESNO,fn: function(btn){ if(btn == 'yes') {App.direct.SetTimeStamp(#{TextField}.getValue());}}})}" />
            </Listeners>
        </ext:Button>
</form>

Edit 1 Simply use Ext.Ajax.request()
Ext.Msg.show({
        title: 'Save?',
        msg: 'Do you want to save the data?:',
        buttons: Ext.Msg.YESNO,
        fn: function(btn, text){
              Ext.Ajax.request({
                url: 'yourUrl',
                method: 'POST',
                params: {
                    // your params
                },
                success: function() {
                    console.log('success');
                },
                failure: function() {
                    console.log('woops');
                }
            });
        }
});

Form example removed
Comment: Point is, my action is to make the button do a postback action, I cant make this to happen.
Comment: @Mark I made an edit so that now a ajax request is fired after clicking YES
Answer: Thank you all for your support, I found my way through your answers I will put it here maybe it can be useful for someone.
First, button code, need to have Isupload = "true"
ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false"
CommandName="Update" Text="Save" StyleSpec="float: left; margin-left: 10px;"
AutoScroll="False">
<DirectEvents>
<Click OnEvent="btnUpdateClick" IsUpload="true" AutoDataBind="true">
</Click>
</DirectEvents>
</ext:Button>

in the button event in the aspx :
protected void btnUpdateClick(object sender, DirectEventArgs e)
{
        MessageBoxButtonConfig buttonYes = new MessageBoxButtonConfig();
        buttonYes.Text = "Yes";
        buttonYes.Handler = "Ext.net.DirectMethods.ClickedYES();";

        MessageBoxButtonConfig buttonNo = new MessageBoxButtonConfig();
        buttonNo.Text = "NO";
        //  buttonNo.Handler = "Ext.net.DirectMethods.ClickedNO();";

        MessageBoxButtonsConfig yesNoButtons = new MessageBoxButtonsConfig();
        yesNoButtons.Yes = buttonYes;
        yesNoButtons.No = buttonNo;

        X.Msg.Confirm("Save Changes", "Would you like to Save?", yesNoButtons).Show();
 }

Last the Yes method that will save to database:
[DirectMethod]
public void ClickedYES()
{
      Formview.UpdateItem(false);
      Formview.DataBind();
}

Answer: I would suggest that instead of wiring the yes button of the dialog to perform the postback. You should wait for the message box to close and then invoke the postback functionality if the user clicked yes.
For example:
Ext.Msg.prompt('SaveChange', 'Would you like to save the changes?:', function(btn, text){
    if (btn == 'yes'){
         __doPostBack('btnSubmit','OnClick');
    }
});

Replace btnSubmit with the name of your button.
Although the above solution would be my recommended approach, you could, alternatively, use jquery by doing:
$('btnSubmit').trigger('click');

Source: http://dev.sencha.com/playpen/docs/output/Ext.MessageBox.html
Comment: Point is, my action is to make the button do a postback action, I cant make this to happen.
Comment: -1 for mixup jquery with extjs. There's no need for using two libraries
Comment: Disagree strongly, jquery is so defacto with asp.net it's practically part of the framework and I have also supplied an standard asp.net method for performing this!
Comment: JQuery is just shipped as default which is perfectly well cause it's the best you will find for that purpose. But this is about Ext.net which is ExtJS driven and not ASP.net MVC. This is neither related to jquery nor is it shipped with it. The other point is, think about application layers... jQuery is just a ...'Hey, you should use this cause we think it fits very well'... Delete the libs and ASP.net MVC  still work the same. And if you choose any other frontend framework like ExtJS, there is no need to keep jQuery. (OK, there are some rare situations, but the are really rare)
Comment: I would agree if I had not also supplied a pure asp.net solution. Your solution does not actually do what the OP requested. You are submitting the request via AJAX, the OP wanted to programmatically click a button when the dialog 'Yes' button was clicked. This isn't the same thing in all scenarios. I feel there is a tactical nature to your objection, rather than a firm concrete techincal one. Never the less, I will update my answer to reflect my preferred approach.

extjs/c# Yes saves to the database


System can't see ServerRAID M1015 virtual drive?

Question: We connected the card to our system and have created a new mirror RAID 1 virtual drive, Now we want to clone our existing single drive to this new virtual drive, but our cloning software Acronis True Image Server doesn't see it.
We also don't see the SAS controller in BIOS boot order.
Any idea how to make the drive visible to system?
Thanks!
Answer: The boot off the SAS controller could come under "external device" or similar heading in the BIOS. You can also call IBM support, they should be able to tell you, how to set this up.
The checklist to run:

Is the controller supported by your server? Check e.g. here: http://www.redbooks.ibm.com/abstracts/tips0740.html
Is the controller supported by your cloning software? Check the producer's website and check hardware compatibility list for your version of the software.

You could also try Clonezilla. Support for ServeRAID has been in Linux kernels for ages now and it should be able to do the job for you.
Comment: Hi. 1) Server model is x206m (8485EAY), and while it not listed in the link above, it does boots normally and allows creating new virtual drive.
Comment: After creating the new virtual drive, we want to select it as boot drive, but there is no boot order in BIOS, there is boot menu (F12) which doesn't contain the virtual drive. 2) Acronis Echo Server should be supporting this card - we will try with latest version. Also, we will give a look to the Clonezilla you have mentioned.
Comment: Clonezilla does the trick - wish other software would start support LSI/ServeRaid too!


Combinatorics problem ascending order numbers

Question: Let $n_1 < n_2 < n_3 < n_4 < n_5$ be positive integers such that $n_1 + n_2 + n_3 + n_4 + n_5 = 20$. Then the number of such distinct arrangements $(n_1, n_2, n_3, n_4, n_5)$ is ....
Comment: You want partitions: https://en.wikipedia.org/wiki/Partition_(number_theory)
Comment: One such arrangement is $1+2+3+4+10$.  As it so happens, any other arrangement can be made by moving one of the numbers up and another number down.
Comment: Please read this [tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Comment: Manualy answer is 7.but I need some combinatorial proof if possible.
Answer: The solutions must be of the form
$$(n_1,n_2,n_3,n_4,n_4)=(1+a,2+b,3+c,4+d,5+e)$$
with
$$0\le a\le b\le c\le d\le e\quad\text{and}\quad a+b+c+d+e=5$$
These correspond to the partitions of $5$ (fleshed out with $0$'s), of which there are $7$, namely
$$\begin{align}
0+0+0+0+5\\
0+0+0+1+4\\
0+0+0+2+3\\
0+0+1+1+3\\
0+0+1+2+2\\
0+1+1+1+2\\
1+1+1+1+1\\
\end{align}$$


How to replicate existing aws-ec2 instances and s3 data on nearest location/endpoints for improved network throughput?

Question: I am a remote developer working out of India. My client is based out of North America and has his ec2 servers/s3 data kept in the us-west-2 region.
The number of hops needed to fetch the data is obviously big and thus wastes a lot of my time during testing, as we are dependent on large data coming in from s3.
How can I replicate the existing ec2/s3 system to have an endpoint in India so that my testing performance can be increased?
Comment: It can be easier to run testing software on an ec2 instance in us-west-2 AWS region.
Answer: Technically you can. You just need to setup infrastructure clone and copy all data to India region. There are several BUTs:

running cost. You (resp. your client) will have to pay for running environment in India. It can be thousands of dollars and maybe it can lead to hiring US-based developer (because your salary + India environment is more expensive than US developers salary.)
setup cost. Someone from your client must setup this clone corresponding to US environment. This can takes months (depends on how much automation is prepared and how fresh it is). Same for data, it can takes a lot of time to copy data to India
Synchronization between US and IND. Your copy of infrastructure must be up to date with structure in US, same as testing data. Someone from your client must handle it.
Law regulation. Maybe there are some data which must be stored in US and cannot be copied to India.

All of those questions must be answered by your client, not by us.


Flutter slide with inner arrows

Question: How can I achieve such behavior in Flutter? any widget or plugins example?
See this gif
I tried carousels plugins and viewPagers widgets but couldn't make it work.
here is the sample code I started with.
<code>CarouselSlider(
   items: [
        Container(child: Text("Complimentary"), width: double.infinity),
        Container(child: Text("Complimentary"), width: double.infinity),
        Container(child: Text("Complimentary"), width: double.infinity),
        Container(child: Text("Complimentary"), width: double.infinity),
        Container(child: Text("Complimentary"), width: double.infinity),
   ],
   options: CarouselOptions(
        height: 39 * resizeFactor,
        autoPlay: false,
        enlargeCenterPage: true,
        autoPlayInterval: Duration(seconds: 10),
   ),
),
</code>
Answer: I made it work by using both Swiper and Row of arrows, with the following code:
<code>      Stack(
        children: [
          Container(
            height: 39 * resizeFactor,
            child: Swiper(
              itemCount: 4,
              itemBuilder: (context, index) => getIndexWidget(index), // -> Text widget.
              viewportFraction: 0.4,
              onIndexChanged: (value) {
                setState(() => carouselIndex = value);
              },
              loop: false,
              controller: swiperController,
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 30 * resizeFactor),
            height: 39 * resizeFactor,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                getIndicatorWidget(false),  // back arrow icon.
                getIndicatorWidget(true),   // forward arrow icon.
              ],
            ),
          ),
        ],
      ),
</code>
Thank you for your contributions.
Comment: where did you get ```getIndicatorWidget``` from?
Comment: it's just the right/left arrow widget.. @ajnabz
Comment: oh for some reason it gives me an error saying I need to declare it

Flutter slide with inner arrows


Why is cache control not working?

Question: I set the cache control to "no-cache" and "max-age=0" still when I click on back button of the browser it shows the  previous page. Actually the problem is when we login from login page and then it gets login to the main page but if we hit back button then it again shows the login page.Thats why i want to apply cache-control to no-cache but it is not working. Is there any other option to do it. What I've done is as follows
I added these two meta-tag to head section of page :
<meta http-equiv="cache-control" content="max-age=0"/>
<meta http-equiv="cache-control" content="no-cache"/>

Thanks in advance.
Comment: Disableing cache is covered well here http://stackoverflow.com/questions/1341089/using-meta-tags-to-turn-off-caching-in-all-browsers
Comment: Actually the problem is when we login and then it gets login to the main page but if we hit back button then it again shows the login page.
Comment: So detail the problem in your question.
Comment: Thats why i want to apply cache-control to no-cache but it is not working
Comment: Cache control doesn't control navigation. It makes the browser download the page again.
Comment: ok thats fine. i just do it.
Comment: so is there any other way to do it
Comment: This question should be fixed or deleted
Answer: I had the same problem in one of my javascript project, please pick this code if useful to resolve your issue, this is one of the way to handle browser back button

Comment: but this script is working only for chrome not for other browsers.
Comment: there could be a conflict with other functions please debug, for me it worked in all webkit browsers even IE.
Comment: Try adding this
Comment: The problem is if the user disables JS.

Why is cache control not working?


GLMM to test change between two periods

Question: I have made an analysis to test whether the weight of a mice population has changed between two periods. Data have been collected in the period 1978-81 and 2005-07. Many mice were captured through the whole set of years (all months) in the first period and a much smaller number was captured in the second period. The unbalanced data are due to a different capture effort in the field and to a strong reduction of mice population size.
Weight may vary according to: (i) sex, (ii) age class, (iii) month of capture, (iv) total body length, and (iv) type of capture (e.g. individuals captured by live- and death-traps, both used, may tend to provide data on individuals of different average conditions or age). Moreover, a random deviation in weight may be result of environmental stochasticity with some years "better" and other "worse". For this reason, to test whether weight has changed BETWEEN the two periods I have chosen to use a GLMM for each sex by including all the predictors I mentioned before (using notation of package lme4 in R):
weight ~ age + month + TBL + TypeCap + year + (1|yearF)

where all the predictors are categorical except TBL (total body length, continuous variable) and year (integer variable, i.e. 1978,1979,1980,1981,2005,2006,2007 - yearF is categorical).
I have checked my model visually as usually and looked also for influential point (individuals or years). The model seems really OK, it converges well, it has good fit to data, and does not seem overfitted.
I find a strong and significant decrease over time (year effect highly significant). According to the first and last year (1978 and 2007) point estimates and net of the above mentioned controlling variables, it would correspond to a decrease of about 30% (similar for both females and males).
So, what is my question about?
I feel fine with this approach and the interpretation I am doing of the results but, until now, reviewers (this forms part of a scientific manuscript) do not seem to agree. There have been already three reviewers who claim against using the GLMM because there are not data in the middle and suggest some type of ANOVA test. I do not agree and would like to convince them that there is nothing wrong in using a GLMM to test whether there has been a change between the beginning and final of period study even if we do not have data in the middle. What actually matters is that we cannot say nothing about what happens in the middle (and in fact we do not) but we can do it about the change in weight between 1978 and 2007. We never talk about any linear trend or anything similar. By using the GLMM we can control for several potential confounding variables (e.g age, month, capture type, etc.) and also for random effect as that of year. However, I don't see an immediate way of doing that by using some kind of t-test.
I would appreciate any thought, commentary or suggestion (even some reference I could cite) on this.
Answer: You have no reason to add random effect in your model. Random effect is used to model the correlation between error terms.
The general linear model is:
$Y=X\beta + \epsilon $
We assume that $\epsilon$ ~ $N(0, I\sigma^2)$.
If you find the assumption above is not good and $\epsilon$ ~ $N(0, \Sigma)$, and $\Sigma$ has non-zero off-diagonal elements, it is the time to add random effect to incorporate these non-zero off-diagonal elements.
But from your description, I could not find any evidence of existence of non-zero off-diagonal elements in $\Sigma$.
So reviewers' suggestions are correct, just use GLM, instead of GLMM.
Comment: Reviewers are suggesting to use an ANOVA that, as you say, is a special case of GLM. However a GLM is not an ANOVA, and for instance is not that easy to model with an ANOVA an unbalanced data like mine (but it is by using a GLM). That said, once again, the commentary of the reviewers is not aboout random effects, is about the fact that I have tested for a temporal change by using YEAR as an integer covariate even if I have a big gap in this covariate (1978,1979,1980,1981,2005,2006,2007). They suggest to use an ANOVA with period I and period II as two treatments.
Comment: Then you can fit another model treating year as categorical variable. Comparing your old model with this new model by likelihood ratio. If the new model is better, it means the reviewers idea is good. Otherwise, you can argue that year effect is really linear and your old model is better. (Two models should be the same on treating random effect)
Comment: Yes, actually it is what we decided to do, happy to know that you have led to the same conclusion. Thanks!
Comment: Thanks for your input. However, the reviewers suggestion is not about using a GLM instead of a GLMM, it is about using an ANOVA or t-test, i.e. a test to compare difference between groups (in this case difference in weight between period I and period II).
I do not understand your point. The reason why I am using a GLMM with a random intercept is because I think that the yearly average weight may vary randomly among years.
Comment: t-test and ANOVA are special cases of GLM. Random effect is used to deal with correlation among $\epsilon$. But it seems there is no this kind of correlation in you data. So no random effect is necessary for your analysis.
Comment: I think that my skills in math are too limited to follow your reasoning about the non-zero off diagonal elements. However, I understand the conceptual meaning of  adding a random intercept as that I have included in my model. Actually, I have compared by Likelihood Ratio Test and also by AIC the fit of one model with and another without the random intercept and the former is better than the latter.
Anyway, my question was a bit different. Is there anything wron in using a GLMM (or a GLM) for my case of study? if, as I think, it is OK, how may I convince a reviewer?
Comment: Suppose you have two mice with exact age, month, TBL, TypeCap and year. You did not see them. Someone else measured weight for one mouse and tell you result. Does this weight provide additional information (apart from age, month, TBL, TypeCap and year) for you to guess the weight of another mouse? If yes, it means there is correlation and random effect should be added. If no, no random effect is necessary.
Comment: Right, this is a clear explanation of random intercept.
My question is:
**is it wrong using a GLM or GLMM instead of an ANOVA or t-test for my case study?**
Note that I have unbalanced data and lot of variables related to my response variable.
**how may I convince a reviewer that it is OK?**
Comment: If your answer to my previous question is "yes", GLMM is needed. If "no", GLM is good enough. Convincing the reviewers is very hard.

GLMM to test change between two periods


how to avoid installing rails as a system gem by using bundler and expect

Question: I'm trying to make a new rails application with a intent not to install gems as system gem as possible.
At first I installed bundler as system gem, made a Gemfile which specified only rails and executed 'bundle install'. (In my opinion, bundler is OK to be a system gem...)
mkdir -p /opt/rails/rails_app
cd /opt/rails/rails_app
gem install bundler
bundle init
cp Gemfile /tmp
sed 's/#gem rails/gem rails/' /tmp/Gemfile > Gemfile
bundle config build.nokogiri --use-system-libraries
bundle install --path vendor/bundle

Rails was installed as a 'local gem' which is limitted within /opt/rails/rails_app.
Then I tried to make a rails application by 'rails new'.
bundle exec rails new . --skip-bundle

This caused replacing the Gemfile, so a message was shown like this.
Overwrite /opt/rails/rails_app/Gemfile? (enter "h" for help) [Ynaqdh]

Usually what should be done is only type 'y'. However, this time, I want to do that automatically for making a vagrant's provision script.
So I tried expect but it never worked. All results were either timeout or syntax error:
expect -c "
spawn bundle exec rails new . --skip-bundle --quiet
expect \"Overwrite /opt/rails/rails_app/Gemfile? (enter \"h\" for help) \[Ynaqdh\] \"
send \"y\r\"
"

I couldn't find where is wrong in this code and other solutions than using expect.
Comment: Have you looked at [rvm](https://rvm.io/) or [rbenv](https://github.com/sstephenson/rbenv)?  They let you install Rubies and gems (including Rails) to your home directory.  No root privileges are needed.
Comment: No, I didn't. I'll try them.Thanks.
Comment: About the solution with expect, I got answer at another question: http://stackoverflow.com/questions/31601455/expect-script-string-with-square-braces-doesnt-match
Answer: It looks like there is a skip_gemfile option in the rails generator
Answer: You can use bundle install --path [directory] to install you gems locally inside your app.  Typicall you would use './vendor/bundle' as your directory.


Number of gap techniques in American Football

Question: While reading this thread and this one I had trouble following the football terminology of the different "techniques" for defensive line men.
What does it mean to have a 1 / 2 / 3 / 5 gap technique defensive linemen?
What does that gap mean?
Answer: The gap refers to the empty space between offensive linemen on the opposing team at the line of scrimmage. If you have a 1 or 2 gap defensive linemen, it means that he is responsible for keeping the offensive team from advancing through either one or two gaps, or responsible for  advancing himself between the gap and tackling the ball carrier behind the line of scrimmage. See the below example for an illustration.

In this example the defensive linemen (the four shaded triangles) are all playing a one gap technique as they are only responsible for a single gap in the offensive line of scrimmage.
The offensive team often uses the terms "A-Gap" or "B-Gap" to refer to the gaps on the offensive line. The A-Gap's are the gaps on either side of the center. The B-Gap's are the gaps between the guards and the tackles. The C-Gaps are the gaps between the tackles and the tight-ends. So a running play that was meant to run to the "Strong-side B-Gap" would run to the offensive right (strong-side is determined by the side that the tight-end is lined up on) between the Right Guard (RG) and the Right Tackle (RT).
Comment: Where do I find more info like this? I can never understand the intricacies of football.
Answer: Many defenses will number different positions on the offensive lineman to indicate where the defender should line up. It's used as a short-cut. Each team can have their own system. Here are some that are the commonly accepted ones you'll hear on TV:

0 - head up on center
1 - outside shoulder of center
2 - inside should of the guard
3 - outside shoulder of the guard
4- inside shoulder of the Tackle
5 - outside should of the tackle (a wide "5" is common for pass rushers)
7 - inside shoulder of the tight end
9 - outside shoulder of the tight end

These apply to both the left and right sides of the defense. Here is one explanation:
http://www.denverpost.com/premium/broncos/ci_14630467
http://sonsofsamhorn.net/topic/55895-3-technique-vs-5-technique/


Is this a case of Non-Repeatable Reads?

Question: I have the following tables (here modeled in Entity Framework, but my question has nothing to do with EF):

As you can see, this is a versioned Product table. The Id column is the primary key, but the combination (EntityId, VersionId) could be the primary key as well. EntityId denotes the Id of the entity which is constant between different versions of the entity. The entity gets deleted by writing a row with IsDeleted = 1.
The stored procedures that are responsible for data manipulation first check if the data operation is okay. For example, the UPDATE SP checks if the entity has already been deleted. If those checks succeed, the SPs generate a new row in the Version table, followed by a new row in the Product table:
(pseudo-code):

sp_Product_Update:
(1) IF EXISTS (SELECT Id FROM Product WHERE IsDeleted = 1 AND EntityId = @ProductId)
        RAISERROR "Entity has already been deleted"
        RETURN
(2) INSERT INTO Versions ...
(3) INSERT INTO Product ... (IsDeleted = 0)

sp_Product_Delete:
(1) IF EXISTS (SELECT Id FROM Product WHERE IsDeleted = 1 AND EntityId = @ProductId)
        RAISERROR "Entity has already been deleted"
        RETURN
(2) INSERT INTO Versions ...
(3) INSERT INTO Product ... (IsDeleted = 1)

This works all well.
Currently, I'm analyzing this for concurrency issues. Imagine the following concurrency scenario, where two SPs are invoked at the same time, for the same entity:
Transaction 1                          Transaction 2
sp_Product_Update                      sp_Product_Delete

(1) Check succeeds, entity has not yet been deleted.

                                       (1) Same check.

                                       (2) INSERT INTO Versions...
                                       (3) INSERT INTO Product.. (IsDeleted = 1)

(2) INSERT INTO Versions...
(3) INSERT INTO Product ... (IsDeleted = 0)

As you can see, this race condition leads to inconsistent data, namely an IsDeleted = 0 row which comes after an IsDeleted = 1 entry.
So we have to determine what level of isolation we need to avoid this race condition.

This doesn't appear to be a Dirty Read, since the data that is read in (1) is not dirty.
It's no Non-Repeatable Read either, there are no two reads in either transaction.
Same goes for Phantom Read, there are no two queries in either transaction.

So I'm left with two questions:

Is my analysis correct?
What isolation level is needed to avoid this kind of issue?
Answer: Your solution requires serializable isolation level as all commands need to be executed together as one atomic operation.
If you would not use stored procedures, I would encourage to use optimistic locking which is designed for this kind of situation with high throughput.
Comment: So there are other requirements which influence the isolation level? According to http://en.wikipedia.org/wiki/Isolation_(database_systems), the **Serializable** isolation level just means that I won't get **Dirty Reads**, **Non-Repeatable Reads** nor **Phantom Reads**. How can I know that **Serializable** prevents my issue?

Is this a case of Non-Repeatable Reads?


Como acessar um elemento (ou seus valores) gerado dinamicamente?

Question: Sei que é possível usar o on() e delegar o seletor, assim ele acessa o elemento dinâmico a partir de um elemento estático, mas se não tiver como usar o on(), o que fazer?
Por exemplo, dentro de uma função qualquer eu preciso pegar o id de um elemento adicionado dinamicamente para mudar um atributo de estilo e não existe um evento que dispare o on():
jQuery
function(){
    if(1 + 1 == 2){
        //Não vejo como usar o on() nessa situação.
        $("#elemento").css("color", "black");
    }
    //Talvez...
    $("#elemento2").on((1 + 1 == 2), "#elemento", function(){
        $("#elemento").css("color", "black");
    });
}

Existe algum outro método, como gerar ações que independam de outras ações do usuário ou é impossível fazer isso com jQuery?
Comment: Você quer então uma maneira de seu script sempre ficar de olho e poder interagir com novos elementos inseridos no DOM, sem ficar preso a eventos do cursor como o hover e o click?
Acredito que uma boa são os **Mutations Observers**, mas eu ainda não tenho uma prática muito bacana com eles.
Comment: Não entendi! O que deseja fazer? Você poderia explicar resumidamente.
Comment: @MarcosFreitas, exato, quero gerar ações que independam do usuário, vou adicionar essa afirmação na pergunta, talvez a deixe mais esclarecida.
Comment: Pois bem, assim só posso te ajudar indicando esse artigo sobre os **M. Observers**: http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers
Comment: Você quer algo como um evento que dispare quando um estilo é alterado? Ou você quer somente selecionar o elemento com jQuery?
Comment: No caso, selecionar o elemento com jQuery, no exemplo o `#elemento` deveria mudar a cor da fonte quando 1 + 1 for igual a 2, mas isso não acontece, pois o `#elemento` é adicionado dinamicamente.
Comment: @Patrick tem algum caso concreto que lhe levantou essa questão? se __sim__ por favor coloque o código todo ou crie uma situação específica onde este problema surge. Para ser honesto ainda não percebí o que procura fazer...
Comment: Já agora dê uma olhada aqui, no caso de ser isto que procura: https://github.com/naugtur/insertionQuery
Comment: Adicionei mais um exemplo ao código, não sei se vai ajudar a entender...
Comment: Se a ação que você quer que seja disparada seja sempre a mesma, porque você não usa classes CSS quando for criar os elementos dinâmicos?
Comment: @Kazzkiq, algo como `display: none` e depois `display: block`?
Comment: Patrick, qual é o problema com o código que você postou (primeiro if)? Ele funciona contanto que o elemento exista na página. E se ele não existir, não faz sentido mudar a cor... Desculpe, mas continua difícil de entender o que você está procurando.
Comment: Imagine que o elemento fora adicionado dinamicamente, sem delegação ele não vai funcionar.
Answer: Parece que você está confuso sobre a necessidade de delegação. Quando você seleciona um elemento com jQuery – por exemplo, com $('#algumId') –, o elemento só é selecionado se ele existir. Se ele não existir, você não pode fazer nada com ele (como alterar conteúdo, atributos, ou associar uma função que trate um evento nesse elemento).
Delegação de eventos é uma forma de se definir como tratar eventos em determinado elemento antes mesmo de ele existir no DOM. Porém, na hora em que o evento é disparado, o elemento naturalmente precisa já existir no DOM para que sua função delegada faça alguma coisa.
Se você quer alterar o conteúdo ou atributo do elemento, basta fazer isso diretamente:
function pintaDePreto(){
    $("#elemento").css("color", "black");
}

Não faz sentido falar em delegação nesse caso, não há eventos envolvidos. Se o elemento #elemento existir quando a função for chamada, será aplicado color: black nele. Se ele não existir, nada acontece. Isso não tem a ver com o elemento ser ou não adicionado dinamicamente, e sim com a própria existência do elemento no DOM. Se ele não existir, não faz sentido querer mudar a cor! Então apenas garanta que a função será chamada quando o elemento alvo existir.
Comment: Então se usa delegação apenas onde existem eventos, caso contrário, basta fazer como no seu exemplo?
Comment: Isso, na verdade o que se chama "delegação" é *event delegation*, portanto delegação **de eventos**.


focus on accessible UI element in cocoa programmatically

Question: I have a toolbar with a button and an NSView with a titled box. When the window opens and Voice Over is on, I want the focus to be on the titled box. Currently it's on the toolbar button, because it's probably higher in accessibility hierarchy. What should I do to have a focus on the box, instead on button?
Thanks
Answer: The solution was to access the window accessibility hierarchy in windowDidLoad like this:
id windowElement =  NSAccessibilityUnignoredDescendant(self.window);
NSArray *windowElements = [windowElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];

After that the element that is supposed to be first in hierarchy should be found in windowElements array. Say we found it and its index is firstElIndex then:
    NSMutableArray *mutArray = [NSMutableArray arrayWithArray:windowElements];
        id firstElement = [[mutArray objectAtIndex:firstElIndex] retain];

        [mutArray removeObject:firstElement];
        [mutArray insertObject:firstElement atIndex:0];

        [windowElement accessibilitySetOverrideValue:mutArray forAttribute:NSAccessibilityChildrenAttribute];
        [windowElement accessibilitySetOverrideValue:mutArray forAttribute:NSAccessibilityVisibleChildrenAttribute];
        [windowElement accessibilitySetOverrideValue:mutArray forAttribute:NSAccessibilitySelectedChildrenAttribute];
        [firstElement release];

Finally we override windowElement children attribute with new array, where the element we want the focus to be on will be at the first place.
This is the example for a very simple case. But this is the way to go.


Is using both training and test sets for hyperparameter tuning overfitting?

Question: You have a training and a test set. You combine them and do something like GridSearch to decide the hyperparameters of the model. Then, you fit a model on the training set using these hyperparameters, and you use the test set to evaluate it.
Is this overfitting ? Ultimately, the data was not fitted on the test set, but the test set was considered when deciding hyperparameters.
Comment: This is a case of  Data Leakage. Similarly in the statistics the term  data snooping (data dredging) - is used [https://en.wikipedia.org/wiki/Data_dredging].  You leak some information from test set to the train set. This will falsely improve the performance of your model on the test set.
Comment: Related:  https://stats.stackexchange.com/questions/189678/is-it-better-to-do-exploratory-data-analysis-on-the-training-dataset-only
Comment: Intuitively it would be like scoring a student's capability on a test where the student already know the solutions. It's not overfitting, it's just that you would have no idea about the performance of the model
Answer: The idea behind holdout and cross validation is to estimate the generalization performance of a learning algorithm--that is, the expected performance on unknown/unseen data drawn from the same distribution as the training data. This can be used to tune hyperparameters or report the final performance. The validity of this estimate depends on the independence of the data used for training and estimating performance. If this independence is violated, the performance estimate will be overoptimistically biased. The most egregious way this can happen is by estimating performance on data that has already been used for training or hyperpameter tuning, but there are many more subtle and insidious ways too.
The procedure you asked about goes wrong in multiple ways. First, the same data is used for both training and hyperpameter tuning. The goal of hyperparameter tuning is to select hyperparameters that will give good generalization performance. Typically, this works by estimating the generalization performance for different choices of hyperparameters (e.g. using a validation set), and then choosing the best. But, as above, this estimate will be overoptimistic if the same data has been used for training. The consequence is that sub-optimal hyperparameters will be chosen. In particular, there will be a bias toward high capacity models that will overfit.
Second, data that has already been used to tune hyperparameters is being re-used to estimate performance. This will give a deceptive estimate, as above. This isn't overfitting itself but it means that, if overfitting is happening (and it probably is, as above), then you won't know it.
The remedy is to use three separate datasets: a training set for training, a validation set for hyperparameter tuning, and a test set for estimating the final performance. Or, use nested cross validation, which will give better estimates, and is necessary if there isn't enough data.
Comment: suggested edit: future data -> unknown/unseen data: distribution can change over time (in my field e.g. drift due to detector aging, ...), so we evaluate future performance separately, from generalization error which measures predictive abilities wrt. just unknown data.
Answer: I would say you are not necessarily overfitting, because overfitting is a term that is normally used to indicate that your model does not generalise well. E.g. If you would be doing linear regression on something like MNIST images, you are probably still underfitting (it does not generalise enough) when training on both training and test data.
What you are doing, however, is still not a good thing. The test set is normally a part of the data that you want to use to check how good the final, trained model will perform on data it has never seen before. If you use this data to choose hyperparameters, you actually give the model a chance to "see" the test data and to develop a bias towards this test data. Therefore, you actually lose the possibility to find out how good your model would actually be on unseen data (because it has already seen the test data).
It might be possible that you do not really care about how well your model performs, but then you would not need a test set either. Because in most scenarios you do want to have an idea how good a model is, it is best to lock the test data away before you start doing anything with the data. Something as little as using test data during pre-processing, will probably lead to a biased model.
Now you might be asking yourself: "How should I find hyperparameters then?". The easiest way would be to split the available data (assuming that you already safely put away some data for testing) into a training set and a so-called validation set. If you have little data to work with, it probably makes more sense to take a look at cross validation
Answer: Yes, you are overfitting. The test set should be used only for testing, not for parameter tuning. Searching for parameters on the test set will learn the rules that are present in the test set, and eventually overfit it.
Comment: You're not overfitting *per se*, but indulging into data leakage. See other answers.
Answer: It is not necessarily overfitting, but it also runs an unnecessary risk of overfitting, and you deprive yourself of the possibility to detect overfitting.

Overfitting happens when your model is too complex/has too many degrees of freedom for the available training data. This includes degrees of freedom for the hyperparameter space you search. So if your data set is still large enough, you don't overfit (say, you have thousands of cases, just two variates to regress on and a single continuous hyperparameter to tune - that would likely still be OK. On the other hand, if you a handful of cases, hundreds or thousands of variates and a large hyperparameter search space, you run a huge risk of overfitting).
But as all your data entered the training phase (during the hyperparameter optimization), you lost the chance to measure generalization error and thus cannot check/show that you do not overfit.  Which is as bad as overfitting, unless you can give other evidence that you are not in a situation where overfitting can occur.
Moreover, you traded in your ability to measure generalization error for at most a minute improvement in training: You could (and should) have done the whole training on the training set - that's what it is for. And training includes fixing the hyperparameters.
From that point of view, the decision is really whether you need to have an error estimate based on unknown data or not (again based on the overall risk of overfitting - and in machine learning the decision would pretty much always be that unknown data performance is needed), and then either do the whole training on your data, or do the whole training on the training set and test with the test set. (Or possibly on multiple such train/test splits as in cross validation).
Answer: It is an "in-sample" forecast since you eventually make the forecast on observations that are already part of your training set. Why not use n-fold cross-validation? By doing that, at each time, you are making "out-of" sample forecast, in which test set and training set are separate.
Answer: The idea of CV is to overcome the weaknesses of Train-Test split (loss of information, only a part being used for testing etc.). Hence, CV ensures that all parts of data falls into training and testing folds in the successive iterations. This ensures that we get a balanced picture of whatever we are trying to evaluate (choice of hyperparameter, algorithms etc.).
Given this situation, you should use entire dataset for tuning. If you use only train fold, the tuned hyperparameter would be specific to Train fold; not the whole data. My experience is that the model would exhibit overfitting even after tuning using only Train set.
imho, practitioners are going overboard with the term 'data leak'. In the effort to prevent data leak, they are giving too much importance to train-test split; which is just a chance. Judicious application of CV is the best approach. Not a combination of Train-Test split and CV.


Probability - intersection and union

Question: How to express a general relationship between $P(A\cup B \cup C)$ and $P(A\cap B \cap C)$, please? $A, B, C$ are phenomena of occurrence.
Is this correct?
$$P(A\cup B \cup C) = \frac{1}{2}[P(A)+P(B)+P(C)-P(A\cap B)-P(A\cap C) - P(B \cap C)]$$
Answer: For two events $U$ and $V$,
$$
P(U\cup V) = P(U)+P(V)-P(U\cap V).
$$
Then
$$
\begin{aligned}
P\left(A\cup B\cup C\right) &= P\left(\left(A\cup B\right)\cup C\right) = P\left(A\cup B\right) + P(C)-P\left(\left(A\cup B\right)\cap C\right) = \\
&= P(A)+P(B)-P(A\cap B) + P(C) - P\left(\left(A\cap C\right)\cup \left(B\cap C\right)\right) = \\
&=P(A)+P(B)-P(A\cap B)+P(C)-\left[P(A\cap C) + P(B\cap C)-P(A\cap C\cap B\cap C)\right] = \\
&= P(A) + P(B) + P(C) - P(A\cap B)-P(A\cap C) - P(B\cap C) + P(A\cap B \cap C)
\end{aligned}
$$
Comment: Thank you very much

Probability - intersection and union


How to use mailto function in iBooks HTML Widget

Question: I have tried code with the mailto function in a web browser on my iPad which links to the mail app, but the same code does not work in the iBooks (the mailto does absolutely nothing in the iBooks app).
Does anyone know of some sort of workaround for emailing out html form data?
Answer: If you are trying to link inside an iBooks page, open your link inspector and the "Link to" menu should have an email option.
If you are using the HTML widget option, you could try something like this:
Open Email


Please Wait dialog

Question: I have problem with showing a dialog in Thread.Sleep method here is my code, its not working.
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent arg0) {
    JDialog loading = new LoadingDialog();
    loading.setVisible(true);
    try {
      Thread.sleep(6000);
    } catch (Exception e) {
      e.printStackTrace();
    }
    loading.dispose();
  }
});

and
public class LoadingDialog extends JDialog {
  public LoadingDialog(){
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension screenSize = tk.getScreenSize();
    int screenHeight = screenSize.height;
    int screenWidth = screenSize.width;
    setBounds((screenWidth-400)/2, (screenHeight-200)/2, 350, 80);
    getContentPane().setLayout(null);
    setResizable(false);
    setUndecorated(true);
    JLabel lblPleaseWaitWhile = new JLabel("Please wait while starting the services.");
    lblPleaseWaitWhile.setBounds(85, 22, 313, 14); getContentPane().add(lblPleaseWaitWhile);
    setVisible(true);
  }
}

Help me to solve this.
Comment: Its not displaying the loading dialog. It waits for 6 sec and the exits.
Comment: What exactly does *its not working* mean?
Comment: What error or exception are you getting? I notice you're missing a semicolon after `new LoadingDialog()` but that might just be a typo.
Comment: missing a semicolon is a typo error here. Sorry for that.
Comment: if I run it with a regular `JDialog` in place of a `LoadingDialog` it works as intended. Did you override something like `setVisable()` in your `LoadingDialog`?
Comment: LoadingDialog extends JDialog and I've writen all my controls in constructor.
Comment: part of SwingWorker's Q&A is about
Answer: With your custom Dialog, you're blocking the main thread - try this instead;
btn.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
    final JDialog loading = new LoadingDialog();
    loading.setVisible(true);
    btn.setEnabled(false);

    new Thread(new Runnable() {
      public void run() {
        try {
          Thread.sleep(6000);
        } catch (InterruptedException e) {
        }
        loading.dispose();
        btn.setEnabled(true);
      }
    }).start();
  }
});

Comment: Don't update UI components outside of the context of the EDT. This would actually be a classic case for SwingWorker
Comment: This is working for me too, but if I have custom JDialog, like extending JDialog, how should I proceed.
Comment: @Pasupathi Post `LoadingDialog.java`?
Comment: public class LoadingDialog extends JDialog {

public LoadingDialog(){
 Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension screenSize = tk.getScreenSize();
    int screenHeight = screenSize.height;
    int screenWidth = screenSize.width;
 setBounds((screenWidth-400)/2, (screenHeight-200)/2, 350, 80);
 getContentPane().setLayout(null);
 setResizable(false);
 setUndecorated(true);
 JLabel lblPleaseWaitWhile = new JLabel("Please wait while starting the services.");
 lblPleaseWaitWhile.setBounds(85, 22, 313, 14);
 getContentPane().add(lblPleaseWaitWhile);
 setVisible(true);
}

}
Comment: @Pasupathi Updated based on your LoadingDialog class.
Answer: You better use SwingWorkder int this case. This class allow you to create a thread that runs in background mode. It's suit very well with modal frames.

Please Wait dialog


How many times to repeat an event with known probability before it has occurred a number of times

Question: If I have a known probability of an event occurring, 1% chance, and I need the event to occur a number of times, 120 times, about how many times would I have to repeat the event before I can expect it to happen that number of times?
Comment: How sure do you want to be that the event will have happened that number of times?
Comment: Expecting an event 120 times and needing an event 120 times are _widly_ different things.
Comment: Running such an experiment 100 times would have a failure rate of 1 in e. To jake's point, we need more detail to give a valid answer.
Comment: Somewhere between 120 and infinity.
Answer: Consider a sequence of $n$ independent trials with success probability $p$. Let $X$ be the number of successes out of the $n$ trials. Then $X$ has a Binomial distribution with parameters $n$ and $p$. The expected value of a Binomial rv is $E(X) = np$. A simple approach is to set this equal to $120$ and solve for $n$. Since $p=0.01$, we have $n(0.01) = 120$ which means that $n=12,000$ trials are expected to obtain $120$ successes.

Alternatively, here is a related approach that gives the number of trials needed to observe $r=120$ successes with some probability $\gamma$ (i.e. $\gamma=0.95$).
Consider a sequence of independent trials with success probability $p$. Let $X$ be the number of trials required to observe $r$ successes. Then $X$ has a Negative Binomial distribution with parameters $r$ and $p$. In your case, $X \sim \text{Negative-Binomial}(120, 0.01)$, and you want to find $x$ such that $$P(X \leq x) = \gamma.$$
Although the Negative Binomial distribution has no closed form quantile function, this $x$ can be solved for easily. For instance, the answer can be obtained in R by typing: qnbinom(.95, 120, .01). The answer $x=13728$ indicates that $13,728$ trials are required to have a 95% chance of observing $120$ (or more) successes.
Comment: The first method is equivalent to the second with $\gamma = 0.5$, correct?
Comment: @jpmc26 I get 0.5556 for 12000. I used ```qnbinom(.5556, 120, .01)``` in here : https://rextester.com/l/r_online_compiler
Comment: @jpmc26, the first method will give a similar answer to the second with $\gamma = 0.5$.. but they are not equivalent. The first approach is the expected number of trials (the mean) and the second approach can be thought of as the median number of trials.
Answer: First, I'm going to assume that the experiments are independent since you said the probably of a success is always 1%.  The keyword in your question is "expected," which means we'll be looking for a mean or expected value.
If you are interested in the number of trials $X$ (with common probability of success $p$), needed to obtain $r$ successes, then you can model this as a negative binomial random variable with probability mass function:
\begin{eqnarray*}
f_{X}(x|r,p) & = & {x-1 \choose r-1}p^{r}(1-p)^{x-r}
\end{eqnarray*}
for $x=r,r+1,...,$
The expected value of the negative binomial is well known as:
\begin{eqnarray*}
E(X) & = & \frac{r}{p}
\end{eqnarray*}
In your case, $p=0.01$ and $r=120$.  So the expected number of independent trials of your experiment (times) needed to obtain $120$ successes is simply given by $120/0.01=12,000$
Comment: @DreamConspiracy, no dispute here.  I was making an inference from the OP's description.  In the case of a N.B. PMF with independent events, it would necessarily be the case that the event probability be constant.
Comment: Nitpick: Saying the probability is always 1% is not the same as the trials being independent
Answer: As others have noted, the chance of succeeding enought times will follow a negative binomial distribution. It is useful to plot this, and you can do this in R with:
plot(function(x) pnbinom(x,120,0.01),120,20000)

Which gives:

As you can see it has a sigmoidal shape and there are large areas with virtually no chance and almost certainty and a rapid shift between the two close to the expected value. Therefore, increasing the number of trials may have little effect or a very great effect on the chance of achieving the target depending on how many you've already decided on.
If you scale this function by the number of trails (i.e. mean chance per trial), you can see that there is a clear maximum value,
plot(function(x) pnbinom(x,120,0.01)/x,120,20000)

which you can identify with:
optimise(function(x) pnbinom(x,120,0.01)/x,c(120,20000),maximum=TRUE)
$maximum
[1] 13888

$objective
[1] 6.929301e-05

Answer: As knrumsey says, the number of successes will follow a binomial distribution, but unless you need a high level of precision, 1% is a small enough number that you can use the approximation of a Poisson distribution with $\lambda=120\frac{1\%}{99\%}=1.2121$
Comment: How exactly would one "use" this Poisson distribution to answer the question?
Comment: 1.2 what? trials?
Comment: I like the idea of using the Poisson distribution and am glad you brought it up, but your answer currently is misguided. Letting $F(k,\mu)$ be the value of the Poisson$(\mu)$ CDF and $1-\alpha$ the desired chance of observing at least $n$ occurrences, you can formulate this question as finding the smallest $n$ for which $F(120-1,n\lambda)\le\alpha$ where $\lambda=1/100.$ The answer isn't related to a Poisson$(120\times1/100/(1-1/100))$ distribution! Of interest is the connection with the Gamma distribution: the solution is $F^{-1}_{120-1}(1-\alpha)$ where $F_{120-1}$ is the Gamma$(120-1)$ CDF.
Comment: And why are you multiplying $120$ by $1\%$ (rather than dividing one by the other)?


How to prove it? (one of the Rogers-Ramanujan identities)

Question: Prove the following identity (one of the Rogers-Ramanujan identities) on formal power series by interpreting each side as a generating function for partitions:
$$1+\sum_{k\geq1}\frac{z^k}{(1-z)(1-z^2)\cdots(1-z^k)}=\prod_{k\geq1}\frac{1}{1-z^k}$$
Comment: Above equation is not one of Rogers-Ramanujan identities see http://en.wikipedia.org/wiki/Rogers%E2%80%93Ramanujan_identities
Answer: Let be
$$a_0=1,a_{k}=\frac{z^{k}}{(1-z)(1-z^2)\cdots(1-x^{k})},k>0$$
and
$S_{k}=1+\sum_{i=1}^{k}a_i$.  We want to show that
$$
S_{k}=\frac{1}{(1-z)(1-z^2)\cdots(1-z^{k})}.$$
$S_0=a_0=1$; and assuming it's true for $k=n$, we have
$$
\begin{eqnarray}
S_{n+1}&=&S_{n}+a_{n+1} \\ &=&\frac{1}{(1-z)\cdots(1-z^{n})}+\frac{z^{n+1}}{(1-z)\cdots(1-z^{n})(1-z^{n+1})} \\
&=&\frac{1-z^{n+1}}{(1-z)\cdots(1-z^{n})(1-z^{n+1})}+\frac{z^{n+1}}{(1-z)\cdots(1-z^{n})(1-z^{n+1})} \\ &=& \frac{1}{(1-z)(1-z^2)\cdots(1-z^{n+1})},
\end{eqnarray}
$$
i.e., it's true for $n=k+1$.  So it's true for all $k$ by induction.  In particular, the partial products are equal to the partial sums, and
$$
1+\sum_{k>0}\frac{z^{k}}{(1-z)(1-z^2)\cdots(1-z^{k})}=\prod_{k>0}\frac{1}{1-z^{k}}.
$$
Comment: I want to prove it by interpreting each side as a generating function for partitions not by induction. Thank you anyway.
Comment: From your opinion what is generating function. The equation above is generating function of partition function $p(k)$
Comment: But what is $p(k)$
Comment: $p(k)$ is number of partitions of natural number $k$ for example $p(3)=3$ because 3 has 3 partitions $3,1+2,1+1+1$
Comment: what does  $1+\sum_{k\geq1}\frac{z^k}{(1-z)(1-z^2)...(1-z^k)}$ mean?
Comment: For further investigations you must start reed for example http://en.wikipedia.org/wiki/Partition_(number_theory)
Comment: Proving for any $n$ doesn't really prove it. I think there's a huge loophole about proving its convergence.
Comment: Basically what is being done.You are taking a truncated cone(say) and observing that the truncated cone converges to a certain cone, as you can increasing make more accuracy of the prediction. But that doesn't prove. Does it?
Comment: From a certain recurrence about partition of number in parts I can establish right hand side equation and with some other manipulation as did firstly Euler we can establish right hand side. Details of proof are messy and they can't presented here
Answer: Notations: Let $[n]=\{1,2,\ldots n\}$
$P(n)$ is the number of partitions of $n$.
$P(k,[n])$ is the number of partitions of $k$ taking values from $[n]$.
           for example-$P(n)=P(n,[n])$
Note that coefficients of $x^n$ in left hand side is $\displaystyle\sum_{k=0}^{n-1}P(k,[n-k])$.Easy enough the coefficients of $x^n$ in the right hand side is $P(n)$.
We shall establish a bijection between them.
For some $m$, we shall denote any partition $<\lambda_1,\lambda_2,\ldots \lambda_m>_n$ among the set of partitions of $n$.
With $\lambda_i\le\lambda_j$ for all $i\ge j$
Take any such partition $<\lambda_1,\lambda_2,\ldots \lambda_m>_k$. Construct a new partition $<\lambda_1,\lambda_2,\ldots \lambda_m,\lambda_{m+1}=n-k>_n$.
I claim by constructing new partitions like this from all the partitions of of each $i$, where $i\in[n-1]$ we get unique partitions of $n$.
Remark- For the case $k=0$ we add $n$ to get the trivial partition $<n>_n$.
Hence, on the contrary assume some two of the constructed partitions are equal.
But the maximum element is $n-k$ for some partition constructed from $k$.
Hence the two equal constructed partitions must be from the same $k$.
Easy enough to prove the partitions are equal.
Now, it remains to show in the other way, i.e. to show by subtracting the maximum element we get all such partitions.
Whhich we can do by a very similar arguement.
Answer: Let us use the notation $[z^n] \sum_k a_k z^k$ to represent the operation of extracting $a_n$, the coefficients of $z^n$, from a formal power series $\sum_k a_k z^k$.
Let us look at the components in RHS of the identities we want to show:
$$1+\sum_{k\geq1}\frac{z^k}{(1-z)(1-z^2)\cdots(1-z^k)}=\prod_{k\geq1}\frac{1}{1-z^k}\tag{*}$$
We know:
$$[z^n]\frac{1}{1 - z^k} = \begin{cases}1,&k|n\\ 0,&\text{otherwise}\end{cases}$$
This represent the tautology that the number of ways to represent $n$ as a multiple of $k$ is $1$ if $k|n$ and $0$ otherwise.
Similarly, the expression:
$$[z^n]\left(\frac{1}{1-z^k}\frac{1}{1-z^l}\right)$$
is the number of ways of breaking $n$ into 2 unordered pieces, one piece is a multiple of $k$ while the other is a multiple of $l$. In general,
$$[z^n] \prod_{k\ge 1}\frac{1}{1-z^k}$$
is the number of ways of breaking $n$ into sum of integers $\ge 1$. Once again, order of the breakdown doesn't matter.
In the LHS of $(*)$, the $k$-th term:
$$[z^n]\frac{z^k}{(1-z)(1-z^2)\cdots(1-z^{k})}$$
is the number of ways to represent $n$ as sum of positive integers $\le k$ and the factor $z^k$ in numerator constraints the sum to use the integer $k$ at least once. ie. if $n = c_0 + c_1 + \cdots + c_r$, is a breakdown of $n$ as sum of integers $c_s \ge 1$, the $k$ corresponds to
$\max( \{ c_1, \ldots c_r \} )$, the maximum of integer appear in a breakdown.
The $\sum_{k}$ part in LHS of $(*)$ can now be interpreted as a sub sum of RHS with respect to the maximum of integer appear in a breakdown. The extra $1$ in LHS is used to cover the special case in RHS where $0$ is treated as a sum of zero number of positive integers.


synchronized blocks and dispatch_async

Question: What happens to the lock in IOS using @synchronized() when we call dispatch_async() within the block.
For ex:
    id myID
-(void) foobar
{
    @synchronized(myID){
        dispatch_async(){ //do stuff with myID};
    }
}

Is the lock still valid within the dispatch_async call? Or more importantly is there any drawbacks in using another @synchronized() call inside dispatch_async()?
Comment: What are you trying to achieve?
Comment: BTW, am I correct in assuming that you are _not_ reinstantiating `myID` at any point? The `@synchronized` block is unique to that particular instance of the object pointed to by `myID`, not the variable in general.
Answer: Assuming you're trying to synchronize the interaction with this myID object in the background queue, you want it the other way around, the lock inside the dispatched block. Right now you have:
@synchronized(myID) {
    dispatch_async(queue, ^{
         // do stuff with myID
    });
}

That's synchronizing the process of adding the dispatched block to your queue, but does not synchronize what you're doing in the background. I suspect that's not what you meant.
You probably intended:
dispatch_async(queue, ^{
    @synchronized(myID) {
         // do stuff with myID
    }
});

It looks very similar, but results in an entirely different behavior. Now, the work dispatched to the background queue is being synchronized.
As a further refinement, if this dispatched block is possibly slow (and I assume it may be), then you'd probably want to constrain the @synchronized block as much as possible:
dispatch_async(queue, ^{

    // do slow stuff in preparation for interacting with `myID`

    @synchronized(myID) {
         // quickly do stuff with myID
    }

    // do anything else here
});

If you do all of the background block within a @synchronized block, you may defeat the entire purpose for dispatching it to the background, namely to minimize impact on the main queue. This last rendition mitigates that problem.
As a final observation, if you have a serial queue (or a non-global concurrent queue in which you do updates with a barrier), that's often used as a technique that eliminates the need for locks altogether, as long as all updates and inquiries for myID are dispatched to that queue. See Eliminating Lock-Based Code in the Concurrency Programming Guide.
Comment: When you say "minimize impact on the main queue" you mean only that the background process is going to take longer, right? The work is still being done in the background queue and would not e.g. block the UI.
Comment: @Ixx - No, my point is that if (a) you do something time-consuming inside a `@synchronized` block on a background thread; and (b) if the main thread also needs to access `myID` (and therefore would have to use `@synchronized`, too), your background `@synchronized` block can easily block the main thread's, defeating the purpose of dispatching this stuff to a background queue altogether. So, when the background thread has to do `@synchronized`, make sure you get in and out as quickly as possible, keeping time-consuming stuff outside of the `@synchronized` block, if you can.
Answer: The lock there would just prevent two different blocks being dispatched at once. However they're dispatched asynchronously, so they may be performed then or may be performed arbitrarily far in the future. The dispatch call also won't wait for them to complete.
So the stuff inside the block isn't synchronised. Options to achieve that with minimal changes are a synchronous dispatch or just @synchronizing within the block.
Depending on what you're doing, the best idea might be to establish a serial dispatch queue and dispatch your blocks onto that.

synchronized blocks and dispatch_async


Cursor do input indo para final da linha com jQuery e propertychange

Question: Por exemplo, eu preencho o input deste fiddle com "ste" e depois volto para o início do input para digitar "te" antes de "ste", ele vai para o fim do input quando digito o primeiro caractere "t".
Ou seja, sempre que digito um caractere e o cursor não está no fim, o cursor vai para o fim do input após eu digitar o caractere.
Este é o script que estou utilizando. Vi em algum lugar que setando o this.selectionEnd funcionaria mas não funcionou.
    $('body').on('input propertychange', '#form_cliente_id', function (e) {
        var position = this.selectionStart;
        e.preventDefault();
        $('#form_cliente_id').submit();
        this.selectionEnd = position;
    });

Alguma dica de por que está acontecendo isso e como resolver?
Obrigado!
Answer: Descobri que o problema estava no seguinte trecho:
oninput="this.value = this.value.toUpperCase()"

Retirando este trecho e incluindo este trecho, resolveu o problema:
style="text-transform: uppercase;"

Answer: Você estava pondo o manipulador de evento no id errado. Em vez de #form_cliente_id, deveria ser #nomecliente:
$(function () {
  $(document).on('change', '#nomecliente', function () {
    alert('Submitei o form com nome de cliente: "' + $(this).val() + '"');
    $(this).parents('form').submit();
  });
});

Veja o fiddle.
Comment: #form_cliente_id é o id do form. O código original é ativado quando algo é mudado em qualquer input do form. No exemplo da pergunta não faz muita diferença, mas no caso real há vários inputs.
Além disso, o problema não foi corrigido em seu fiddle.
Mas acabei descobrindo a solução


Finding least upper bound and greatest lower bound

Question: Consider the poset ($\mathbb{Z}^+ - \{1\}, |)$.
What is the least upper bound and greatest lower bound of $\{6,10,14,15\}$?
I don't see how the set in the question applies to the poset.  What operations am I supposed to be performing on these numbers to determine what the GLB or LUB is?
EDIT: The answer says there is no GLB and that the LUB = 2*3*5*7 = 210.  Why is this so?
Answer: You've been given the order relation: it's $\mid$, divisibility. Because it may be difficult to think order relation when you see $\mid$, let me use $\preceq$ instead: I'll write $m\preceq n$ if and only if $m\mid n$. Thus, for instance, $3\preceq12$, but $3\not\preceq 5$. You're asked for the least upper bound and greatest lower bound of the set $\{6,10,14,15\}$. The least upper bound, if it exists, is an integer $n\in\Bbb Z^+\setminus\{1\}$ such that:

$6\preceq n$, $10\preceq n$, $14\preceq n$, and $15\preceq n$; and
if $m\in\Bbb Z^+\setminus\{1\}$ and $6\preceq m$, $10\preceq m$, $14\preceq m$, and $15\preceq m$, then $n\preceq m$.

The first condition makes $n$ an upper bound for $\{6,10,14,15\}$; the second makes it the least upper bound.
Remember that $\preceq$ is really just divides, so the first condition really just requires that $n$ be a multiple of each of the numbers $6,10,14$, and $15$; in other words, it must be a common multiple of the elements of the set $\{6,10,14,15\}$. The second condition says that if $m$ is any common multiple of these four numbers, then $n\mid m$; in other words, $n$ is not just a common multiple of them, but the least common multiple.
You should now be able both to find $n$. With that as an example, you should be able to figure out what a lower bound has to be in terms of divisibility, and then what the greatest lower bound must be. Be careful, though: remember that $1$ is not in the partial order.
Comment: There seems to be a weird MathJax bug which makes me see "$3\preceq12$, but $3\preceq5$", even though you mean (and typed) a "not" in the second one. Let me try again in this comment, to test how it appears: $3\not\preceq5$. (I still don't see the not.)
Comment: @ShreevatsaR: I see it in your comment. (On the other hand, Firefox is currently not displaying embedded images for me.)
Comment: I also see what @ShreevatsaR sees.  Thanks for the thoughtful response, Brian.  Do you mind just elaborating a little more on the $\preceq$ notation?  I've seen it used quite often, but I don't really have a great intuitive sense of what it means.
Comment: I've also seen it as $\prec$.  Is there a difference?
Comment: @user1038665: It's just a common symbol for a partial order relation. The difference between $\prec$ and $\preceq$ is entirely analogous to the difference between $<$ and $\le$: $x\preceq y$ allows the possibility that $x=y$ as well as the possibility that $x\prec y$ in the strict sense. (Be careful, though: I have occasionally seen $\prec$ used in the non-strict sense, just as $\subset$ is sometimes used to mean $\subseteq$.)
Comment: Got it. Thanks again.
Comment: @user1038665: You're welcome.
Answer: In the poset $(\mathbb Z^+ \setminus\{1\}, \mid)$ a lower bound is a common divisor and an upper bound is a common multiple. So you have to find the greatest common divisor and the least common multiple (if such exist in $\mathbb Z^+\setminus\{1\}$) of your given numbers.
Comment: So the GLB is the smallest number that divides all of 6, 10, 14, 15? And the LUB is the smallest number that is a multiple of 6, 10, 14, 15?
Comment: @user1038665 Yes.
Comment: @user1038665: The GLB is the *largest* (greatest) number that divides all of 6, 10, 14, 15.
Answer: Well, since the ordering relation is $|$ (divides), then, you can rephrase the "least upper bound" question as "what number, is divisible by 6, 10, 14, and 15, and such that no divisor of it is itself divisble by 6, 10, 14, and 15". Now, "is divisible by x" is the same as "is a multiple of x", so we see that we want a multiple of 6, 10, 14, and 15 that is not itself a multiple of such a multiple. A candidate is the least common multiple (or lcm) of 6, 10, 14, and 15. This will be divisible by all of those, and furthermore, we can prove it is the desired least upper bound since it is not divisible by another such multiple, since such a multiple would have to be a smaller one, but it's the least one (note that if $n | m$, then $n \le m$. Since $n \ne m$ in this case, $n < m$). We have $\mathrm{lcm}(6, 10, 14, 15) = 210$, so 210 is the least upper bound.
Now, for the greatest lower bound. We can rephrase this as "what number is a divisor of 6, 10, 14, and 15, and such that it is not itself a divisor of such a divisor". A natural candidate is then the greatest common divisor (or gcd) of 6, 10, 14, and 15. This will be a divisor of all of those. To prove this is the desired number, we merely note that if it was a divisor of another such divisor, then there would be a larger common divisor, but it's the greatest one. We have $\gcd(6, 10, 14, 15) = 1$. BUT!!! $1$ is not in the set! So, there is NO greatest lower bound. There are in fact no lower bounds at all, since there are no common divisors except $1$!


Finding the min/max of consecutive numbers which equal a given sum

Question: Given a consecutive list of numbers of size $n$, and a total sum figure $t$, what is the simplest way of finding the minimum $min$ and maximum $max$ numbers of that consecutive list?
For example,
$t = 10$
$n = 4$
$1 + 2 + 3 + 4 = 10$
$min = 1, max = 4$
Is there a way to find out the min/max for any sum value?
Updated: Added size of list condition
Comment: Are we told the size of the list?
Comment: This is a good point. Yes you're told the size of list. I've updated the question.
Answer: If list size = even like in your case, the minimum is $\lfloor sum/listsize\rfloor - (listsize/2-1)$ and the maximum is  $\lceil sum/listsize\rceil + (listsize/2-1)$.
If list size = odd, the minimum is $ sum/listsize- (listsize-1)/2$ and the maximum is  $ sum/listsize + (listsize-1)/2$.
Comment: How would this work for lists of various sizes? Say I want 10 numbers, or maybe 100 numbers?
Comment: Based on changed notations, listsize is $n$ and sum = $t$. If $n$ is even, the mean is fractional, there are $(n/2-1)$ below the floor and same above the ceiling, which gives those numbers in the result. For $n$ odd, mean gives the center number and there are $(n-1)/2$ numbers below and above that. Hope this helps see the result mentioned. So, it works for any $n$,$t$.
Comment: I've tried this, but it just doesn't seem to work. Given $t=1000$ and $n=20$. I get 41 and 59 as the mix/max. That sums to 950 and only has 18 consecutive numbers
Comment: You cannot get 20 consecutive numbers with sum of 1000 - since 20 is even, sum/20 has to have 0.5 fractional part.
Comment: In your case of 41 to 59 with sum 950 - try $n=19$, $t=950$, and you will get the needed answer.
Comment: That makes sense, thanks. I also just noticed that you can get negative min numbers. Any way to ensure this is positive numbers only? e.g. $t=1500$, $n=100$
Comment: Can you first explain which 100 consecutive numbers sum to 1500 - by the same logic as before since $1500/100$ is integer and $100$ is even, this is not a valid choice.
Comment: ahh okay, I'm working approximately. The person I'm writing the code for, won't necessarily know what a "valid" choice is. 1500/100 gives me -34 and 64.
Answer: Let the first number be n then the sum of four consecutive numbers are
$$n+n+1+n+2+n+3=4n+6$$
Now $$4n+6=given sum$$
Find n and n+3
the number of numbers in the list must be given so that u can add those many numbers and then equate it to the given sum then find the min and max of these numbers.


VaR in case of ARMA-GARCH?

Question: How do I calculate the VaR in case of using an ARMA-GARCH approach? I am not good at time series, so I am more or less confused with the different possible notations of an ARMA-GARCH process. I hope the notation I use is correct.
Suppose I use the following AR(1)-GARCH(1,1):
\begin{align*}
r_t=\delta + \phi_1 r_{t-1} + z_t\\
z_t = \sigma_t \epsilon_t\\
\epsilon_t \text{ is } N(0,1)\\
\sigma_t^2=\alpha_0+\alpha_1 z_{t-1}^2+\beta \sigma_{t-1}^2
\end{align*}
I mean, I would have to calculate a quantile at timepoint t. Normally in case of a more simpler approach:
$r_t=\mu + \sigma_t*\epsilon_t$ and the $\epsilon_t$ is N(0,1) this would give
$VaR=\mu + \hat{\sigma_t}*z_\alpha$ where $z_\alpha$ is the quantile of the standard normal. How to do this in case of the ARMA-GARCH approach? I now have no $\mu$, but an AR process?
I read some papers, they all give more or less the ARMA-GARCH formula and say that they generate the forecast, but they give no formula, how to do this.
Answer: To estimate $VaR$ of the one-step-ahead return (which is what you seem to need to do) you should do the following ($E_t$ denotes the conditional expectation given the values of the time series up to and including the moment $t$ have been observed):

Compute the forecast of the mean. In your case of $AR(p)$ process you
should do the following: $$r_{t+1|t} = E_t(r_{t+1}) = E_t( \delta +
    \sum^p_{k=1} \phi_k r_{t+1-k} + \sigma_{t+1} \epsilon_{t+1})$$ which
reduces to $r_{t+1|t} = \delta + \sum^p_{k=1} \phi_k r_{t+1-k}$,
since $\epsilon_{t+1}$ has zero mean, and $\sigma^2_{t+1}$ is known
given the observations up to $t$. In your case $$r_{t+1|t} = \delta
    + \phi_1 r_t$$
The volatility forecast is $\sigma^2_{t+1|t} = \alpha_0 +
    \alpha_1 \hat{z}^2_t + \beta \sigma^2_t$ where $\hat{z}_t = r_t -
    \delta - \phi_1 r_{t-1}$, and can be obtained similarly.
Now to get $VaR$ at the moment $t+1$, given the history up to $t$, you
should just take the quantile of the standard normal, multiply it by the square root of
$\sigma^2_{t+1|t}$ and then add $r_{t+1|t}$: $$VaR = r_{t+1|t} +
    \sqrt{\sigma^2_{t+1|t}} z_\alpha$$

VaR in case of ARMA-GARCH?


Exibir todos os registros de uma coluna

Question: fiz uma query onde obtive resultado desta consulta, no entando o que preciso é este resultado exibe apenas uma linha, um único registro mas na realidade te mais de um: segue o código abaixo e por favor me mostrem onde estou errando pois não consigo ver o erro ou a falta de algum elemento..
if (empty($_POST['contrato'])) {"";}
     if(isset($_POST['contrato'])) {"";
        if($_POST['contrato'] == "") {"";}
        else{

            $cmd = "SELECT login FROM tecnicos GROUP BY Area = '%$Roteamento%' ";
            $login_tecnico = mysqli_query($conn, $cmd);

            $row = mysqli_num_rows($login_tecnico);

            if($row == " ") {" ";} else{

            while ($res = mysqli_fetch_array($login_tecnico)) {
            $tec_login = $res['login'];

exibe com sucesso a variavel tec_loogin, mas como disse este exibe apenas 1 registro quando na verdade tem mais de um, minha pergunta é como exibir todos?? help me...
Comment: Você está agrupando todos resultados com Area = Roteamento, se todos seus registros forem assim, certamente retornará um unico resultado, tente usar o WHERE
Comment: ja fiz assim, sem êxito.
Comment: apenas quero fazer uma consulta e por meio dela exibir todos os resultados da coluna entende.
Comment: você pode mostrar alguns valores que estão na coluna `Area`?
Comment: sim posso, são estas areas: AREA 05
AREA 06
AREA 24
AREA 25
AREA 30
AREA 31
AREA20
e cada area tem seu respectivo login.
Answer: Isso ta acontecendo pois a cada repetição do while, o seu código rerescreve o que está em $tec_login, por isso que só mostrará um registro. Você pode concatenar tudo nessa mesma variável ou guardar cada login em um elemento de um array:
Concatenando:
$tec_login = '';
while ($res = mysqli_fetch_array($login_tecnico)) {
            $tec_login .= $res['login'].' ';
}

Array:
$tec_login = [];
while ($res = mysqli_fetch_array($login_tecnico)) {
            $tec_login[] = $res['login'];
}

Do jeito que seu código está fazendo o while, seria a mesma coisa de, por exemplo:
$tec_login = 'valor 1';
$tec_login = 'valor 2';
$tec_login = 'valor 3';

Onde, no fim das contas, o valor da variável seria apenas 'valor3'.
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/84383/discussion-on-answer-by-tropicoder12-exibir-todos-os-registros-de-uma-coluna)

Exibir todos os registros de uma coluna


jQuery Sortable not dragging and dropping

Question: So I have the following code:

.

      a
      b
      c
      d
      e
      f
      g
      l
      r
      c
      M
      R

      0.5414001697208732
      0.6267579135019332
      0.5372867004480213
      0.28073547524400055
      0.7313777771778405
      0.6606377188581973
      0.3469888048712164
      0.3188476248178631
      0.6436003404669464
      0.928964062128216
      0.2371064145117998
      0.28258453658781946
    0.9378320435062051

      0.9801695849746466
      0.6072432077489793
      0.7846700719092041
      0.7305404511280358
      0.6679015851113945
      0.30196039425209165
      0.453620670363307
      0.7305374522693455
      0.5768151506781578
      0.13476323708891869
      0.707804215606302
      0.5663123105186969
    0.5736047253012657

      0.04010314913466573
      0.16257555224001408
      0.09655012399889529
      0.7034578064922243
      0.1477506139781326
      0.8663290378171951
      0.7496497964020818
      0.4106598789803684
      0.40226005110889673
      0.7200973171275109
      0.3833731727208942
      0.21165849990211427
    0.2390481496695429

      0.024977961787953973
      0.15549557167105377
      0.4385726018808782
      0.4258966601919383
      0.8824008668307215
      0.7984057203866541
      0.41061330679804087
      0.31520942342467606
      0.1834968824405223
      0.3562249494716525
      0.6327322069555521
      0.05667565925978124
    0.9547795762773603

      0.5718567981384695
      0.7837580549530685
      0.2138461337890476
      0.6907847372349352
      0.8337705079466105
      0.8015895446296781
      0.6213393285870552
      0.9426947564352304
      0.8353719974402338
      0.758063220884651
      0.9910459201782942
      0.7154726085718721
    0.18522482318803668

      0.554456579266116
      0.6647287227679044
      0.029392496217042208
      0.05623618420213461
      0.8104374699760228
      0.9746970348060131
      0.8055676252115518
      0.4653796493075788
      0.9834965777117759
      0.45254838350228965
      0.6599208291154355
      0.3398332125507295
    0.28924844693392515

I have a pretty complicated problem that doesn't exist if I create a static page on JsFiddle. All I am trying to do is have a table where I can move the rows around via drag and drop and edit the cells when I click on a span within a tr. The thing is within the context of my application this is not happening.  The only difference between the static page I have on JsFiddle and my actual application is that the table is served up from an ajax response. After receiving this response I do some processing(which you can see in my script). The processing includes adding the table to a container, adding a id to tbody, puts data in a span element and adds its back, and finally I have sortable instantiated. In my application my span content is editable, but I have drap and drop rows. Anyone have any idea what could be going on?
Answer: You can do this:
$('table').sortable({ items: 'tr' });

See example: http://jsfiddle.net/ddan/mekayx28/1/


Row weights on taxonomy

Question: On my live site I am unable to see the drag and drop functionality only on taxonomy, whereas it is successfully appearing on menus.Below is my screen shot for taxonomy.

It should be like this:

Can any one have idea about this?
Comment: Try enabling  `Aggregate JavaScript files` option at admin/config/development/performance. Sometimes that resolves this type of issues.
Comment: it's not an "answer", but use a different browser. I never bothered to figure out why, but sometimes Safari doesn't do the drag/drop,  but Firefox does.
Comment: no @krishna Mohan,
Comment: but on my local machine it is working
Comment: Ok thanku but not even working on another browser. Actually this problem appears only on live site on every browser. If this is the browser issue then I am unable to see this drag drop functionality on menus, but for menus on live site it is working.
Answer: Try enabling Aggregate JavaScript files option at admin/config/development/performance.
Sometimes that resolves this type of issues
Here is the screenshot

Row weights on taxonomy


Como usar o border-radius no CSS?

Question: Bom tipo eu sei como usar o border-radius mais eu vi em um site que eles usavam o border-radius: 50px / 50px tipo ele arredonda os cantos da borda e com esse segundo valor ele arrendonda tipo mais ainda na vertical mais oque quer dizer esse /
Answer: Olá, tudo bem?
A propriedade border-radius do CSS pode receber até quatro valores.
Ex:
border-radius: 15px 50px 30px 5px;

O primeiro valor aplica-se ao canto superior esquerdo, o segundo valor aplica-se ao canto superior direito, o terceiro valor aplica-se ao canto inferior direito e o quarto valor aplica-se ao canto inferior esquerdo.
Como estamos falando da "/", um valor representa o quanto vai definir horizontalmente e a outra verticalmente referente aquele canto.
border-radius: 40px / 20px;
   horizontal --^      ^-- vertical

Segue a imagem para você entender melhor:

Espero ter lhe ajudado, caso ainda houver dúvidas, segue o link para lhe ajudar melhor:
https://www.w3schools.com/csSref/css3_pr_border-radius.asp
Comment: Opa valeu broder ajudou  bastante valeu mesmo hehe

Como usar o border-radius no CSS?


Cannot install tflearn in python 3

Question: I have tensorflow 1.11.9 for python 3 and am trying to install tflearn.
I tried installation using:

"pip3 install git+https://github.com/tflearn/tflearn.git"
"pip3 install tflearn"
"pip install git+https://github.com/tflearn/tflearn.git"
"pip install git+https://github.com/tflearn/tflearn.git"

Nothing seems to work. pip install is installing a tflearn version for python 2 (I have python2.7 and 3.4 on Ubuntu 14.04), whereas pip3 is claiming that installation is successful, but I get an error saying

"No module named 'tensorflow.contrib.rnn.python.ops.core_rnn'".

Can anyone suggest what am I doing wrong? I would be happy to provide any further information that might be required. Thanks in advance.
Answer: I think your tensorflow version is probably a bit low. Current one is 1.4
Comment: I figured out that I was installing tensorflow using "sudo pip3 install --upgrade tfBinaryURL", where, tfBinaryURL identifies the proper URL of the TensorFlow Python package. Doing the tensorflow installation using "pip3 install tensorflow" and then installling tflearn using "pip3 install git+https://github.com/tflearn/tflearn.git" solves my problem.

However, I am getting another warning saying "The TensorFlow library wasn't compiled to use SSE4.1, SSE4.2 instructions, but these are available on your machine and could speed up CPU computations".

Can you please send me a link to tf 1.4?
Answer: I figured out that I was installing tensorflow using

sudo pip3 install --upgrade tfBinaryURL,

where, tfBinaryURL identifies the proper URL of the TensorFlow Python package. Doing the tensorflow installation using

pip3 install tensorflow

and then installling tflearn using

pip3 install git+github.com/tflearn/tflearn.git

solves my problem.

Cannot install tflearn in python 3