DataTable não ordena corretamente

Question: Estou usando o plugin datatables para fazer paginação de resultados em uma tabela. O problema é que a primeira coluna tem 3 datas:
26/11/2015
19/11/2015
03/12/2015

Eu preciso ordenar os resultados da dataTables com base nessas datas. O correto seria da última data (03/12/2015) até a menor (19/11/2015). Ou seja, era para estar assim:
03/12/2015
26/11/2015
19/11/2015

Tenho o código
$('#example').DataTable({
  order: [[0, 'DESC']]
});

Mas não está funcionando. Eu posso colocar DESC ou ASC, ele não ordena
Comment: Como é que está o HTML que está querendo ordenar?
Answer: Complementando a resposta do @Ricardo, o problema de ordenação no formato dd/mm/yy pode ser corrigido com o plugin Ultimate date do datatable.
Eu tinha um problema parecido como pode ser visto na imagem.

Mesmo clicando em ordenar, ele continuava fora de ordenação.
Resolução
Para resolver esse problema, como dito na referência, deve-se incluir os plugins

//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js
//cdn.datatables.net/plug-ins/1.10.10/sorting/datetime-moment.js

no cabeçalho, e em seguida, no javascript, incluir o seguinte código:
$(document).ready(function() {
        $.fn.dataTable.moment( 'DD/MM/YY HH:mm:ss' );    //Formatação
        $('#tabela').dataTable( {    //Criação da dataTable
            "order": [[ 4, "desc" ]]   //Campo ordenado por padrão (ao carregar página)
        } );
} );

Lembrando que na linha $.fn.dataTable.moment( 'DD/MM/YY HH:mm:ss' ); é o formato que a data estará visível na tabela (os campos podem ser vistos aqui) e "order": [[ 4, "desc" ]] é a coluna que deseja-se ordenar ao carregar a página (no seu caso, seria o 0).
Após essas modificações, obtive sucesso no resultado, visto na imagem

Espero que ajude.
Comment: Muito bom se ajudou e faltou verificar data pode falhar alguma linha, e necessário colocar `moment("2016-05-03T20:15:01Z").format('DD/MM/YYYY HH:mm:ss')` este exemplo para ajustar de data fica certinho. Obrigado GustavoR
Comment: Muito bom mesmo me ajudou muito, como eu deixo em português Brasil ?
Comment: Funcionou muito bem.
Answer: Acredito que o seu problema é a falta de carregamento do JavaScript do JQuery referente ao DataTable, é esse aqui: https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js
Fiz dois Fiddles para você, um sem funcionar, com o comportamento igual ao seu e um funcionando, repara que a unica diferença é que o que funciona tem esse javascript carregado.
Esse Funciona
Esse não Funciona
Repara que a coluna 3 é a data, basta no seu caso mudar para zero, não tinha o seu HTML para usar e então resolvi pegar um de exemplo. (Aqui está o link de onde peguei o código)
ATUALIZANDO
Segue o código completo funcionando no corpo do post.

$(document).ready(function() {
    $('#example').DataTable( {
        "order": [[ 3, "desc" ]]
    } );
} );

<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet"/>

                Name
                Position
                Office
                Age
                Start date
                Salary

                Name
                Position
                Office
                Age
                Start date
                Salary

                Tiger Nixon
                System Architect
                Edinburgh
                61
                2011/04/25
                $320,800

                Garrett Winters
                Accountant
                Tokyo
                63
                2011/07/25
                $170,750

                Ashton Cox
                Junior Technical Author
                San Francisco
                66
                2009/01/12
                $86,000

                Cedric Kelly
                Senior Javascript Developer
                Edinburgh
                22
                2012/03/29
                $433,060

                Airi Satou
                Accountant
                Tokyo
                33
                2008/11/28
                $162,700

                Brielle Williamson
                Integration Specialist
                New York
                61
                2012/12/02
                $372,000

                Herrod Chandler
                Sales Assistant
                San Francisco
                59
                2012/08/06
                $137,500

                Rhona Davidson
                Integration Specialist
                Tokyo
                55
                2010/10/14
                $327,900

                Colleen Hurst
                Javascript Developer
                San Francisco
                39
                2009/09/15
                $205,500

                Sonya Frost
                Software Engineer
                Edinburgh
                23
                2008/12/13
                $103,600

                Jena Gaines
                Office Manager
                London
                30
                2008/12/19
                $90,560

                Quinn Flynn
                Support Lead
                Edinburgh
                22
                2013/03/03
                $342,000

                Charde Marshall
                Regional Director
                San Francisco
                36
                2008/10/16
                $470,600

                Haley Kennedy
                Senior Marketing Designer
                London
                43
                2012/12/18
                $313,500

                Tatyana Fitzpatrick
                Regional Director
                London
                19
                2010/03/17
                $385,750

                Michael Silva
                Marketing Designer
                London
                66
                2012/11/27
                $198,500

                Paul Byrd
                Chief Financial Officer (CFO)
                New York
                64
                2010/06/09
                $725,000

                Gloria Little
                Systems Administrator
                New York
                59
                2009/04/10
                $237,500

                Bradley Greer
                Software Engineer
                London
                41
                2012/10/13
                $132,000

                Dai Rios
                Personnel Lead
                Edinburgh
                35
                2012/09/26
                $217,500

                Jenette Caldwell
                Development Lead
                New York
                30
                2011/09/03
                $345,000

                Yuri Berry
                Chief Marketing Officer (CMO)
                New York
                40
                2009/06/25
                $675,000

                Caesar Vance
                Pre-Sales Support
                New York
                21
                2011/12/12
                $106,450

                Doris Wilder
                Sales Assistant
                Sidney
                23
                2010/09/20
                $85,600

                Angelica Ramos
                Chief Executive Officer (CEO)
                London
                47
                2009/10/09
                $1,200,000

                Gavin Joyce
                Developer
                Edinburgh
                42
                2010/12/22
                $92,575

                Jennifer Chang
                Regional Director
                Singapore
                28
                2010/11/14
                $357,650

                Brenden Wagner
                Software Engineer
                San Francisco
                28
                2011/06/07
                $206,850

                Fiona Green
                Chief Operating Officer (COO)
                San Francisco
                48
                2010/03/11
                $850,000

                Shou Itou
                Regional Marketing
                Tokyo
                20
                2011/08/14
                $163,000

                Michelle House
                Integration Specialist
                Sidney
                37
                2011/06/02
                $95,400

                Suki Burks
                Developer
                London
                53
                2009/10/22
                $114,500

                Prescott Bartlett
                Technical Author
                London
                27
                2011/05/07
                $145,000

                Gavin Cortez
                Team Leader
                San Francisco
                22
                2008/10/26
                $235,500

                Martena Mccray
                Post-Sales support
                Edinburgh
                46
                2011/03/09
                $324,050

                Unity Butler
                Marketing Designer
                San Francisco
                47
                2009/12/09
                $85,675

                Howard Hatfield
                Office Manager
                San Francisco
                51
                2008/12/16
                $164,500

                Hope Fuentes
                Secretary
                San Francisco
                41
                2010/02/12
                $109,850

                Vivian Harrell
                Financial Controller
                San Francisco
                62
                2009/02/14
                $452,500

                Timothy Mooney
                Office Manager
                London
                37
                2008/12/11
                $136,200

                Jackson Bradshaw
                Director
                New York
                65
                2008/09/26
                $645,750

                Olivia Liang
                Support Engineer
                Singapore
                64
                2011/02/03
                $234,500

                Bruno Nash
                Software Engineer
                London
                38
                2011/05/03
                $163,500

                Sakura Yamamoto
                Support Engineer
                Tokyo
                37
                2009/08/19
                $139,575

                Thor Walton
                Developer
                New York
                61
                2013/08/11
                $98,540

                Finn Camacho
                Support Engineer
                San Francisco
                47
                2009/07/07
                $87,500

                Serge Baldwin
                Data Coordinator
                Singapore
                64
                2012/04/09
                $138,575

                Zenaida Frank
                Software Engineer
                New York
                63
                2010/01/04
                $125,250

                Zorita Serrano
                Software Engineer
                San Francisco
                56
                2012/06/01
                $115,000

                Jennifer Acosta
                Junior Javascript Developer
                Edinburgh
                43
                2013/02/01
                $75,650

                Cara Stevens
                Sales Assistant
                New York
                46
                2011/12/06
                $145,600

                Hermione Butler
                Regional Director
                London
                47
                2011/03/21
                $356,250

                Lael Greer
                Systems Administrator
                London
                21
                2009/02/27
                $103,500

                Jonas Alexander
                Developer
                San Francisco
                30
                2010/07/14
                $86,500

                Shad Decker
                Regional Director
                Edinburgh
                51
                2008/11/13
                $183,000

                Michael Bruce
                Javascript Developer
                Singapore
                29
                2011/06/27
                $183,000

                Donna Snider
                Customer Support
                New York
                27
                2011/01/25
                $112,000

Answer: $('#example').DataTable({
  order: [[0, 'DESC']],
 "aoColumnDefs": [ { type: 'date-uk', aTargets: [0] }]
});

tenta isso.
Comment: Não sei porque está negativa, na [documentação](//cdn.datatables.net/plug-ins/1.10.12/sorting/date-uk.js) fala sobre esse plugin apesar de estar obsoleto.
Answer: Para traduzir, use:
$('#table-clientes').DataTable({
    "language": {
        "url": "https://cdn.datatables.net/plug-ins/1.10.12/i18n/Portuguese-Brasil.json"
    }
});

DataTable não ordena corretamente


Installing Mercurial 1.5.1 on Debian Lenny

Question: What's the easiest way to install Mercurial 1.5.1 on Debian Lenny? Can I safely install the package from the sid repository using apt-get, or should I compile it from the sources?
Answer: Hmm; looks like backports.org doesn't go newer than 1.3.1 right now.
Given that, the safest approach is to build from sid's source package (so you'll still have a debian-packaged binary, just one you built yourself); see http://www.debian.org/doc/manuals/apt-howto/ch-sourcehandling.en.html for a quick primer
If you've added the sid source repository to your sources list, you might also consider using apt-get build-dep to install the build-time dependencies, and apt-get source to download and unpack the sources themselves.
Comment: Okay thanks. It sounds pretty complicated, so I think I will just stick with the 1.3.1 version from backports for now.


Is FileChannel position(long newPosition) 0-indexed?

Question: That is, if I do:
channel.position(0)
channel.read(buffer); // will read in 1st byte of file and so on

vs
channel.position(1)
channel.read(buffer); // will read in 2nd byte of file and so on

Are my assumptions correct? Reading the documentation doesn't really say anything about that so I wanted to make sure
Answer:
Is FileChannel position(long newPosition) 0-indexed?

Yes.

Reading the documentation doesn't really say anything about that so I wanted to make sure

It is clear to me.  The javadoc for position() says:

"Returns: This channel's file position, a non-negative integer counting the number of bytes from the beginning of the file to the current position".

"[A] non-negative integer" means zero or greater.  If they had meant one or greater, they would have written "a positive integer" or "a strictly positive integer".
Answer: The method is 0-indexed.
Also when you call the read method, then the file position is updated with the number of bytes actually read. The channel's position() method returns the current position.


Zabbix PDF Report Generation

Question: if any of you have an idea how to implement zabbix generate PDF reports? in forum I found some like this: https://www.zabbix.com/forum/showthread.php?t=24998 .
I try implement this to my zabbix  2.2.3 but when I do this I still see Text (Unable to login:) I guess it is a problem version. as you can see it was only tested on 1.8.8 and 1.8.10. Does anyone have some idea?

One problem fixed, is that it is failing due to API version issues, I download fresh from http://zabbixapi.confirm.ch/ and now I can generate PDF report, However, when I have select some site I see only ALL option and PDF is are empty
Below I share screen and example report: http://pl.scribd.com/doc/237807238/file-1

Anybody have some idea ?
Regards
Mick
Comment: Problem resolve. Solution in this link:

http://wikibaseofknowledge.blogspot.com/2014/09/module-to-generate-pdf-reports-in-zabbix.html
Answer: zabbix-dynamic-pdf-report
zabbix-dynamic-pdf-report module allow us to generate pdf reports. Once implemented we have options to generate reports for 'Host', 'Host Group' on time range of 'Hour', 'Day', 'Week', 'Month', 'Year'.
We can retrieve old report from 'Old Reports' section.
Implementation Dependencies

php5-curl
php5-json

sudo apt-get install php5-curl php5-json
Clone the git repo that contain the module
cd /opt/
git clone https://github.com/SandipSingh14/Zabbix_
Configure zabbix-dynamic-pdf-report according to zabbix-server
vim Zabbix_/zabbix-dynamic-pdf-report/config.inc.php
<?php
//CONFIGURABLE
# zabbix server info(user must have API access)
$z_server       = 'http://zabbix.example.com/';
$z_user      = 'admin';
$z_pass         = 'zabbix';
# Temporary directory for storing pdf data and graphs - must exist
$z_tmp_path    = './tmp';
# Directory for storing PDF reports
$pdf_report_dir    = './report';
# Root URL to reports
$pdf_report_url    = "./report";
# paper settings
$paper_format    = 'A4'; // formats supported: 4A0, 2A0, A0 -> A10, B0   -> B10, C0 -> C10, RA0 -> RA4, SRA0 -> SRA4, LETTER, LEGAL, EXECUTIVE, FOLIO
$paper_orientation = 'portrait'; // formats supported: portrait / landscape
# time zone - see http://php.net/manual/en/timezones.php
$timezone    = 'Asia/Calcutta';
# Logo used in PDF - may be empty
# TODO: Specify image size!
$pdf_logo    = './images/zabbix.png';
$company_name   = 'Zabbix';
//DO NOT CHANGE BELOW THIS LINE
$z_tmp_cookies     = "/tmp/";
$z_url_index     = $z_server ."index.php";
$z_url_graph    = $z_server ."chart2.php";
$z_url_api    = $z_server ."api_jsonrpc.php";
$z_login_data    = "name=" .$z_user ."&password=" .$z_pass ."&autologin=1&enter=Sign+in";
?>

Change directory and create directory inside zabbix-dynamic-pdf-report
cd Zabbix_/zabbix-dynamic-pdf-report
mkdir tmp report
Change zabbix auth to login method, it's required for login into zabbix server
sed -i 's,user.authenticate,user.login,g' inc/ZabbixAPI.class.php
sed -i 's,user.authenticate,user.login,g' inc/ZabbixAPI.class.php.org

Copy zabbix-dynamic-pdf-report into /usr/share/zabbix/
cp -r /opt/Zabbix_/zabbix-dynamic-pdf-report /usr/share/zabbix/

Restart apache
service apache2 restart

Procedure to Generate Reports

Open  Generate PDF Report page

http:///zabbix-dynamic-pdf-report/index.php

Once Opened you can choose report type 'HOST OR HOSTGROUP' and click the dropdown to select the hostname or hostgroup name
And you can choose report range 'LAST OR CUSTOM' and select the dropdown for the time period of report
And if you select 'custom' in report range then you can select the time period for which you want to generate the report.
And click on  'GENERATE' button and your report will be generated.
Module provides feature of old reports i.e you can see the reports you have generated earlier.
Comment: If you are linking to your own project, you need to be explicit about it. See [How to not be a spammer.](/help/promotion)

Zabbix PDF Report Generation


How can I get the full content of a PHPUnit test truncated response?

Question: I'm writing a Functional test (extending BrowserTestBase) for a Drupal REST resource.  My resource works fine in real life, but the test (running with --verbose and --debug options) throws a server error
...resulted in a '500 500 Service unavailable (with message)' response:
The website encountered an unexpected error. Please try again later.

Drupal\Component\P (truncated...)
This happens when I make the request, before I can try to catch it in an assertion.  I'm pretty sure that truncated output has the information I need to solve this, but I'm having no luck getting to it.  Drupal console docs say there's a test:run command but when I try that (v1.8.0), it tells me that's not a valid command name.  I've tried running my test through the debugger but no help there, either.
Is there any way I can get to see what's in the truncated part of the response?
Answer: My problem stemmed from trying to use GuzzleHttp to make my request, instead of BrowserTestBase::drupalGet().  I still don't know about getting to that truncated output, but using drupalGet() returns the output without truncating.


Why do tags disappear when adding '; ' to field which is combined with 'for xml path'?

Question: I want to concatenate some values from a sub-query into a string. But something happens I do not understand.
When I use this sql:
select (
    select t1.value
--       + '; '
    from Table1 t1
        join Table2 t2 on t1.xId=t2.xId and t1.TypeId in (31,33)
    where t2.pId=1001
    for xml PATH('')
)
as ValuesAsString

I get:
<value>value 1</value><value>value 2</value>

But when I remove the '--' and run the query again, the output becomes:
value 1; value 2;

Why are the xml tags removed?
I am using SQL Server 2008
Answer: Try running the inner query without the XML functionality. In the original query, it produces a result set with a single column called value, because you're directly selecting from a column called value.
In the updated query, you get a result set with a single unnamed column, because you're selecting an expression value.
So the tag names are based on the column names (or any applied aliases), and in the updated example, the column has no name. And since there's no way to have an unnamed element in XML, the element tags are omitted.
select (
    select t1.value
       + '; ' as fruitbat
    from Table1 t1
        join Table2 t2 on t1.xId=t2.xId and t1.TypeId in (31,33)
    where t2.pId=1001
    for xml PATH('')
)
as ValuesAsString

Would produce XML with your values enclosed in <fruitbat> elements.
Answer: Because the name of the column is used as the element-name in a FOR XML PATH(''). When you have a computed expression and you don't supply a column alias (... AS alias_name, or alias_name=...), a column name does not exist so no element-name is renderered (an empty XML element name is invalid).
To remove the column name, select the column as the [text()] property, like
...
select [text()]=t1.value
...

More info: 1, 2.


How to modify the background of a Tab Layout tab's text when it is focused?

Question: When I tap on a Tab Layout tab, there's the focus flash that occurs for the entire tab, except when it does, you can see a black box around the text of the tab itself. I want to get rid of that black box so that when the tab is tapped, you don't see the black box around the text from the focus flash.
Here's what I mean (print screen mid-focus flash):

I want to get rid of this black box around it. I've tried setting tabBackground, background, tabIndicatorColor to transparent, but this black box remains. Any ideas as to how I can remove the black box around the text?
Here's the XML for the TabLayout:
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    style="@style/tabStyle"
    android:layout_width="match_parent"
    app:tabBackground="@android:color/transparent"
    app:tabMaxWidth="200dp"
    app:tabMinWidth="200dp"
    app:tabSelectedTextColor="@color/textColorSelected"
    app:tabTextColor="@color/textColorNormal"
    tools:tabTextAppearance="@style/TabTextStyle">
</com.google.android.material.tabs.TabLayout>

And then the styles for both the tabs and the text inside of them:

Answer: I figured out what the issue was here; our "AppTheme" default style was declared and had a black background color set. Since the application's "AppTheme" was setting the background of the app to black overall, any other tabBackground or Background color sets I did were just overlapping the main background color designated by AppTheme. I changed the AppTheme background color to transparent, and then set the tab and background colors in the activity itself to black, and that removed the black box behind the text when a tab is selected.
Answer: You have to specify the tabBackground from the Layout (XML file) like this
app:tabBackground="@drawable/tab_color_selector"
or specify with color @color/....
Here is example look of the drawable selector
Example
<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

Comment: I have tried setting the tabBackground to transparent, as well as removing the tabBackground value entirely, and it still has the black box behind it.
Comment: Could you share your code
Comment: I just edited the original post and added the XML.
Answer:     <com.google.android.material.tabs.TabLayout
    ...>

    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_label_1"
        />

    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_label_2"
        />

    ...
</com.google.android.material.tabs.TabLayout>

Changes to tab selection can be observed like so:
  tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

    override fun onTabSelected(tab: TabLayout.Tab?) {
        // Handle tab select
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
        // Handle tab reselect
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
        // Handle tab unselect
    }
})

Implementing tabs theming
Using theme attributes and styles in res/values/styles.xml (themes all tabs and affects other components):

Comment: Is all of this really necessary in order for me to make it so that black box isn't behind the text?


Unable to setup Android Studio 3.0.1

Question: I installed Android Studio 3.0.1 and everything seemed to go as expected. When first starting up, I got to the point of downloading the SDK components, and received the following error.
"Android Support Repository, Android SDK Tools and 7 more SDK components were not installed"
Has anybody every seen this? Any ideas or suggestions are greatly appreciated.
I am using Windows 10 64 bit. I was able to capture some more details of the failure.
"java.nio.file.AccessDeniedException: C:\Users\gcleveland\Documents\Android\SDK2\extras\android\m2repository.backup.installer.installData -> C:\Users\gcleveland\Documents\Android\SDK2\extras\android\m2repository.installer.installData Warning: Failed to move original content of C:\Users\gcleveland\Documents\Android\SDK2\extras\android\m2repository back into place! It should be available at C:\Users\gcleveland\Documents\Android\SDK2\extras\android\m2repository.backup"
There are multiple other instances like this but different directories.
It is almost as if my permissions are not correct. I have full administrative rights and run android studio as an administrator.
Comment: What are you trying to install it on? Windows 10? Windows 7? Mac (version?)? A Commodore 64?
Comment: Was there an earlier line giving a reason for not installing?
Answer: I ran into similar issues with the exe file version and resolved them by instead downloading and installing the zip version of Android Studio 3.0.1 for Windows 10 (https://dl.google.com/dl/android/studio/ide-zips/220.127.116.11/android-studio-ide-171.4443003-windows.zip). After unzipping this file, I simply executed its bin/studio64.exe. I also switched my networking connection to NOT need a proxy, which may also have helped to resolve the issue.

Unable to setup Android Studio 3.0.1


Two-Way ANOVA with non-sig interaction effect: is it reasonable to argue for an interaction from simple effects?

Question: This is in the context of marking an undergraduate sociology essay in which the student has not found the predicted significant interaction effect in a Two-Way ANOVA.
The diagram below is schematic and doesn't depict the actual data. Imagine that the interaction effect is non-significant. The student has said that because the effect of task is significant in the treatment group but non-significant in the control group, there's some evidence that there really is an interaction effect.

I sense there is something fishy about this but I am struggling to come up with a precise explanation of why.
Comment: It's quite possible for the effect of task is significant in the treatment group but non-significant in the control group when there is *zero* interaction. (Consider, for example, the case where the control group is smaller.) You might get some value from [this article](http://www.stat.columbia.edu/~gelman/research/published/signif4.pdf).
Comment: Comment 1: What if the task effect had p-value 0.051 in the control group but 0.049 in the treatment group? Comment 2: One has to be careful not to interpret "interaction effect is not statistically significant" as "there is no interaction effect".
Comment: John, by itself it's not really a full answer. The difference between significance and non-significance isn't what hints there's an interaction -- as @PeterFlom suggests, a difference in effect size does. The problem is that you can't tell that possibility from what might arguably be equal population effects in the presence of sampling error (which is what the hypothesis test shows you).
Comment: Glen_b, why not expand that a bit and make it the answer?
Comment: @Glen_b is correct. Nevertheless, the student is on to something: If the *effect sizes* are different in the two groups, there is evidence of an interaction.
Answer: The student wrote

because the effect of task is significant in the treatment group but
  non-significant in the control group, there's some evidence that there
  really is an interaction effect.

By itself, this is not very good evidence of an interaction effect, for reasons others have identified:

p in treatment group could be 0.049 and in control group 0.051, this would not be evidence of anything in particular.
Similarly, the effect size could be identical and, thus, the interaction exactly 0, and yet the p could be significant in one and not in the other due to different group sizes.

What, then, would be evidence of an interaction? That depends on whether you mean an important interaction or a significant one. The two are not the same. The importance of the interaction can be seen in a plot like the one in the question (only with real data!) or by examining the effect size in each group separately, or by looking at a regression with an interaction term and seeing how big that interaction term is (not how small its p-value is). The significance of the interaction can be examined by the p-value of the interaction term in the equation.
In addition to the usual reasons for not using p-values to indicate things they don't indicate, I will note that interaction terms are notorious in that, if the main effects that go into the interaction are measured with error (as nearly everything is, but usually more so in subjects like sociology than subjects like chemistry) then the error on the interaction term is even larger.


Remover caracteres do meio de uma String

Question: Escreva um programa que, começando numa palavra definida por si, imprima no ecrã as palavras resultantes de ir retirando, um a um, os caracteres do meio da palavra anterior, até chegar a uma palavra com um só caractere. Se o número de caracteres da palavra for par, será retirado o primeiro dos dois caracteres do meio.
Exemplo: se a palavra for rapsodia, o programa deverá imprimir as palavras:

rapsodia, rapodia, rapdia, radia, raia, ria, ra e a.

Comecei por fazer o seguinte:
public class Exercicios {

    //5
    static String semLetraMeio(String s) {

        int sLength = s.length();
        while(sLength > 1) {

            int midIndex = sLength / 2;
            s = s.substring(0, midIndex).concat(s.substring(midIndex + 1, sLength));
            System.out.println(s);

        }

        return s;
    }

    public static void main(String[] args) {
        semLetraMeio("zero");

    }

}

Comment: Na minha opinião seria melhor fazer uma chamada recursiva e criar menos variáveis, como aqui:

```java
static String semLetraMeio(String s) {
    if (s != null) {
        if (s.length() == 0)
            return s;
 System.out.println(s);
 return semLetraMeio(new StringBuilder(s).deleteCharAt(s.length() % 2 == 0 ? s.length() / 2 - 1 : s.length() / 2).toString());
 }
 return s;
    }
```
Comment: @yurishimoki Não vejo porque recursão é melhor pra esse caso. Vc pode até ter criado menos variáveis, mas vai ocupar mais espaço no stack com esse monte de chamadas recursivas (talvez seja até pior que "evitar variáveis") - e fazer tudo em uma linha somente para evitar variáveis nem sempre torna o código "melhor". Variáveis não são um mal a ser evitado, vc usa quando fizer sentido e só é ruim criar variáveis que não servem para nada ou deixam o código menos claro. E eu acho que faz sentido criar uma para o índice a ser removido, por exemplo, já que é o ponto central do algoritmo :-)
Comment: Neste caso:
`static String semLetraMeio(String s) {
    if (s != null) {
      if (s.length() == 0)
        return s;
      while (s.length() > 0) {
        System.out.println(s);
        s = new StringBuilder(s)
        .deleteCharAt(s.length() % 2 == 0 ? s.length() / 2 - 1 : s.length() / 2)
        .toString());
      }
    return s;
    }
  return s;
}`
Comment: Só que como Strings são imutáveis, isso seria melhor: `static String semLetraMeio(String s) {
    if (s != null) {
      if (s.length() == 0)
        return s;
      StringBuilder sb = new StringBuilder(s);
      while (sb.length() > 0) {
        System.out.println(sb);
        sb.deleteCharAt(sb.length() % 2 == 0 ? sb.length() / 2 - 1 : sb.length() / 2);
      }
    return sb.toString();
    }
  return s;
}`
Answer: O problema é que você calcula o tamanho da String somente no começo, antes do while. Mas depois da primeira iteração, a String terá um caractere a menos, e aí você vai tentar pegar uma substring até sLength, que agora é maior do que o tamanho da String (afinal, você retirou um caractere), e isso causará um StringIndexOutOfBoundsException. E mesmo que esse erro não ocorresse, o programa entraria em loop infinito, afinal sLength nunca é atualizado no while.
Então uma solução seria atualizar o tamanho da String a cada iteração. Outro detalhe é que quando o tamanho da String é par, você está pegando o segundo caractere do meio, então tem que ser feito um ajuste para este caso:
static void semLetraMeio(String s) {
    System.out.println(s);
    int sLength = s.length();
    while (sLength > 1) {
        int midIndex = sLength / 2;
        if (sLength % 2 == 0) { // ajuste para quando o tamanho é par
            midIndex--;
        }
        s = s.substring(0, midIndex).concat(s.substring(midIndex + 1, sLength));
        System.out.println(s);
        sLength = s.length();
    }
}

Outro detalhe é que eu mudei o retorno do método para void, pois não parece fazer sentido ele retornar alguma coisa (ele vai retornar a última substring encontrada). Bom, se achar que faz sentido, é só colocar de volta o return e o retorno do método para String.
Também coloquei um println no início para imprimir a String original. Chamando semLetraMeio("rapsodia"), a saída é:
rapsodia
rapodia
rapdia
radia
raia
ria
ra
a

Outra alternativa é usar um StringBuilder, que possui o método deleteCharAt, que serve justamente para apagar um caractere em determinada posição:
static void semLetraMeio(String s) {
    System.out.println(s);
    StringBuilder sb = new StringBuilder(s);
    while (sb.length() > 0) {
        int midIndex = sb.length() / 2;
        if (sb.length() % 2 == 0) {
            midIndex--;
        }
        sb.deleteCharAt(midIndex);
        System.out.println(sb);
    }
}

Se quiser que o método retorne uma String, como o seu código original faz, mude para:
static String semLetraMeio(String s) {
    System.out.println(s);
    StringBuilder sb = new StringBuilder(s);
    while (sb.length() > 0) {
        int midIndex = sb.length() / 2;
        if (sb.length() % 2 == 0) {
            midIndex--;
        }
        sb.deleteCharAt(midIndex);
        System.out.println(sb);
    }
    return sb.toString();
}

Answer: Sua lógica está certa, apenas esqueceu de alguns detalhes:
public class Main {
   // ja que a função apenas printa as Strings não há necessidade de retornos
   static void semLetraMeio(String s) {
        int sLength = s.length();
        while(sLength > 1) {
          int midIndex = (sLength - 1) / 2; // vc deve diminuir 1 no length para pegar o primeiro char do meio caso o numero seja par
          s = s.substring(0, midIndex).concat(s.substring(midIndex + 1));
          sLength = s.length(); // vc tbm esqueceu de definir o novo tamanho da string, causando um loop infinto
          System.out.println(s);
        }
    }

    public static void main(String[] args) {
      semLetraMeio("rapsodia");
    }
}


Fast octaves on the piano

Question: I'm working on the piano accompaniment to Schubert's "Trockne Blumen" variations for flute and piano.  Variation 2 is all sixteenth-note octaves in the left hand.  I began by practicing very slowly with the metronome and gradually increased the tempo over several weeks up to a quarter note = 80.  This is fast enough for the performance (which will be in two months) but it is still tiring, and the octaves still sound like I'm struggling with them.  (On recordings, professional pianists play them quite smoothly at 96.)
Do you have any tips for practicing these?
Comment: Another example is Scriabin's first sonata, third movement.
Comment: Just to be clear, do you mean playing both octaves at once or switching back and forth? I thought you meant switching back and forth, but Babu seems to think it is both at once and now that I look at it I don't know what to think.
Comment: Two notes at the same time, an octave apart.  Other famous pieces with fast octaves are Chopin's Polonaise in A-Flat (middle section) and Liszt's Funerailles.
Comment: The score on IMSLP shows 32nd notes...!
Answer: I have been learning "Rage Over A Lost Penny", and there is a part about one third in where the left hand quickly plays in 16th notes at about the same tempo the fingers are 2,1,5,1,2,1,5,1 and is supposed to seamlessly change the notes that 5 plays each time. Then I play 5,1,2,1,5,1,2,1 and about 6 more variations seamlessly with only two short pauses.
Here is what I have figured on my own after 6 months of practice and I have about got it mastered.

Vary your tempo during practice: Practice slow and steady, as well as at tempo (even if it sounds bad). Switch back and forth. (Your brain can get a better idea what is going on if you play slow once in a while)
When performing, you might be able to cheat the tempo: It is possible to gradually speed up or slow down the song to accommodate your skill, as long as it sounds like part of the effect. Make sure it sounds like part of the effect, if the real purpose occurs to one of the audience, it may be a distraction, and if change in tempo only happens in one place, there could be a problem and if the audience has heard the song before there could be a problem. On the other side, if done right, a tempo change can be refreshing. I currently practice tempo changes temporarily for Rage Over a Lost Penny, until I sound good with the correct speed. In this case, I cut the tempo in half for a certain part, which does not mess with the beat (Actually, this is just before I move into a transition to the first section so I can make an end about half way, I am not yet able to play the whole thing). Also, in The Entertainer, I have (don't anymore), slowed down the song when playing the first section the third time, that way I can preserve the slower tempo for the second half. This does not work for every song. (Perhaps see below comments that object to this suggestion)
Interesting case from a well known composer:
Michele McLaughlin has a song called So Long Mr. Selfish, and she has composed in an alternating octave similar to what you have described, in her CD, she plays it surprisingly inconsistent, although it does not sound like a struggle to me. This however is not written out as 16th notes, but rather as a Tremolo between two whole notes an octave apart.

Now that I know you mean both notes at once, the answer mostly applies, but whatever you do, do not sound like you are struggling. :) Anything to make it sound natural.
Comment: I'd strongly caution against cheating the tempo.  Most of the time it does not work and is noticed.  Especially the suggested 25%+, that would be impossible to hide.
Comment: Downvote removed, but my caution is still stronger than yours.  In my experience a "layperson" audience may not know exactly what's wrong, but they still know it just doesn't sound right.
Comment: @Matthew: After this explanation, I am thinking that paragraph needs to be re-written to state it right. The fact that I understated the caveat in the first place is an example of the disadvantages of doing without a teacher and also an example of why I wanted this site so much. I will bookmark this and rewrite the paragraph when I have time.
Comment: @Matthew: [See my edit here](http://music.stackexchange.com/posts/161/revisions). I know this answer is still against the grain, but if you think it is good enough you can remove the down vote.
Answer: When I play octaves, I do my best to separate the up and down motion of the wrist from the lateral motion of the arm.  The nice bit of isolating the motion is that it helps in keeping a relaxed grip.  It also makes it easy to practice fast octaves away from the piano (it's your wrist moving up and down rapidly).  To build endurance, just practice the up and down wrist motion while you're waiting for something to happen.  Granted, slapping your leg rapidly while you're waiting for a train is......an odd thing to do, but it does help you build endurance in otherwise dead time.
Comment: +1 for isolating the motion to practice elsewhere. I practice _rasgueados_ when emptying sugar packets.
Answer: You must find a fingering that lets the outside bit of your hand play a legato-compatible fingering (i.e. 4-5-4-5-5-4-5-5), even if you don't play legato. This keeps you hand from freezing up and lets you work toward relaxing the rest of the mechanism more.
Answer: Sounds like you have a workable solution for this particular performance. For future pieces, playing octave scales as part of your daily regimen of exercises will help you approach octave passagework as something more normal. While playing octave scales, keep your hand open and loose, not clawlike or tense, with just enough support in the fingers and palm muscles to bounce off the keyboard like you're dribbling a basketball with your thumb and pinky. Listen for a strong and even sound. Stay at a tempo that is manageable without panic or tension (that tempo will increase as you become more accustomed to octave scales.) Do major, minor, and chromatic scales.
Comment: I tend to tense up and sort of lock myself in octave position when I see a passage with a lot of octaves, be it alternating and legato or static and staccato, more so with the static octaves. I then move my wrist up and release when the octaves end. With the moonlight sonata, this is no big deal because of the slow tempo. But when I play the Liszt transcription of Beethoven's 5th symphony, that 120 bpm Allegro is enough to get noticeable tension. I can't imagine being able to play Chopin's Octave Etude if I noticeably tense up with eighth note octaves at Allegro.

Fast octaves on the piano


Design patterns: many objects of same type with multiple objects of other type

Question: Which would be a good approach if I were to make an application where I had to store all countries in Europe and as well as their respective cities (for example)?
I considered using an enum to store the information but since that'd require me to hard-code lots of data I quickly scrapped that idea.
Afterwards I considered something like:
class Country {

    public Country(String name, City... cities) {
        //Stuff
    }
}

That way I'd be able to read cities from a .txt and create objects accordingly thus eliminating the need for manual labor. However, that brings a new issue, where do I store my list of countries? I considered the following:
class Country {

    public Country(String name, City... cities) {
        //Stuff
    }

    public static List<Country> getAllCountries() {
        return countries;
    }
}

but I feel like such code pollutes the structure and cleanliness of the project.
I thought about going with a combination of an enum (Country) and a class (City) but that doesn't feel right either.
Ideally I'd like to be able to access countries like an enum Country.FRANCE or Country.getByName("France") but neither seems like a solution here. So, I'm back to my initial question. What is a good way to go about doing this?
Answer: The list of cities is big and it's quite possible that you'll need more than just a name for a country or a city. Storing this information in file for regular use is impractical and definitely enumerations are not for that. Instead, you could use a database, which you can populate with the Geonames data. The Geonames database contains the information about locations of cities and much more else. You can use ISO 3166-1 alpha-2 codes to identify countries and Geoname IDs to reference cities in the country. There are also localized names of the countries, if you want to present the list of countries in different languages.
This data can be downloaded from here (description is below):
http://download.geonames.org/export/dump/
You can easily find the code for importing the files into your database of choice in Github - there are many examples for doing just that.
With the database your code could look like this:
class CountryRepository {
    public Country findByISOCode(String code) { ... }
    public List<Country> findAll() {
       // JDBC or JPA query
    }
}

class SomeBusinessLogic {
    private CountryRepository countries;
    private CityRepository cities;
    ...
    Country france = countries.findByISOCode("FR");
    List<City> largestFrenchCities = cities.findTopLargestIn(france, 5);
}

Comment: Thanks for your reply! I should probably have clarified this in the OP but country/city is merely an example of the problem. Generally speaking I guess it's kind of like a x-to-many parent/child relationship? In your example, if you didn't query a database, how would you initialize the country list?
Comment: Without context your question becomes too abstract to answer. It always depends on the domain, which solution to choose. How many objects are there? Will they change during application lifetime? Are there any other relationships between these objects and other domain entities? What is the execution environment and what options do you have there?
Answer: You could use a HashMap. This is a storage for a key and value pair.
It could look like this :
HashMap<Country, City> europe = new HashMap<Country, City>();


What is the effect of preserving Angular Router query parameters?

Question: Per this article with Angular it's possible to preserve query parameters like this:
goUsers() {
  this.router.navigate(['/users'], { queryParamsHandling: 'preserve'
   });
}

I'm looking for a practical examples that shows why we might want to do this?
Comment: You could for example implement filtering and memorize it with query-params. If you didn't preserve query params, they'd get lost on re-route.
Comment: I'm not sure what memorize it with query parameters means?  A practical example would go a long way here.
Answer: If you look into the definition for queryParamsHandling (not much is given there), it is to handle next navigation.
The practical example would be if you want to make your app stateless. So it will help you no to maintain the selections made on web page to be maintained. For example on shopping or travelling site, they store the choices selected in query parameters as even site goes down or you reload the page the choices selected still persist.
Second would be easier bookmarking so when you bookmark the page with given selections, you can easily open it next time or even forward this link to anyone without specifying the selections that you choose for the result.
For client-side application, its a good way to store state at given pageview and when you move forward or backward in browser history your selection will persist. It will be helpful for user as each time they don't have to update their choices.
Comment: Are you able to illustrate with some hello world like code that illustrates what happens over a sequence of events?
Comment: For example the article navigates to users and sets query params handling to to preserve, but it's still not clear to me what effect this has ... in other words what the difference between preserve or no preserve ...
Comment: in article an example is given how to do that if you are moving across pages or maybe on user page based on previous page action you want to display additional info on user profile. For second Q, if you don't put the preserve the params will lost on subsequent navigation action ( as mentioned in article only). It depends if you want to use selections of this page on other page.
Answer: Suppose you are at:
http://localhost:4200/heros?hero=jack

And you want to move to the crisis center but keep jack as the hero, so that you can match jack up to a crisis.
goCrises() {
  this.router.navigate(['/crises-center'], { queryParamsHandling: 'preserve'
  });
}

This changes the URL to http://localhost:4200/crises-center?hero=jack and that component can retrieve the hero parameter via ActivateRoute and match up the hero to a crises.
Answer: I'm using this to preserve the lang queryparam.
According to Google's guidelines, one url must match a specific content. So storing the language in localStorage is not recommended.


jquery link css class change

Question: I have the following main menu:

Home

About

Features

Contact

Support

I would like to add a css class "selected" to a link when the link is clicked and remove the css class from all other links in the . This is to mark the page that the user has clicked to open.
Perhaps this can be done in a way where jquery reads the current path when the page loads and adds the css class to the corresponding menu link tag?
Thank you
Comment: Are you using AJAX to load the content? If not, this would be rather pointless.
Comment: No, it is an ASP.NET MVC view layout page. Like a Master page. And the main menu is there.
Answer: CSS-Tricks Snippet
Let's say you have navigation like this:

Home

About

Clients

Contact Us

And you are at the URL:
http://yoursite.com/about/team/
And you want the About link to get a class of "active" so you can visually indicate it's the active navigation
$(function() {
  $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});

Essentially that will match links in the nav who's href attribute begins with "/about" (or whatever the secondary directory happens to be).
Further reading...
Comment: putting $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active'); in the $(document).ready(function () did the trick. thank you very much
Answer: A bit late to the party but try this out for size...
It compares the href attribute of each anchor element to the current window location for your navigation structure given above.
$('.ddsmoothmenu > ul#nav > li').each(function() {
    var $this = $(this),
        $link = $this.children('a'),
        path = $link.attr('href');

    if (path == document.location.pathname) {
        $this.addClass('selected');
    }
});

Can be seen in action on JSFiddle: http://jsfiddle.net/LdQft/
Answer: Try this
$('div#smoothmenu').on('click', 'a', function(e){
  $(this).addClass('Selected').siblings('a').removeClass('Selected');
});

jquery link css class change


Sonicwall firewalls and redundancy of route based vpns

Question: I am attempting to configure a route based vpn on a Sonicwall TZ device.
The datacenter has two public IPs on different subnets (A and B).  The remote office has 1 public ip (C).
When I configure two tunnels from the datacenter firewall to the remote office (A to C as well as B to C), one of them always fails, most likely due to the same terminating IP address (C) at the remote site.
Sonicwall documentation states that this should be feasible but their tech support is unable to figure out how to get it to work.
Does anyone have experience configuring redundancy using sonicwall route based vpns?
Answer: We have this same problem between an NSA3500 and TZ215. Let me know if you make any headway. I have logged a case with Sonicwall Tech support (useless) and they mention it is not possible to have multiple SA's for the same remote gateway even if the local endpoints are different.


Why does this Pi approximation become less accurate?

Question: The code included below calculates a pi approximation in Java using a Monte Carlo method. As expected, the answer (very) gradually improves, but when the main loop terminates the answer is always worse than the results during the run. Why?
import java.util.*;
import java.math.*;
import java.text.*;

public class PiMonte
{
  private static final int MAX_PTS = 500000;

  private static final BigDecimal BD100 = BigDecimal.valueOf(100);
  private static final BigDecimal BD10 = BigDecimal.valueOf(10);
  private static final BigDecimal BD4 = BigDecimal.valueOf(4);

  private static final BigDecimal PI = BigDecimal.valueOf(Math.PI);

  public static void main(String[] args)
  {
    Random rand = new Random();

    BigDecimal circlePts = BigDecimal.ZERO;
    BigDecimal totalPts = BigDecimal.ZERO;
    BigDecimal piEstimate = BigDecimal.ZERO;

    BigDecimal err = BigDecimal.ZERO;
    BigDecimal eps = BigDecimal.valueOf(100);  // percentage

    MathContext mc = new MathContext(20);

    System.out.println("Math.PI: \t" + Math.PI);
    System.out.println("PI Estimation");

    for (int i = 0; i < MAX_PTS; i++) {
      double x = rand.nextDouble()*2-1;  // in the range [-1,1]
      double y = rand.nextDouble()*2-1;

      if ((x*x + y*y) <= 1)  // inside circle
        circlePts = circlePts.add(BigDecimal.ONE);
      totalPts = totalPts.add(BigDecimal.ONE);

      piEstimate = circlePts.multiply(BD4).divide(totalPts, mc);
      err = piEstimate.subtract(PI).multiply(BD100).divide(PI, mc).abs();

      if (err.compareTo(eps) < 0) {
        System.out.println(" Step " + i + ": \t" + piEstimate +
                               " < " + eps + "%; " + format(err) + "%");
        eps = eps.divide(BD10);
      }
    }

    System.out.println("\nEnd " + MAX_PTS + ": \t" + piEstimate +
                                           " and " + format(err) + "%");

  } /* main */

  public static String format(BigDecimal num)
  {
    DecimalFormat df = new java.text.DecimalFormat("0.##########");
    return df.format(num);
  }

}

The originally code used doubles, and displayed the same problem, which I thought was due to rounding. That's why I rewrote the code using BigDecimals. I've run the program with many different stopping values for MAX_PTS, and the accuracy of the calculation varies (as you'd expect). What surprises me is how poor the final result is; always a lot less accurate than the best results during execution. The following output illustrates my point:
> java PiMonte
Math.PI:        3.141592653589793
PI Estimation
 Step 2:        1.3333333333333333333 < 100%; 57.5586818422%
 Step 20:       2.8571428571428571429 < 10%; 9.0543182332%
 Step 107:      3.1111111111111111111 < 1%; 0.9702576317%
 Step 111:      3.1428571428571428571 < 0.1%; 0.0402499435%
 Step 190:      3.1413612565445026178 < 0.01%; 0.0073655967%
 Step 1327:     3.1415662650602409639 < 0.001%; 0.000839973%
 Step 24174:    3.1415925542916235781 < 0.0001%; 0.0000031608%
 Step 87878:    3.1415924168458903720 < 0.00001%; 0.0000075358%
 Step 186181:   3.1415926351634422232 < 0.000001%; 0.0000005865%

End 500000:     3.143968 and 0.0756096245%

In response to the comments, I increased MAX_PTS to 500000000 and ran the code again. Typical output was:
Math.PI:        3.141592653589793
PI Estimation
 Step 0:        4 < 100%; 27.3239544735%
 Step 83:       3.4285714285714285714 < 10%; 9.1348181202%
 Step 157:      3.1645569620253164557 < 1%; 0.7309766404%
 Step 158:      3.1446540880503144654 < 0.1%; 0.0974484855%
 Step 274:      3.1418181818181818182 < 0.01%; 0.0071787865%
 Step 5740:     3.1416129594147361087 < 0.001%; 0.0006463545%
 Step 45269:    3.1415948751932847360 < 0.0001%; 0.0000707158%
 Step 71415:    3.1415929203539823009 < 0.00001%; 0.0000084914%
 Step 131051:   3.1415926502457039954 < 0.000001%; 0.0000001064%
 Step 131955:   3.1415926520961532632 < 1E-7%; 0.0000000475%
 Step 4182829:  3.1415926537774664521 < 1E-8%; 0.000000006%
 Step 47075584:         3.1415926536016493475 < 1E-9%; 0.0000000004%
 Step 196187169:        3.1415926535868782857 < 1E-10%; 0.0000000001%
 Step 345802403:        3.1415926535895337500 < 1E-11%; 0%

End 500000000:  3.141660976 and 0.0021747699%

The error seems to converge on an average of 0.002%. I'd like to understand why that is.
Here's a plot of err*10000 vs the number of iterations. Each point is recorded every 10,000 steps up to 500 M.
Comment: Not only is `Math.PI` a `double`, `rand.nextDouble()` and the entire circle calculation is done with `double` precision too. So it's pointless to pretend a higher accuracy by using `BigDecimal` *afterwards*.
Comment: For one thing, `Math.PI` is a double, so it is an approximation and the BigDecimal could get closer. I'm not sure if that is the case. Another thing, you only print out on certain loops when err < eps.  If you were to plot it you probably find the err isn't decreasing monotonically, but is fluctuating around some value that is decreasing.
Comment: How do you determine that your "calculation result is accurate during execution"? How can you even claim that after [admitting that it is not](https://stackoverflow.com/questions/75885245/why-does-this-pi-approximation-become-less-accurate#comment133852437_75885463)?
Comment: You are not "accurate in the sense of being close to Java's value for PI". You already admitted that you get the same graph as shown in the answer, just wiggling up and down rather than converging. Some values happening to be closer to `Math.PI` than others is not a prove for accuracy. That's just chance. I could take arbitrary random numbers between three and four and some of them will happen to be closer to PI. I could even get exactly PI by chance. Repeated evaluation will only converge as much as the actual random number generator and the accuracy of the calculation allow.
Comment: I think, the biggest problem here is that you are citing the "law of large numbers" while 500,000 is not a large number at all. It easily fits into an `int` counter, as demonstrated by your `for` loop. As said, your use of `BigDecimal` is a big distraction. You are as close as one can expect after only 500,000 iterations. You have the wrong expectation because *some* error values happened to be smaller. Talk again about "large numbers" after checking 500,000,000 and 500,000,000,000 iterations (note that even that number doesn't require `BigDecimal`, optimize the loop to reduce waiting time).
Comment: I don't think that's the problem since the random numbers are only being used to increment counters. Also, the calculation result is accurate *during* execution, but disappointing at the end.
Comment: Accurate in the sense of being close to Java's value for PI.
Comment: Referring to user16320675: doesn't Monte Carlo rely on the law of large numbers, which means that the piEstimate value will always move towards the 'correct' answer (barring rounding errors)?
Comment: You should be able to estimate the expected variance of the prediction based on the number of samples taken. Any particular measurement doesn't change, but if you took an ensemble of measurements, then you should see a decrease in average error with an increase in N. Also, this technique creates a biased random walk with a step size of 1/N. Which means the value can get stuck far away from the actual value.
Answer: The error isn't decreasing monotonically. It should be decreasing on average though.
Here is the error for a sample run.

If you zoom in.

You should be able to estimate the variance after N steps. You're essentially taking a random walk with a step size of 1/N. One way to improve the accuracy is to compare the values of different simulation runs.

That image shows the average error and the std deviation of the error from the value obtained with ensemble of 10 simulations.

That is the zoomed in version. You can see the variance decreases with more steps. But, the actual error for any given simulation might not be less. It could be though.
This way also helps you see how accurate your estimate is. In your example you know Math.PI, but if you were to do use this technique to solve something you don't know, then sampling an ensemble of simulation runs shows the value converge to an average value.
Comment: From the looks of it, I feel like the estimate has sort of almost stabilised after some point. Perhaps it's just that the rate of the convergence is slower the longer you do this?
Comment: I added some plotting code that added the piEstimate value to a graph every 10,000 steps, and obtained a graph similar to yours. I continued the graph up to 5 million, and the estimate didn't improve at all. The error seems to converge to a value and stays there.
Comment: Sorry I meant to say the err value. I plot err*10000 against steps.
Answer: In your for loop you only report these steps where err is smaller than eps but in many cases this is not the case. In the end you just report the final step. Here, also err is not smaller than eps, hence the worse approximation.
Comment: As I mentioned in the comments above, my code uses the Monte Carlo method which relies on the law of large numbers. In particular, that means that the piEstimate value will always move towards the 'correct' answer (barring rounding errors).
Answer: My thanks to everyone for helping me to understand what was going on. As Holger pointed out, my printing of piEstimate during the execution is not very useful since these are just random values that happen to be close to pi. I should have focused instead on how the error value decreases over time, which brings those random values on average closer to the true value of pi. matt's suggestion of plotting the err value was crucial.
Due to the central limit theorem, the standard error will decrease proportional to 1/sqrt(N), with N being the sample size. This can be seen in action in my final example when N = 500 M. The standard error will be around 0.00005, which implies 4 dp's of accuracy in the final result.
Reducing standard error (aka Variance reduction) is an important aspect of Monte Carlo simulation;
e.g see https://en.wikipedia.org/wiki/Variance_reduction


.htaccess redirection with multiple rules

Question: Basically what I want to do is :
1) redirect any .html request to .php page.
2) if any 404 happens , then it should redirect to www.domain.com
3) domain.com should be redirected to www.domain.com
4) www.domain.com/index.html should redirect to www.domain.com
Here is my htaccess code
RewriteEngine On
RewriteRule ^(.*)\.html$ $1.php [L]

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^fr/(.)*$ / [R=301,NC,L]  # Added line
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . http://www.domsdain.com/index.php [L]
</IfModule>

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteRule ^(.*)index\.(php|html?)$ /$1 [R=301,NC,L]

With above code 4th rule (www.domain.com/index.html should redirect to www.domain.com) is not working
Answer: You can refactor to use these rules:
ErrorDocument 404 http://www.examle.com/
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+index\.(?:php|html) [NC]
RewriteRule ^ http://www.examle.com/ [L,R=301]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

RewriteRule ^(.+)\.html$ $1.php [L,NC]

RewriteRule ^fr/(.)*$ / [R=301,NC,L]

Make sure to clear your browser cache or use a new browser for testing.


iPhone opengl ES copy framebuffer into the renderbuffer

Question: Hy folks,
I'm working on an animation in opengl es. The animation should draw squares. This works already, but how can I copy the content from the Framebuffer into the renderbuffer, the problem is that with every frame only one square is on the display.
When I tested it in the simulator and it worked. With every new frame a knew square is drawn and the others that have been drawn already are still on the screen. But when I tested it on the device it didn't worked. The screen was just blinking.
I think this happens because my mac like every other computer is using doublebuffering and the iPhone dosen't.
Please help me.
This is  how I'm setting up my Framebuffer:
<code>- (BOOL)createFramebuffer {

    glGenFramebuffersOES(1, &viewFramebuffer);
    glGenRenderbuffersOES(1, &viewRenderbuffer);

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);

    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
    if (USE_DEPTH_BUFFER) {
            glGenRenderbuffersOES(1, &depthRenderbuffer);
            glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
            glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
            glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
        }

        if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
            NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
            return NO;
        }

        return YES;
    }
</code>
I also wrote a setupView Methode:
<code>- (void)setupView {
    glClearColor(0.0f, 0.0f, 0.0f, 0.5f);               // Black Background
    //  glEnable(GL_DEPTH_TEST);                            // Enables Depth Testing
    //  glDepthFunc(GL_LEQUAL);                             // The Type Of Depth Testing To Do
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  // Really Nice Perspective Calculations

    glViewport(0,0,backingWidth,backingHeight);                     // Reset The Current Viewport

    glMatrixMode(GL_PROJECTION);                        // Select The Projection Matrix
    glLoadIdentity();                                   // Reset The Projection Matrix

    // Calculate The Aspect Ratio Of The Window
    gluPerspective(45.0f,(GLfloat)backingWidth/(GLfloat)backingHeight,0.1f,100.0f);

    glMatrixMode(GL_MODELVIEW);                         // Select The Modelview Matrix

    isSetUp = YES;

}
</code>
This is my drawView Methode:
const GLfloat squareVertices[] = {
        -1.0f,  1.0f,   0.0f,
        1.0f,   1.0f,   0.0f,
        1.0f,   -1.0f,  0.0f,
        -1.0f,  -1.0f,  0.0f
    };
<code>[EAGLContext setCurrentContext:context];

if (!isSetUp) {
    [self setupView];
}

glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);

//glClear(GL_COLOR_BUFFER_BIT);

//////////////////////Variablen
float xg = -26;
float yg = 35.5;
float z = -100.0;

float abstandXg = 3.0;
float abstandYg = 3.0;

for (int i = 0; i < 26; i++) {
    //arrayKoordinatenY[j] = y - abstandY * (j);
    for (int j = 0; j<=17; j++) {

        // glLoadIdentity();
        //arrayKoordinatenX[i] = x + abstandX * (i);
        //glTranslatef(arrayKoordinatenX[j],arrayKoordinatenY[i],z);

        glTranslatef(xg,yg,z);

        glEnableClientState(GL_VERTEX_ARRAY);

        glColor4f(0.0f,0.0f,0.0f,0.0f);
        glVertexPointer(3, GL_FLOAT, 0, squareVertices);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

        arrayKoordinatenX[j]=xg;
        xg = xg + abstandXg;

    }
    xg = -26.0;

    arrayKoordinatenY[i]=yg;
    yg = yg - abstandYg;
}
//// Here comes the Part where the squares are draw
.
.
.
/////
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];
}
</code>
Comment: Post your rendering code
Comment: Do you mean the drawView Methode??
Comment: why are you calling lBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context presentRenderbuffer:GL_RENDERBUFFER_OES]; twice?
Comment: oh thanks for the advice, but i have a newer version of this code i posted the wrong one i will edit the question sorry...
Answer: <code>glMatrixMode(GL_PROJECTION);                        // Select The Projection Matrix
glLoadIdentity();
</code>
OK - but where is the same thing for GL_MODELVIEW ?
Comment: In the setupView Method or do you mean something else ?
Comment: you must load identity every time you render a frame (for model and projection matrices).
Comment: So you mean I should write it like this ??

`glMatrixMode(GL_PROJECTION);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();`
Comment: no. you should write glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity();
Comment: ok thanks for your really fast answer =D. It works in the simulator. I have to wait until tomorrow to test it on the device. Thank you very much.
Comment: I have only one more question. With this changes the old squares will be drawn in also in the next frame ??
Comment: So the main idea is: before drawing the next frame you clear the working space (buffers) and you reset all transformations (by loading identity matrices to GL_MODELVIEW and GL_PROJECTION). After this you have clear space to present the next frame (in the end it is just an image). So answering you question: only things that you tell OpenGL to draw are drawn + that is left from the previous frame (if you clear it, then nothing is left).
Comment: Ok and now I don't need to use `glClear(GL_COLOR_BUFFER_BIT);` to rest the whole buffer ?? because glClear fixed the blinking problem, the renderbuffer was flashing every time a new frame was displayed on the screen
Comment: It was probably flashing cause you didn't specify the color. You have to call glClearColor(0.6f, 0.6f, 0.6f, 1.0f); before glClear(GL_COLOR_BUFFER_BIT);


O Java não está dividindo uma String corretamente

Question: Estou tentando dividir uma String usando o seguinte caractere "|"
Mas o java está entendedo que é para dividir letra por letra.
        List<Curso> cursos = new ArrayList<Curso>();
        List<String> pacotes = Arrays.asList("Criança-1,2,3-1,00|Preparatório Primeiro Emprego-4,5,6,7,8,9-139,99".split("|"));
    System.out.println(pacotes.toString()); //I/System.out: [, C, r, i, a, n, ç, a, -, 1, ,, 2, ,, 3, -, 1, ,, 0, 0, |, P, r, e, p, a, r, a, t, ó, r, i, o,  , P, r, i, m, e, i, r, o,  , E, m, p, r, e, g, o, -, 4, ,, 5, ,, 6, ,, 7, ,, 8, ,, 9, -, 1, 3, 9, ,, 9, 9]

Alguém pode me ajudar?
Answer: O pipe "|" é um caractere especial do regex. Sendo assim, você deve escapá-lo:
split("\\|");

Comment: Obrigado Amigo!


VMware CPU Hyper Threading Scheduling Affinity

Question: I have looked everyware and read a bunch of documentation on this but haven't found a direct answer so here it goes:
There is a setting in the "Resources" Tab in vCenter that lets you configure Hyper-threading Core Sharing. I have this set to "ANY".
My question is with Scheduling Affinity. What happens if I leave the text field blank where you would assign specific cores?
Does VMWare handle the hyper-threading across all logical cores or does this disable hyper-threading?
Note: the Scheduling Affinity Group Box says

hyperthreading status: active
  available CPUs: ## (Logical CPUs)
Comment: This is a bit of an [*X-Y Problem*](http://xyproblem.info) question, since your real goal is to comply with Adobe ColdFusion licensing. What have you purchased license-wise, and what is the configuration of your ESXi host hardware?
Comment: The configuration for HT on the Physical Host is Enabled, Logical Processors are 40. CF requires the count of all logical processors per VM when HT is used. I need to identify that HT is being utilized on the VM. It seams to me that HT is infact being used on the VM but is not configuraed with granularity as the "Scheduling Affinity" is blank. So all logical cores are shared in my configuration and this sharing is managed by VMWare, does that sound like a true statement in my case?
Comment: How many cores is CF licensed for?
Comment: I'm working through that with a Adobe rep to make sure our environment is true.
Comment: @Everyone. I appreciate everyone's input, they are all good answers. I am going to mark one correct because it defines it for me. The fact that Hyper Sharing and Scheduling Affinity were called out as separate items lead me to find that my initial understanding was correct. I found from a verbal source that; If HT is enabled at the global level, no affinity is assigned and hyper sharing is set to any at the VM level, then all logical cores are used.
Answer: The UI may be confusing here, but Hyperthreaded Core Sharing and the Scheduling Affinity are separate items.

Hyper threading Sharing is just finer control over the HT options.
The Scheduling Affinity dialog displays Hyperthreading status (which is controlled at the hardware BIOS level) and then allows you to specify taskset-style CPU affinity masks.

Hyperthreading Sharing
The options are:
Any – (default) The virtual CPUs of this virtual machine can freely
  share cores with other virtual CPUs of this or other virtual machines.
None – The virtual CPUs of this virtual machine have exclusive use of
  a processor core whenever they are scheduled to it. The other
  hyperthread of the core is "halted" while this virtual machine is
  using the core.
Internal – On a virtual machine with exactly two
  virtual processors, the two virtual processors are allowed to share
  one physical core (at the discretion of the ESXi scheduler), but this
  virtual machine never shares a core with any other virtual machine. If
  this virtual machine has any other number of processors than two, this
  setting is the same as the None setting.

In either case, I don't recommend changing any of these settings in 99% of use cases as you run the risk of performance problems or increased contention. The Scheduling Affinity box should be blank.
Is there a particular effect or situation you're trying to deal with?

I just checked the language of the Adobe ColdFusion license. For your use case, "CPU" means physical socket (which may be multi-core). The licenses are sold in 2-CPU quantities. So you need one license per dual-socket ESXi host.
Comment: I need to determine the logical cores used for HT per VM for licensing purposes. Since HT is enabled at the Host level (on the physical ESXi box) and is enabled in the VM settings then HT is active and being used across all VM's using the number of logical cpus define in scheduling affinity, Correct?
Comment: VMware Licensing is based on no. of CPUs, not based on cores or logical cores.
Comment: @Amir, I don't think he's worried about vSphere licensing, but rather a virtualized application which has licensing restrictions.
Comment: @MikeMyers: Yes, that's right.
Comment: @MikeMyers What application? More detail is always better.
Comment: I am working with ColdFusion licensing which is based off of # of pCPU, pCores, vCPU, vCores, logical processors etc.
Answer: The default for all virtual machines on a hyperthreaded system is ANY. The virtual CPUs of a virtual machine with this setting can freely share cores with other virtual CPUs from this or any other virtual machine at any time.
Changing this settings can cause performance issues and you won't really be using the benefits of it.
Also, Hyperthreading depends on processor type and is enabled in System bios.
Comment: so i can expect that if i have 40 logical processors that all 40 are used in hyper threading if mode = any and scheduled affinity is left blank. Correct?
Answer: The activation of Hyperthreading is set at the host level, but the decision of whether or not a given VM uses HT is set at the VM level.
As such, leaving the Scheduling Affinity box blank won't have any effect if Hyper-threading Core Sharing is set to ANY.
Comment: So are you saying then that hyperthreading is not being used with the VM if affinity is blank? This is where my confusion is.
Comment: I'm saying that having HT enabled is a seperate issue altogether from those settings. HT is set globally at the host level, and each VM on that node can be configured what to do with the threads as you want. So, in your case, HT is enabled (based on the `hyperthreading status: active` bit of your post), and the VM in question is going to `freely share cores with other virtual CPUs of this or other virtual machines`.


Confidence Interval for Regression Line (simple linear regression)

Question: So I've constructed a confidence interval for my regression line. However, because I have 2500 data points it is a very, very narrow interval (I can barely see it next to the regression line when I make it a 99% interval). I've also been reading similar questions but I just can't get a basic understanding of what this confidence interval means.
Here are my thoughts..
I think it is saying that if I draw another 2500 sample that I can be 99% sure the new estimated regression line will lie within this C.I? Or, in other words, I could draw 100 more samples, fit them and expect only 1 out of the 100 estimated regression lines would violate these new CI. I notice it widens at each end of the graph which would allow a new line to pivot properly if a slightly different coefficient was estimated so that sort of makes sense.
Please let me know what you think I would really appreciate it!
Comment: None of those interpretations is correct.  It would help to review what a confidence interval is (actually, it's a *confidence region* in this case).  Consider looking at some of our [top-rated threads on this topic](http://stats.stackexchange.com/questions/tagged/confidence-interval?sort=votes&pageSize=30).
Answer: You are partially correct about the interpretation of confidence interval. It tells about the population parameter (as opposed to sample statistic) which in your case is regression coefficient of the entire population. A confidence interval is a range of values, derived from sample statistics, that is likely to contain the value of an unknown population parameter such as mean and regression coefficient. Because of their random nature, it is unlikely that two samples from a given population will yield identical confidence intervals. But if you repeated your sample many times, a certain percentage of the resulting confidence intervals would contain the unknown population parameter. The percentage of these confidence intervals that contain the parameter is the confidence level of the interval.
A $99\%$ confidence interval indicates that $99$ out of $100$ from the same population will confidence intervals that contain the population parameter. To make the idea clearer consider this: As the sample size increases, the sampling error decreases and the intervals become narrower. If you could increase the sample size to equal the population, there would be no sampling error. In this case, the confidence interval would have a width of zero and be equal to the true population parameter.Copied from here.
Comment: So this is for the confidence interval for the entire regression line? the one with this formula on slide 5/17 http://www2.stat.duke.edu/~tjl13/s101/slides/unit6lec3H.pdf
Comment: Yes, this equation computes the _lower bound_ and _upper bound_ of regression coefficient, $\beta_i$. It indicates that the true population $\beta_i$ lies between the lower and upper bounds $99\%$ of the time in your case.


Gibbs sampling: Conjugate prior for a two component known-unknown variance?

Question: If I have a normally distributed variable $\mathcal{N}(\mu,\frac{1}{\tau})$ with fixed $\mu$ then the conjugate prior for an unknown $\tau$ is then $\mathcal{Ga}(\frac{n}{2}+\alpha, \beta + \sum_i \frac{(x_i - \mu)^2}{2})$.
If my precision is instead $\tau = \frac{1}{\sigma_a^2 + \sigma_b^2}$, where $\sigma_a^2$ is known and $\sigma_b^2$ is unknown, is there a form of the conjugate prior for $\sigma_a^2$?
It seems as though this should be simple but I have struggled with it. The application of this is to sample $\sigma_b^2$ in a Gibbs sampler.
Comment: Not every distribution has a conjugate prior. First you need to know it exists before you talk about a form for it.
Comment: In your first sentence you appear to be showing the formula for the posterior but you're calling it a prior (it has data in it!).
Answer: Since $\tau = \frac{1}{\sigma_a^2 + \sigma_b^2}$ is in one-to-one correspondence with $\sigma_a^2$, setting a prior on $\tau$ is equivalent to setting a prior on $\sigma^2_a$. The Gamma prior of $\tau$ continues to be conjugate in this setting, except that it is now restricted to $(0,\tau_a^{-2})$.


How to flip a Path element horizontally

Question: I have this <Path> element in a xaml file. I would like to create a copy and flip it horizontally so that the shape will point in the other direction. The <Path> has a really long Data field so I was wondering if there was a way to flip one of the  elements instead of just eyeballing the element and manually making it appear the same shape and size.
I looked into flipping the image programatically using RenderTransform and ScaleTransform, but I am afraid it might hinder the performance of the application especially during a window resize.
References: https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/transforms-overview

Is there a protocol or way I can translate the Path element's Data
  field into its horizontally flipped opposite in a way that wonder hurt
  the performance of the application?
Comment: You can also explicitly assign a PathGeometry to the Data property, and set the PathGeometry's Transform property.
Comment: @Clemens would it be much different than the accepted answer? In terms of performance would it be the same?
Comment: There wouldn't be any noticable difference. I've just mentioned it in case you couldn't set RenderTransform for some reason. E.g. because it's already used for some other purpose. Or you later decide to stretch the Path, but don't want to also stretch its stroke.
Answer: If you want to mirror the shape you might want to try this:
<Path data= "...">
  <Path.RenderTransform>
     <ScaleTransform ScaleX="-1.0"/>
  </Path.RenderTransform>
</Path>

This doesn't really hurt the performance, since all rendered elements are transformed at some point anyway.
Comment: And it's worth adding that to *any* visual element in WPF can have a RenderTransform.

How to flip a Path element horizontally


Setting cross domain cookie with AJAX

Question: Let's say I have domain a.com and b.com, and I own both domains. There's a page on b.com called setcookie.aspx and in the server code, it sets a cookie under the b.com domain.
I want to make an HTTP get request to b.com/setcookie.aspx from a.com (b.com is already allowing CORS requests from a.com) like so:
$.get('http://www.b.com/setcookie.aspx');
For some reason, the cookie is not being set. However, if I put the URL in a hidden image tag:

Then it works. Any idea why the AJAX request doesn't set the cookie?
Comment: `$.get` uses `XMLHttpRequest` - read the documentation regarding cookies [here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) - `XmlHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values` - so, you need to set the jQuery equivalent of `withCredentials` - note, you'll need jQuery 1.5.1+ for this to work - and you probably wont be able to use `$.get` - use `$.ajax` instead
Comment: @JaromandaX actually newer versions allow passing a settings object to the shorthand methods like `$.get` and `$.post` ... but agree is just as easy to use `$.ajax`
Comment: @charlietfl - I must've missed that in the documentation!
Comment: Setting withCredentials to true worked, thanks :)
Answer: You need to make 2 changes.
On a.com
As pointed out by @Jaromanda X in the comments, you need to set withCredentials=true in your $.get request. Cross-domain cookies are not allowed to be set by browsers unless you do this. Read this XMLHttpRequest.withCredentials
On b.com
When a cookie is to be set from the server side, it will send a header of the form:

set-cookie: key=val; expires=Fri, 24-Jan-20 10:29:58 GMT; path=/; domain=example.com; HttpOnly; SameSite=Lax

Notice the SameSite=Lax flag. This prevents the browser from setting cookie across domains.

From the Mozilla Set-Cookie docs
Asserts that a cookie must not be sent with cross-origin requests,
providing some protection against cross-site request forgery attacks

You need to disable this flag. This will depend on your backend platform. I use Django and for me it was just changing 1 setting SESSION_COOKIE_SAMESITE. This allows me to set the session id cookie to be set via a cross-domain AJAX request.
Once you do these 2 changes, the cross-domain cookie will be set. However, make sure to have enough CORS and CSRF checks to ensure the request comes from trusted origins.

Setting cross domain cookie with AJAX


Dynamic Time Warping to find distance in stochastic way

Question: Is there a formulation of DTW that allows to deal with uncertainty or to utilize knowledge of the probabilistic structure of the signal? I would like to have a formulation similar to HMM but stay in DTW paradigm.
Why do I need that? I have several examples of a time series pattern that I want to find in the data. The amount of examples is not enough to build a complex model (e.g. HMM). On the other hand, I would like to leverage all the examples given at once and not use these examples one after another. I am wondering if there is DTW formulation that allows to account for that.
Answer: If you want to "leverage all the examples given at once", then you can optimally average all the patterns [a] into a single template and use that.
However, you should not do that if the patterns are polymorphic.
A good resource for DTW is [b]
[a] http://www.cs.ucr.edu/~eamonn/ICDM_2014_DTW_average.pdf
[b] http://www.cs.unm.edu/~mueen/DTW.pdf
Comment: Yes, I would like  "leverage all the examples given at once" but averaging might be too risky, since yes, template are similar but sometimes might have high variation. So, I am searching for a method that would provide me some uncertainty on every points when performring DTW.


What is the meaning of saying following: Let $P$ be a finitely presented $A[X]$ module. Suppose $P$ is extended from $A$?

Question: What is the meaning of saying following:

Let $P$ be a finitely presented $A[X]$ module. Suppose $P$ is extended from $A$?

I've not seen the above terminology.Could anyone please explain?
Comment: Please, add some more context.
Comment: @egreg: Please see Theorem $1$ [here](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/7680E36F104BCD582614B7F401C22365/S1865243313000172a.pdf/quillens_solution_of_serres_problem.pdf)
Comment: Maybe you have access to the full text; not everybody has.
Comment: @egreg: Oh i see,btw the title of the paper is "Quillen's solution of Serre's problem"
Answer: This means $P$ is obtained from some $A$-module  by extension of scalars, i.e. there exists an $A$-module $M$ such that
$$P\simeq M\otimes_A A[X]\enspace\text{as $A[X]$-modules.}$$
Comment: Is it somehow related with projective modules?
Comment: Not  directly. Do you have something in mind?
Comment: Not really,i was asking because the above terminology is used is a paper  titled "Quille's solution of Serre's problem" and the aim of the paper is to prove that projective modules over polynomial rings are free.
Comment: I see: Quillen-Suslin's theorem, which proves Serre's conjecture (acttually one of Serre's conjectures).  This notion (a module being obtained by extension of scalars) is a general concept useful in many situations.
Comment: Sorry did you mean that it is more general than projective modules?
Comment: It's another notion. Neither more nor less general.


Write the definition of prime number using symbols and no words

Question: I'm trying to write the definition of prime numbers using only symbols.
Here is what I have:
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.
Note:
N$^{*}$ is the set of all natural numbers except for $0$.
So the set of prime numbers is S = {x $\in$ N$^{*}$, x $\neq$ 1 $|$ ... [I'm stuck here]}
I don't know how to explain. I was just introduced to proofs and sets so I do not want to use complex symbols. Can someone suggest me a simple way for the "such that" part, please?
Thank you!
Comment: Consider this: $x\gt1$ $\land\, \forall a,b\in\mathbb N^*$, $ab=x\implies a=x\lor b=x$
Comment: Or $p\mid ab \Longrightarrow p\mid a \vee p\mid b$.
Answer: $$S = \{ x \in \mathbb{N}, x \neq 1 | \forall p,q \in \mathbb{N},\  pq=x \implies p,q \in \{1, x\} \}$$


Angular 2 - Remove non essential files from QuickStart seed

Question: Following the setup guide here and trying to delete non-essentials files from QuickStart seed. It says to run the following commands on Mac:
xargs -a non-essential-files.txt rm -rf
rm app/*.spec*.ts
rm non-essential-files.txt

The first command doesn't work. Looks like xargs on Mac doesn't have -a option.
What is the equivalent to the first command on Mac?
Answer: I'm not seeing a -a option as well, that's strange.
Just copy & paste this (it's just a concat list of all those files) to remove everything:
rm -rf .git .gitignore .travis.yml *.spec*.ts CHANGELOG.md e2e favicon.ico karma.conf.js karma-test-shim.js LICENSE non-essential-files.txt protractor.config.js README.md app/*.spec*.ts non-essential-files.txt

Comment: Yeah, Linux `xargs` has `-a` option, but OSX `xargs` doesn't. Thanks for providing the command, but actually I want to know how to delete a list of files from a text list.
Answer: xargs rm -rf < non-essential-files.txt

Should work.


C++ async + future (deferred vs async)

Question: This is the test program that I am working with.  Can someone please describe in detail what is happening and the reason for this output?
Why does launch::async get the value of g_num as 0, while launch::deferred gets 100?
Both launch::async and launch::deferred got correct values of arg that is on the main stack, which I believe means they should have both gotten 100.
The code:
#include <iostream>
#include <future>
using namespace std;

thread_local int g_num;

int read_it(int x) {
    return g_num + x;
}

int main()
{
    g_num = 100;

    int arg = 1;
    future<int> fut = async(launch::deferred, read_it, arg);
    arg = 2;
    future<int> fut2 = async(launch::async, read_it, arg);

    cout << "Defer: " << fut.get() << endl;
    cout << "Async: " << fut2.get() << endl;

    return 0;
}

The output:
Defer: 101
Async: 2

Comment: Try without `thread_local`.
Answer: The documentation states that launch::deferred will invoke the function on the calling thread, while launch::async will invoke the function on a new thread.
For the calling thread, the value of g_num is whatever you set it to in main. For a new thread, the value is value-initialized (0 for int) since you never set it. Thanks @MilesBudnek for the correction.
Comment: @Seoul: Yes. This is what the `thread_local` qualifier is *for*. Each thread has its own *completely independent* object.
Comment: IIRC, globals (including `thread_local` ones) get value-initialized, so the value of `g_num` is well-defined in the worker thread, it's just `0`.
Comment: @merlin2011 So when a new thread is created under, does it look for all `thread_local` variables and set them to default values even when the `thread_local` variable is altered before the new thread is spawned?
Answer: g_num is define as thread_local this means every thread in your app has its own copy of g_num
launch::deferred runs on the calling thread. g_num on the main thread was changed to 100. It was not changed on the thread that was launched with launch::async which is the reason its value was still the default one.

C++ async + future (deferred vs async)


Ignoring all lint errors and warnings in Android

Question: Is it Ok to ignore lint errors and warnings given by lint if my projects runs perfectly with no errors in my emulator?
I'm asking this because I would like tu publish my app to the store (my first android app) and I'm not sure if this will cause any shut downs or any other errors...
Answer: If you understand the warning well enough, and are sure that it is not going to affect the App's behavior (maybe in other devices), you can go for it.
For example even if you know, tell other-developers by comments, maybe in root build.gradle file, like:
android {
    lintOptions {
        // TODO: remove below once we have time to update entire logic.
        disable 'some_warning_id'
    }
}

But, If you are not sure then certainly you should fix all the lint warnings. Lint error/warnings are very basic for android apps.
Answer: @AnkitSomani's answer says the important things: think about warnings first.
If you want to ignore them, lint can be told to ignore warnings by several methods (document is way longer)

With annotations:
@SuppressLint("NewApi")
public void onGlobalLayout() {

In .xml files:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    ....
    <LinearLayout
        tools:ignore="MergeRootFrame"

java comments:
//noinspection AndroidLintSdCardPath

xml comments:

In Build File: With Gradle Configuration
android {
    lintOptions {
        disable 'TypographyFractions','TypographyQuotes'
        ...
    }
}

on the command line
$ lint --disable MissingTranslation,UnusedIds,Usability:Icons /src/astrid/

config file 'lint.xml' (next to 'AndroidManifest.xml')
<?xml version="1.0" encoding="UTF-8"?>
<lint>

    <issue id="ObsoleteLayoutParam">
        <ignore path="res/layout/activation.xml" />
        <ignore path="res/layout-xlarge/activation.xml" />
    </issue>
</lint>

Android Studio
To suppress an error, open the issue in the editor and run the
  quickfix/intentions action (Ctrl/Cmd F1) and select Suppress which
  will use annotations, attributes or comments to disable the issue.
Answer: There are various levels of Lint errors, as long as they are showing as warnings - the yellow mark - and not errors - the red ones - you are good.
The linter basically just helps you avoid common mistakes - forgetting .show(), or not specifying a default orientation for a LinearLayout.
If the app works, it works. Go for it.
Answer: You can but you definitely should not. Those warnings are here to help you avoid common mistakes which lead to poor code quality.
Especially as a beginner, the lint warnings are good to follow.
Some warning can't be avoided sometimes, but at least you should check them and put a specific annotation on it.
Most importantly, understand the warning and be aware of the consequences of not taking care of it.


nginx redirect what is not coming from load balancing

Question: I have nginx on SERVER1 that is acting as load balancing between SERVER1 and SERVER2
in SERVER1 I have the upstream for the load balancing defined as :
upstream server
    # SELF SERVER1 [localhost]
    server 127.0.0.1:8082 weight=3 max_fails=3 fail_timeout=2;
    # other SERVER2
    server otherserverip:8082 max_fails=3 fail_timeout=2;
}

The load balancing config on SERVER1 is this one:
server {
    listen   80;
    server_name ~^(de|es|fr)\.server\.com;
    location / {
        proxy_pass   http://server;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

        # trying to pass a variable in the header to SERVER2
        proxy_set_header        Is-From-Load-Balancer 1;
    }
}

Then in SERVER2 I have:
server {
    listen   8082;
    server_name localhost;
    root   /var/www/server.com/public;
    # test output values
    add_header testloadbalancer $http_is_from_load_balancer;
    add_header testloadbalancer2 not_load_bal;

    ## other stuff here to process the request
}

I can see the "testloadbalancer" in the response header is set to 1 when the request is coming from the load balancing, it is not present when from a direct access: SERVER2:8082 .
I would like to bounce back to the SERVER1 all the direct requests that are sent to SERVER2, but keep the ones from the load balancing. So this should forbid direct access to SERVER2:8082 and redirect to SERVER1:80 .
Answer: I managed to find a working solution by following the examples here on multiple if conditions in nginx [ http://rosslawley.co.uk/2010/01/nginx-how-to-multiple-if-statements/ ] :
in SERVER2
server {
  listen   8082;
  server_name localhost;
  root   /var/www/server.com/public;

  set $is_load_balancer FALSE;
  if ( $http_is_from_load_balancer ) {
    set $is_load_balancer TRUE;
  }

  if ( $is_load_balancer = FALSE )  {
    # here you redirect to the server.com
    # so this will be processed again by the load balancing
    rewrite ^ http://server.com$request_uri? permanent;
  }
}