Configuring htaccess/mod_rewrite to serve static files with question mark in the URL

Question: I've just taken on hosting of an ancient site that was converted from asp to static html, consisting of about 6,000 files. However, my server doesn't like the filenames, giving a 404 error. The URLs are all of the form:
filename.asp?id=123&a=something.html

where id is always an integer and a is always a string of characters & numbers.
Is there any way I can use htaccess and mod_rewrite to tell it that the question mark is part of the URL rather than signifying a query string?
Comment: Using the `?` to separate arguments from the URI is the default behavior.  How do you have apache configured now?  And does `filename.asp` exist in the directory you're shooting for?
Comment: Apache is configured pretty much out of the box excerpt for performance changes. But as i've got multiple sites on the server i can't change it server-wide, so I'd be looking to do something via htaccess.
Answer: You probably already know you are not the first person to have this need :)
# Allow filenames containing '?' to be served by escaping the '?' in the HTTP
# request so it's not interpreted as a query string.
#
# Apache 2.2: set query string to empty by ending rewritten path with '?'.
# Apache 2.4: use the qsdiscard flag instead
#
RewriteCond %{QUERY_STRING} !=""
RewriteRule ^/(.*) /$1\%3F%{QUERY_STRING}? [noescape,last,redirect]

The key is the combination of adding a redirect and NE/noescape to ensure apache doesn't escape what we don't want escaped.
The above rule will mean that the entire site under this rewrite will treat ? as part of the filename. If you need to have it match your filename.asp - just add it to the RewriteRule
Answer: I would suggest a rewrite that directly serve the file, by escaping the "?" to "\%F3".
To serve files:
RewriteCond %{QUERY_STRING} !=""
RewriteRule ^(.*)$ $1\%3F%{QUERY_STRING}? [L]

Do the same for folders (i.e. serve index.html - adapt index.html to fit your needs)
RewriteCond %{REQUEST_FILENAME} ^.*/$
RewriteCond %{QUERY_STRING} !=""
RewriteRule ^(.*)/$ $1/index.html\%3F%{QUERY_STRING}? [L]

First, we test if the file exists (see next paragraph about this), second we check that we have a query string (otherwise, serve the file as usual), then add the "?" and the original query string and serve it.
I add the "?" at the end, to erase the QueryString (since it is already handled), and to avoid the rule to be applied a second time (ex: if serving a file in a subdirectory). Other solution would be to use the "END" flag (see http://httpd.apache.org/docs/current/en/mod/mod_rewrite.html#rewriterule). According to the same page, and as mentionned by @csharkey and @Gavin C, [qsdiscard] could be added instead in apache 2.4:
RewriteRule ^(.*)/$ $1/index.html\%3F%{QUERY_STRING}? [L,qsdiscard]

Caveat: I didn't test this solution thouroughly, so errors may remains.
Answer: I have converted an ancient Joomla site with wget --mirror. In my case all the links went through the index.php file, so all of them are something like site.com/index.php?blabla=haha.
I have resolved the problem by adding an index.php file with the following content:
<?php

include 'index.php?' . $_SERVER['QUERY_STRING'];

This way you don't even need the rewrite module. Obviously it performs slightly worse, and maybe it's less elegant, but at least you don't have to convert link/filenames.


firebaserecycleradapter() in firebaserecycleradapter cannot be applied to

Question: The same error keeps coming up. I'm guessing they changed how it works now but since I'm a noob, I really need help fixing it.
    private void loadMenu() {
        adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>
            (Category.class, R.layout.menu_item, MenuViewHolder.class, category) {

            @NonNull
            @Override
            public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return null;
            }

            @Override
            protected void onBindViewHolder(@NonNull MenuViewHolder viewHolder, int position, @NonNull Category model) {
                viewHolder.txtMenuName.setText(model.getNama());
                Picasso.get().load(model.getImage()).into(viewHolder.imageView);
                final Category clickItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        //get Category Id and Send to new Activity
                        Intent foodlist = new Intent(Home.this, FoodList.class);
                        foodlist.putExtra("CategoryId",adapter.getRef(position).getKey());
                        startActivity(foodlist);
                    }
                });
            }

"(Category.class, R.layout.menu_item, MenuViewHolder.class, category)" This line is in red and it states that FirebaseRecyclerAdapter() in FirebaseRecyclerAdapter cannot be applied to (a bunch of code here).
Answer: The FirebaseRecyclerAdapter binds a Query to a RecyclerView. When data is added, removed, or changed these updates are automatically applied to your UI in real time.
First, configure the adapter by building FirebaseRecyclerOptions:
 FirebaseRecyclerOptions<Category> options =
                new FirebaseRecyclerOptions.Builder<Category>()
                        .setQuery(category, Category.class)
                        .build();

Next create the FirebaseRecyclerAdapter object. You should already have a ViewHolder subclass for displaying each item.
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {
    @Override
    public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Create a new instance of the ViewHolder, in this case we are using a custom
        // layout called R.layout.menu_item for each item
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.menu_item, parent, false);

        return new MenuViewHolder(view);
    }

    @Override
    protected void onBindViewHolder(MenuViewHolder holder, int position, Category model) {
        // Bind the Chat object to the ChatHolder
        // ...
    }
};

You can find more information here:
https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md#firebaseui-for-realtime-database


Detectar se uma determinada página é aberta dentro de um IFRAME

Question: Gostaria de saber se é possível detectar a seguinte situação:

Temos uma intranet (de uma diretoria) que é carregada através de um dado endereço: http:intr.abcdabcd.abc.br
Temos uma INTRANET global, dentro da primeira página da intranet Global, a intranet da DIRETORIA é carregada dentro um IFRAME (então o atributo SRC desse IFRAME é >> "http:intr.abcdabcd.abc.br"

Questão, é possível, dentro da página que responde pelo endereço "http:intr.abcdabcd.abc.br" eu detectar que "estou sendo" aberta dentro de um IFRAME?
Objetivo, caso eu detecte que estou sendo aberta dentro de um IFRAME ajustar a apresentação.
Atenciosamente,
Answer: você pode tentar acessar window.frameElement, caso frameElement seja nulo, é por que você não está dentro de um iFrame.
Comment: Só faltou um exemplozinho :)
Answer: Tem sim, você pode fazer como expliquei em JavaScript - Diferença entre this e self, então dentro da página que possivelmente pode ser chamada dentro do iframe adicione isto:
if (window.top !== window.self) {
    alert('Esta página foi provavelmente chamada dentro de um iframe');
} else {
    alert('Esta página foi aberta diretamente na aba/janela');
}

O que cada propriedade faz:

window.self retorna o objeto da janela atual
window.top retorna o objeto da janela acima de todas, por exemplo se uma página tiver um iframe chamado #frame1 e este iframe tiver outro iframe chamado #frame2, então em #frame2 usar window.top ele irá retornar o objeto página que embarcou o #frame1

Você também pode querer checar se o domínio for o mesmo que o seu domínio então não ocorre a função, por exemplo:
if (window.top.location.host !== window.location.host) {
    alert('Sua página foi embarcada por um dominio diferente');
} else if (window.top !== window.self) {
    alert('sua página foi provavelmente embarcada por uma página do mesmo dominio');
} else {
    alert('Esta página foi aberta diretamente na aba/janela');
}

Redirecionando
Se você deseja redirecionar para o seu próprio site você pode usar .location = ... ou .location.replace(...), a diferença entre ambos é que location.replace vai substituir a página atual, fazendo com que a página que tinha iframe não fique disponível no back e forward, o que pode ser mais interessante, exemplo:
if (window.top !== window.self) {
    alert('Este site não permite enquadramentos (frame), você esta sendo redirecionado'); //Mensagem opicional
    window.top.location.replace(window.self.location.href);
}

X-Frame-Options
No entanto um coisa interessante que você pode usar para impedir o embed (se for o que deseja) é usar o header X-Frame-Options, que pode ser adicionado via linguagem server-side ou até via .htaccess, web.config, etc. Existem 3 valores possíveis:

X-Frame-Options: DENY
Impede o embed usando frame ou iframe de qualquer site, até mesmo o próprio site
X-Frame-Options: SAMEORIGIN
Impede que site com domínios diferentes do seu embarquem sua(s) página(s), mas se for o mesmo domínio então poderá embarcar
X-Frame-Options: ALLOW-FROM https://sitepermitido.com/
Permite um site especifico embarcar sua(s) página(s).

Exemplos com SAMEORIGIN:

.htaccess:
Header add X-Frame-Options "SAMEORIGIN"

web.config (o ... é para indiciar que pode adicionar mais configurações):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
       <httpProtocol>
            <customHeaders>
                <add name="X-Frame-Options" value="SAMEORIGIN" />
                ...
            </customHeaders>
        </httpProtocol>
        ...
    </system.webServer>
</configuration>

nginx.conf:
location pasta_especifica {
     add_header X-Frame-Options SAMEORIGIN;
}

PHP:
<?php
header('X-Frame-Options: SAMEORIGIN');

asp.net (em c#, creio que não seja muito diferente se escrito em vb.net)
Response.AppendHeader("X-Frame-Options", "SAMEORIGIN");

Answer: Acredito que você possa utilizar a propriedade parent (A reference to the parent of the current window or subframe.), e ate mesmo ser mais especifico como pegando o endereço da janela que contem o iframe.
parent.location.href

Para mais informações você pode utilizar o link abaixo.
https://developer.mozilla.org/en-US/docs/Web/API/Window/parent


Why does the pedal sign look like "Leo"?

Question:
I play piano. I took Trinity College London grade 6 practical and finished my theory course. I still don't understand why the Pedal sign looks like the word "Leo". Could someone tell me why "Leo"?
Comment: Thanks for that. I'm now never going to be able to un-see it...
Comment: When I was a child I believed that those signs were pictures of dogs. My mother played the piano and I asked her why there were all these dogs.
Comment: For centuries before computers and fonts, people would write by hand using crude devices to transfer some type of ink or mark to a substrate like paper.  Letters had a wide variety of shapes and styles, depending on the period and whose hand was doing the writing.  As a matter of tradition, musical scores adopt modern fonts that replicate these older styles of hand-written text.
Comment: I suspect the underlying question for this post is actually "Why does the Ped. sign still look like 'Leo' even though that probably impedes readability?"
Comment: I always saw it as a reference to Led Zeppelin.
Comment: Does this answer your question? [What does this indication mean?](https://music.stackexchange.com/questions/30539/what-does-this-indication-mean)
Comment: @LarsPeterSchultz We thought alike about "Ped" = "small dog". See my comment on [this answer](https://music.stackexchange.com/a/111756/70803)
Comment: I always thought of it as "Led".
Answer: As already mentioned,

it's "Ped." in a funny font.

Once you know it, I guess you can't unsee it.
The font "French Script" has a similar small letter D:

The font "Monotype C" has a similar capital letter P with the uncommon "leg":

It's even more pronounced in "Vivaldi":

But, usually, Ped. is modelled as a single glyph like in Bravura:
Comment: Add on to the single glyph info: this is Unicode 1d1ae MUSICAL SYMBOL PEDAL MARK :  https://unicode.org/charts/PDF/U1D100.pdf
Answer: It's "Ped." in a funny font.
Comment: @Aaron ... and what about the period behind its tail? Ah, I don't wanna know exactly.
Comment: @ojs Whoosh! :)
Comment: I've always seen it as a small dog. The "d" is the tail.
Comment: The period is there to show that it's an abbreviation. For the font: https://en.wikipedia.org/wiki/Blackletter
Comment: @EricDuminil The body of the "d" is the dog's back haunch; the bend in the "L" is the forepaw, and the loops at the top of the "L" are nose and ear.
Comment: @EricDuminil You got it. Glad I could add this important element to your life. :-)
Comment: @ojs in none of the lettering styles I found on that page does the upper case _P_ have a stroke that causes it to resemble an upper case _L._
Comment: "Funny"   Generations of Germans and Goths take exception!
Comment: @phoog you're right, adding lines to join letters is a feature of many handwritten scripts but not any of the blackletter styles. I'm not going to track down the exact style that's used here.
Comment: @Aaron It's not a dog. It's a lion!
Comment: @CarlWitthoft I meant no offense!
Comment: @user1079505   no worries; just a joke
Comment: @Aaron: I somehow cannot see any small dog. Could you please describe it a bit more?
Comment: @Aaron thanks. The head is towards the right, right? I think I see it now.
Comment: @Aaron I think you mean P instead of L.
Comment: @rexkogitans "Ped", "Leo", who can tell...? (Oops.)
Answer: David Rowland, the author of "A History of Pianoforte Pedaling" (Cambridge University Press, 1993), suggests the script "Ped" mark may have emerged in the late 1830s with the publisher Breitkopf & Co. This is based on early Chopin editions found at the Chopin Variorum. He further proposes that Breitkopf might have received new engraving punches around that time, with other publishers following suit.1

Some further hunting...
The first of Breitkopf's Chopin publications to use the script "Ped." (also the first to use the "snowflake" for pedal release) is the Ballade in F Minor, Op. 52, published in 1843. (The French first edition of the same piece, published by Schlesinger, contains a block "Ped.")

(IMAGE SOURCE)
Also in 1843, Schlesinger published Chopin's Impromptu in Gb Major, Op. 51. It contains a block "Ped.", though it does include a snowflakey pedal release indicator.

(IMAGE SOURCE)
The prior publications, the Fantasie Op. 49 (Breitkopf, 1841; shown below) and the Mazurkas Op. 50 (Schlesinger, 1842), use the block "Ped".

(IMAGE SOURCE)

1 Email with Prof. Rowland. Reproduced here by his permission.
Answer:
Could someone tell me what this is supposed to mean?

As you already know, it means Ped.

I still don't understand why the Pedal sign looks like the word "Leo".

Because the glyph for the "P" is made look similar to an "L", and the "d" is styled like an "o" with a tail on it. So while it means "Ped.", it seems to some people to look like "Leo`".

Why does the pedal sign look like “Leo”?


Find if the drupal node is published or not published in node_save()

Question: I am trying to find if the user has set the node to be published when creating a node. Upon hitting save, the call to node_save() is done; I tried to call print_r($node), but nothing seems to show up in the data which relates to the publishing status of the node.
How would I find out if the node is set to be published? Is there a way I can find out if an alias is set?
Answer: You are looking for $node->status. The Node module defines two constants which you can use instead of 0/1 to make your code more readable:
/**
 * Node is not published.
 */
define('NODE_NOT_PUBLISHED', 0);

/**
 * Node is published.
 */
define('NODE_PUBLISHED', 1);

Example:
if ($node->status == NODE_PUBLISHED) {
  // Node is published.
}

Note that you should not alter node_save(). Instead, implement hook_nodeapi() to do something either before ($op is "presave") or after ($op is "insert"/"update") the node is saved.
Comment: Question is tagged for Drupal 6.
Comment: Ah, overlooked that. Updated accordingly.


Another Undefined Index (this one's defined though)

Question: Alright, PHP is throwing this error (in the log) and it's quite detrimental to the application.
PHP Notice:  Undefined index: sessid in methods.php on line 7

Yes, I'm aware of what this error means, what I cannot figure out is why it's obviously defined and saying it's undefined. Here is the relevant code in methods.php
$sessid = mysql_real_escape_string($_REQUEST['sessid']);

Now before you go off and say that "NO IT'S UNDEFINED!!!", here is the POST request to the methods.php (and yes, I'm also aware that $_REQUEST "can't be trusted").
method=r&room=general&sessid=d0sma94yw4r4cdckv2ufhb&qid=1276957562382

As you can see, the sessid is obviously defined and is being sent off to the methods.php. I just thought I'd throw in the relevant query here too.
mysql_query('UPDATE active SET time=\''.$timestamp.'\' WHERE sessid=\''.$sessid.'\'');

Yes, time is also defined as:
$time = time();

So, what is the issue here?
Comment: Can you try `$_GET["sessid"]` ? Are you using any libraries or frameworks that might unset `$_REQUEST`? WHat does `var_dump($_REQUEST);` say?
Comment: If that's the var_dump(), why did the `method`,`room` & `qid` keys disappear?
Comment: `var_dump` is `array(1) { ["sessid"]=>  string(21) "d0sma94yw4r4cdckv2ufhb" }`
Comment: Alright, this is a bit weird, but I did another `var_dump` through the application, not just the URL based one this time, and here are the results (with an obvious undefinition of the `sessid` variable).`array(4) { ["method"]=>  string(1) "r" ["room"]=>  string(7) "general" ["sessid"]=>  string(0) "" ["qid"]=>  string(13) "1276959603731" }`
Answer: Barring typos etc, if you have a version >= 5.3.0, you might want to check what request_order (or variables_order if request_order is empty) ini-setting is set to. If in none of those two the 'P' is set, the $_POST array will not be in $_REQUEST (and not even set it the 'P' is not in variables_order afaik). See: http://www.php.net/manual/en/ini.core.php#ini.request-order
If those 2 are allright, I'd say you have a logical error somewhere else, var_dump() the $_POST  and $_REQUEST superglobals to check.
Comment: I also have other variables being requested and processed, and they are processed without error. It's just `sessid`.
Comment: Do you have `register_globals` enables, and are you using (and possibly unsetting) a `$sessid` variable somewhere?
Comment: `register_globals` is off, and `$sessid` is validated but that happens before it gets to the page that sends data to `methods.php`.
Comment: Solved. I had a typo in the form that submits `sessid`, and setting the method to `$_POST` worked.


Problema com SUDO "must be setuid root"

Question: Então, acho que o título é auto-explicativo. Sou iniciante no Linux, fui tentar instalar o Steroids (ambiente de testes para APP's híbridos) seguindo esse tutorial (o segundo, de instalação), e agora sempre que tento usar o SUDO aparece essa mensagem:
Comment: http://stackoverflow.com/a/19306929/3029543
Answer: Esse problema provavelmente ocorreu após você executar o comando abaixo (fonte):
sudo chown -R `whoami` `npm -g bin`

Ao usar o comando chown com a opção -R você diz ao sistema para alterar o proprietário de arquivos e informações do grupo de modo recursivo, em seus subdiretórios e arquivos. O que certamente afetou o sudo.
Para consertar isso você deve reinicializar o sistema e entrar em modo de recuperação para reverter esse processo.

A partir do menu de inicialização, selecione o modo de recuperação, geralmente é a segunda opção de boot.

Depois de selecionar o modo de recuperação e esperar por todos os processos de arranque, será mostrado algumas opções. Neste caso, você deve inicializar escolher abrir um shell como root.
Em versões recentes do Ubuntu, o sistema de arquivos está montado como somente leitura, então você precisa digitar o seguinte comando para remontar como leitura e escrita, o que permitirá que você faça alterações:
mount -o rw,remount /

Feito isso, você estará no terminal como superusuário, digite:
# mount --all
# chown root:root /usr/bin/sudo
# chmod 4755 /usr/bin/sudo

Depois de executado os comandos acima, encerre a sessão:
exit

Isso o levará de volta para o menu de recuperação.

Escolha para retomar uma inicialização normal. Em seguida, você deve ser capaz de usar o sudo novamente.
Fonte
Comment: @ropbla9 execute *mount -o rw,remount /* uma vez somente. Se nao der certo, execute "mount -o remount /". Se voce estiver usando a versao **12.04 (ou superior)** execute "adduser NomeDoUsuario sudo" se isso nao der certo execute "sudo usermod -a -G sudo NomeDoUsuario".
Comment: @ropbla9 Tem como comentar como você chamou o comando `chown` ao instalar o Steroids?
Comment: eu fiz assim:

mount -o,remount / - OK > adduser myUser sudo (user ja faz parte do sudo) > sudo usermod -a -G sudo rop - OK. Mas ainda não funcionou.
Comment: QMechanic73, Não consegui man. O primeiro comano executando com o `, remount /` processou algo. Depois tentei dar `remount /` mas não deu. Depois rodeu `adduser meuuser sudo` e foi avisado que já faço parte do grupo sudo.
Comment: Eu to usando a versão mais recente do Elementary OS Luna
Comment: eu não lembro como fiz nada, cara.
Comment: esse funciona. Inclusive eu já tinha resolvido com essa mesma sequência que achei numa resposta na net. De toda forma sua resposta tá certa!
Answer: Possivelmente você não configurou a senha do root, tenta fazer isso:
$ sudo passwd root

Digite a senha para o usuário root ai tente instalar os pacotes que você quer.

Caso não dê certo verifique as permissões do arquivo sudo
$ ls -l /usr/bin/sudo

E posta ai

Certo, tente logar como root
$ su root

Se conseguir entrar digite os comandos
$ chown root:root /usr/bin/sudo
$ chmod 4755 /usr/bin/sudo

Se você não conseguir vai ter que entrar em modo de recupeção e digitar esses dois comandos que passei.
Para entrar em modo de recuperação: https://wiki.ubuntu.com/RecoveryMode
Comment: AdirKuhn, ainda nd http://3.ii.gl/Lp4M2JsTM.png
Comment: Adir Kuhn, ainda não consegui cara. Exeuctei esses dois ultimos comandos pelo modo Recorey, ambos funcionaram, mas ainda nao consegui usar sudo.
Comment: Adir Kuhn, tentei entrar em su root logado no sistema normalmente e pede uma 'password', tento colocar a minha que configurei na instalação e não vai.

Problema com SUDO "must be setuid root"


How to programmatically disable Global Theme Settings?

Question: I am trying to programmatically disable logo and site name. I have seen some variables for these set in modules/system/system.admin.inc but haven't been able to disable them through my profile installer settings.
What is the proper way to disable them? I looked around the internet but found no one has really looked into this issue.
Answer: See here for a related question.
The theme settings are not individually saved as variables. They are all in a single variable, whose name depends on your theme. For example, if your theme name is mytheme, the variable name will be theme_mytheme_settings.
You can disable the logo and name like this:
$my_settings = variable_get('theme_mytheme_settings', array());
$my_settings['toggle_logo'] = 0;
$my_settings['toggle_name'] = 0;
variable_set('theme_mytheme_settings', $my_settings);

You can also disable settings by means of the features key in the .info file for your theme. The defaults are:
features[] = logo
features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

If you don't specify any of these, all are enabled. If you specify some, only the ones you specify are enabled. So if you wanted to hide logo and site name, you would put this in your .info file:
; features[] = logo
; features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

See the theme settings documentation for more info. You need to be careful with this depending on what theme you are using. If you're overriding a base theme, these are the keys, but a contributed or custom theme might have different keys.


Azure multi tenant security - Azure Federated SQL, certs etc

Question: I'm trying to get some advice on how to approach a security architecture on Azure.
Background:
We are looking at building a multi-tenant app on Azure that needs to be extremely secure (personally sensitive data). The app will be accessed by standard browsers and mobile devices.
Security access types:
We have three types of users / access types...
1 - plain old user/password over https is fine, accessing both general, non private SQL plus hosted files
2 - user/pass over https, but need authentication of users via certificates that will be installed on user machines/devices. This level of user will need access to sensitive data which should be encrypted at rest both in database, and also any uploaded files.
3 - same as (2) but with the addition of some two factor authentication (we have used YubiKey for other things - might look towards a phone OTP offering as well)
Most users will only have access to their own tenant databases, however we have "account manager" type users that need access to selected tenant data, therefore we expect that they will need either a copy of one certificate per tenant they serve, or we will have to use some kind of master certificate.
Database type:
From a multi-tenant point of view it seems Azure Federated SQL is a good way to go because (a) we simply write one app with "TenentID" key in each table, and after login, set a global filter that handles the isolate for us (b) we understand that Azure federated SQL actually in the background maintains separate SQL database instances per tenant.(Ref: http://msmvps.com/blogs/nunogodinho/archive/2012/08/11/tips-amp-tricks-to-build-multi-tenant-databases-with-sql-databases.aspx)
Can anyone point to any links or give advice in relation to the approach needed to setup and manage file shares, encryption of SQL and file data at rest, authentication of users etc. (automated management on new user signup pref).
Comment: Update - very useful set of information around the entire issue here:  http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/84e53d0c-0dd3-448e-9ff8-ddd5069f9026
Answer: I can't really help on the certificates, but you will indeed need some "master certificate".  If you are planning on using Azure website, you can't use your own certificates currently.
Concerning the database setup.  SAAS applications build on trust, so you NEVER (EVER) want to be showing or editing the data of using to other users.
Therefore I strongly suggest that you don't use the TenantID for each table.  This would leave still the possiblity of an attack by a malicious user or an error by some developer.
The only way to get around these risks are

extensive testing
physical different tables to store each tenant data.

Personally I believe that even with very extensive+automated testing you can't have 100% code coverage against malicious users.  I guess I am not alone.
The only way out IMHO is physical different tables. Let's look at the options:

different server: valid, but pretty expensive in azure
different database: valid, less management overhead but same objection as the previous option - expensive if you have a lot of tenants
different schema's: the solution.  Think about it...

you only have to manage users and there default schema's
you can back-up schema's using powershell
you can move schema's to other databases with some work
You can still digg into SQL federation if you need to.
the major drawback is that you will need to support database upgrades for each tenant.

Have you read on azure.com any articles about multi-tenancy?  http://msdn.microsoft.com/en-us/library/windowsazure/hh689716.aspx
Comment: Thanks - we have since gone ahead and created a multi tenent using one database per client, with a single "master" database in the middle that orchestrates everything. Certificates being worked on next!


Qt - Help Linking Dynamic Library

Question: I am having a ton of trouble with the simple task of linking a DLL to my Qt project.
My steps:

In Qt, I go to 'File -> New File or Project -> Other Project -> C++ Library'
Add a calc method to my mylibrary.h.
Implement the calc method in my mylibrary.cpp.
I compile, and I go to the directory where .a and .dll files were created.
I create a new project: 'File -> New File or Project -> Qt Widget Project -> Qt Gui Application'
I copy and paste all header files from MyLibrary to C:/Users/Me/includes, as well as MyLibrary.dll and libMyLibrary.a to C:/Users/Me/.
I then go into my Qt Widget Project's project file (step 5).

I add the include path as well as the DLL path:
INCLUDEPATH += "C:/Users/Me/includes"
LIBS += "C:/Users/Me/MyLibrary.dll"

I then go into my mainwindow.cpp, and put this code:
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include "mylibrary.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    MyLibrary myLib;
    qDebug() << myLib.calc();
}

MainWindow::~MainWindow()
{
    delete ui;
}

And of course, I get undefined errors:
C:\Users\Me\Desktop\TestInternals-Win\..\TestInternals\mainwindow.cpp:15: error: undefined reference to `_imp___ZN13MyLibrary4calcEv'

C:\Users\Me\Desktop\TestInternals-Win\..\TestInternals\mainwindow.cpp:15: error: undefined reference to `_imp___ZN13MyLibrary4calcEv'

:-1: error: collect2: ld returned 1 exit status

MyLibrary File Contents
mylibrary.h contents:
#ifndef MYLIBRARY_H
#define MYLIBRARY_H

#include "MyLibrary_global.h"

class MYLIBRARYSHARED_EXPORT MyLibrary{
public:
    MyLibrary();
    int calc();
};

#endif // MYLIBRARY_H

mylibrary.cpp contents:
#include "mylibrary.h"

MyLibrary::MyLibrary()
{
}

int calc()
{
    return 5;
}

I have not touched the Qt generated MyLibrary_global.h file
Thanks for any help.
Comment: You suppose to link `MyLibrary.lib' instead of `MyLibrary.dll`?
Comment: I don't have a .lib, but I have a .a. I've tried linking the .a also, but that doesn't work either.
Comment: .a sosunds like it was compiled using gcc, not visual studio.
Answer: You define a stand alone calc function instead of MyLibrary::calc, try:
mylibrary.cpp
#include "mylibrary.h"

MyLibrary::MyLibrary()
{
}

int MyLibrary::calc()
{
    return 5;
}

Qt - Help Linking Dynamic Library


Migration of public folders from Exchange 2010 to Icewarp

Question: We are in the process of Migrating Exchange 2010 to Icewarp.
The migration process works without problems for postboxes and items. I'm feeling absolutely lost when it comes to Exchange public folders.
There is NO document about that, even though there is a Manual about the migration it does (nearly) not cover the public folders.
In the migration App there are those settings. Does anybody have an idea what to fill in there?
What is the "Exchange source mailbox" of a public folder?
I have no idea how to use on this stuff.

I'm thinking about exporting the content of those Exchange Public folders via Outlook into a pst-file and then import it (somehow?) into Icewarp public folders.
Comment: All public folders we are using in Exchange are created by an Administrator as "Public default folders" in EMC.
When i select email@example.com as "Exchange Source Mailbox" or any other Account, the migration throws an error "Unable to explore folder tree, because The Id property must be set." and just did not stop any more with the migration till i abort the migration run.
Answer: Based on my research, "Public folders stay behind other account data in MS Exchange. There is no exact one-to-one correspondence between MS
Exchange and IceWarp server, thus public folders are created under a group with the Group name specified here.If the Migrate through this account (mandatory) box is not checked, public folders will not be migrated" which is mentioned in this article. And did you use IceWarp Exchange migrator to migrate exchange server,if yes, you also could refer to above article.
In addition, Could you fill out the master migration account as exchange source mailbox? For accurate replies, you'd better to seek for an expert on Icewarp.
Comment: yeah, i read that also. And i read that only because it's the only doc i could find about that issue.
I think Icewarp is fine, but documentation and support could be MUCH better. There own forum is a joke :-(


nash equilibirum help! seems tricky

Question: Any advice for finding all nash equilibrium for this symmetric game? (B,B) looks like one but I feel like there are more. I tried looking for strictly dominant strategies, but only A weakly dominates D.
\begin{array}{|c|c|c|c|c|}
\hline & A & B & C& D \\
\hline  A & (8,8)& (0,10) & (0,5) & (0,0) \\
\hline B&(10,0)& (1,1)& (-9,5)&(-9,0)\\
\hline C&(5,0)& (5,-9) & (-5,-5)& (-15,0)\\
\hline D&(0,0)& (0,-9)& (0,-15)&(-10,10)\\
\hline
\end{array}
Comment: The title makes me want to scream "Help! Help! I'm being repressed!"
Answer: As CommonerG noted, $D$ is worse than $A$ for the row player unless the column player mixes only $B$ and $C$.
So first assume that the column player mixes only $B$ and $C$. Then $C$ strictly dominates $B$ for the row player. That leaves us with
\begin{array}{|c|c|c|}
\hline & B & C\\
\hline  A & (0,10) & (0,5)\\
\hline C& (5,-9) & (-5,-5)\\
\hline D& (0,-9)& (0,-15)\\
\hline
\end{array}
If the column player puts higher weight on $B$, the row player must choose $C$, but then the column player would choose $C$. On the other hand, if the column player puts higher weight on $C$, the row player must choose a mixture of $A$ and $D$, but then the column player would choose $B$. Thus there is no Nash equilibrium in this case.
It follows that neither player mixes only $B$ and $C$, and hence $D$ can be eliminated, leaving us with
\begin{array}{|c|c|c|c|}
\hline & A & B & C\\
\hline  A & (8,8)& (0,10) & (0,5)\\
\hline B&(10,0)& (1,1)& (-9,5)\\
\hline C&(5,0)& (5,-9) & (-5,-5)\\
\hline
\end{array}
If the column player mixes only $A$ and $B$, then $B$ strictly dominates $A$ for the row player, who thus mixes only $B$ and $C$. Since we've excluded that, it follows that neither player mixes only $A$ and $B$.
If the column player mixes only $A$ and $C$, then $A$ strictly dominates $C$ for the row player, leaving us with
\begin{array}{|c|c|c|}
\hline & A & C\\
\hline  A & (8,8)& (0,5)\\
\hline B&(10,0)&(-9,5)\\
\hline
\end{array}
If the row player puts any weight on $A$, the column player chooses $A$, but then the row player must choose $B$. On the other hand, if the row player chooses $B$, the column player chooses $C$, but then the row player must choose $A$. Thus there is no Nash equilibrium in this case.
Now we're left only with the case where both players mix all strategies $A$, $B$ and $C$. That implies that both players can make all three strategies yield the same payoff for the other player, yielding a system of linear equations: $8w_1+0w_2+0w_3=10w_1+1w_2-9w_3=5w_1+5w_2-5w_3$ with $w_1+w_2+w_3=1$.
The solution can be obtained by producing two homogeneous equations by subtraction, e.g. $2w_1+1w_2-9w_3=0$ and $-3w_1+5w_2-5w_3=0$, taking the cross product to find $w\propto(40,37,13)$ and normalizing to find that the only Nash equilibrium is the one in which both players apply the mixed strategy with weights $4/9$, $37/90$ and $13/90$ for strategies $A$, $B$ and $C$, respectively. The value of the game for both players is $8w_1=32/9$.
Note that both players playing $B$ is not a Nash equilibrium, since both players would switch to $C$.
Answer: After eliminating D by weakly domination, observe that some mixture of A and B dominates C. It is the case.
The rest is straightforward.
Comment: This is incorrect. Nash equilibria may contain weakly dominated strategies; see [Wikipedia](http://en.wikipedia.org/wiki/Strategic_dominance#Dominance_and_Nash_equilibria).
Comment: Also, mixing $A$ and $B$ does not dominate $C$, since $C$ has higher payoff against $B$ than both $A$ and $B$.
Comment: Joriki you are right in your second comment (i confused rows and columns). In your first comment it's obvious that weakly domination is what i meant since my sentence starts by (After eliminating D by weakly domination).
Comment: Yes, I think I understood that, and I was responding to that. You tried to eliminate a strategy by weak domination, and I pointed out that this is incorrect because Nash equilibria may contain weakly dominated strategies. (By the way, it's "weakly dominated", but "weak domination", not "weakly domination".)

nash equilibirum help! seems tricky


Help manipulating this equation

Question: I have this equation:
$$A(f)=\frac{1}{\sqrt{\left(1-\left(\frac{f}{F}\right)^2\right)^2+c^2\left(\frac{f}{F}\right)^2}}$$
and I am told this:

Note that for a fixed amplitude $A$, the equation relating amplitude and $f$ can be converted to a 4th degree polynomial in $f$ by squaring both sides (to eliminate the square root), taking the reciprocal of both sides, and then subtracting $A$. Do this algebraic manipulation "by hand."

I got it down to a quadratic:
$$f^2 = \frac{F^4-F^4y^2}{y^2(F^2C^2-2F^2+1)}$$
Please help :)
Comment: Somehow, when you "got it down to a quadratic," the symbol $A$ disappeared altogether. How'd you do that?
Comment: Joe, I hope you don't mind, I rolled back and then incorporated your edits into my edit.
Comment: @ZevChonoles: Don't mind at all.
Answer: $$A=\frac{1}{\sqrt{\left(1-\left(\frac{f}{F}\right)^2\right)^2+c^2\left(\frac{f}{F}\right)^2}}$$
$$A^2 = \frac{1}{(1-(\frac{f}{F})^2)^2+c^2(\frac{f}{F})^2}$$
$$\frac{1}{A^2} =  (1-(\frac{f}{F})^2)^2+c^2(\frac{f}{F})^2$$
$$\frac{1}{A^2} = 1+\frac{f^4}{F^4} - \frac{2f^2}{F^2} + \frac{c^2f^2}{F^2}$$
$$\frac{1}{A^2} = \frac{1}{F^4} f^4 + \left( \frac{c^2-2}{F^2}\right)f^2+1$$
where the last line gives a 4 degree polynomial in $f$. (Not sure where to subtract $A$!)
Comment: I don't think you're missing anything. The problem statement is very sloppy, asking to convert an equation to a polynomial - strictly speaking, that makes no sense. It's not surprising that someone who could be that sloppy could also be sloppy about "subtract $A$".
Comment: Surely the "subtract $A$" was a mistake.
Comment: I assume so, but perhaps I am missing some clever algebraic trick?

Help manipulating this equation


unusual record count in TQuery.Record count

Question: I have one Delphi application that connects to MS-SqlServer-2008R2 via BDE + ODBC. Developed using Delphi 7.
Accessing data using TDatabase, TTable, TQuery components.
The TDatabase is point to Alias name in BDE, and other components using the property TDatabase.Databasename.
The main transaction table have more than 300 000 records.
in main application When I querying the table, the TQuery gives record count as 2.5 million, but my table have only 300k record. After the query open application just crashed. what is the problem here?
If I debug the code , it gives "Memory Error" at TQuery.Open. but while running the application it not giving any error and just application got crashed.
I checked memory usage in Task manager before open the query is just 20 MB, but after open the query the application using more than 700 MB memory.
Copied the same query and run in SQL server management studio and get 45000 records.
Again just created one more small application with one form and one TQuery , TDatabase , and ran the query, it gives correct count 45000.
Why it giving unusual record count in main application?
Comment: Please recheck your query, must be something wrong with JOINS
Comment: There are so many possible problems, and you haven't given enough information for anyone to give an answer. Are you connecting to the same DB. Are your connection settings the same. In SQL Server, are you using the same schema/user? Do you really need BDE? It has officially been deprecated.
Comment: Please, show your query so we can start to dig into it.
Answer: Check the Database component property 'Params'. if any param is set with RowSet Size = -1. if it is there then remove it. This is the cause of the issue.


Flattened notes and odd fuzzy sound on trumpet

Question: Yesterday practicing I noticed a high improvement over previous days in terms of sound and intonation, I could play all the harmonic series up to high E more or less properly intonated and with a good and full sound tonguing them.
The problem is that today, I picked up the trumpet and after a little time of practice I started to make notes very flat by default, almost more than one semitone lower and I was having a really hard time getting it up to the correct pitch.
Also sometimes I get like a "farty" fuzzy sound from my lips like the sound of them clashing too much like if they were too loose.
I don't get why this is. I can think of my embouchure being too relaxed and lips not correctly placed on the mouthpiece and still have problems finding the position and alignment of my jaw
Comment: I don't know anything about playing the flute. I've had a similar experience on clarinet and other instruments. Some days are just bad days. There could be so many reasons: the weather, how much sleep you got last night, your diet, exercise, stress, maybe a butterfly flapped its wings on the other side of the world and that has thrown something off. I hope and expect a flautist will answer with better information and advice, but I wanted to at least say that everyone has off days that we can't explain and you'll definitely get it back. Sometimes even better than before.
Comment: @ToddWilcox, trumpet not flute, but point taken - could have been a bad day
Comment: @phoog More or less been playing for 3 to 5 weeks. I play slowly, focusing on sound and intonation and try to play all notes in the chromatic scale as well from C to High C at least. Higher than that it's still a bit of an effort to me.
Comment: @MisterEquis, how long have you been playing trumpet?
Comment: @MichaelCurtis but the basic point remains.  There's also the principle of [regression toward the mean](https://en.wikipedia.org/wiki/Regression_toward_the_mean): if you do anything where your performance might fall within a certain range, and on one occasion the performance falls near the better end of the range, chances are good that the next performance will be worse.
Comment: @phoog, yes. And I asked about his experience level for some context. I think we need a bit more detail to see the bigger picture.
Answer: You're tired.  Your 'lip's gone'.  Don't worry, it'll be back tomorrow.  Unless you got the high notes yesterday by pressing too hard and bruised the lip.  Then it will take a few days.  Don't over-think this.
Answer: Up front disclosure: I don't play trumpet. I've been practicing piano for a few years. But my son has been playing for 3 years in a very good school program so I have some knowledge of the instrument. Keep this in mind when you read my answer and hopefully a trumpeter will add a better answer.
I think you may be feeling the effect of fatigue. Your mouth probably needs rest.
You may not perceive the fatigue. You may be taking rests while you practice, but that may only be enough for immediate relief and you remain at the cusp of exhaustion.
If you have a teacher, talk to them about it. If not, try feeling about the proper amount of rest you need. Take a day off now to fully recover then figure out intervals for playing and rest. Also consider that a variety of exercises can provide contrast and a sort of rest. Something like long notes in the low register to focus on tone and breath control should also provide embouchure relief from my high notes. "Buzzing" your lips off the mouthpiece is something my son mentioned for rest.
With only a few weeks in to playing, this type of fatigue makes sense to me. When doing something new we have lots of enthusiasm which can risk mental or physical burn out. Of course the enthusiasm is good, but we need to temper it with strategies for a lifetime of activity!
It sounds to me like you are developing a good practice routine and have a thoughtful approach. That's great! You probably need some rest and need to figure out how to not "over train."
Answer: Other posts here suggest you are the cause of the problem. But it might be the instrument...
Intonation and 'slotting' all go haywire when the main water key doesn't seal properly. So check the spring that closes the water key on the main tuning slide. These springs do occasionally fail. Also check that the cork hasn't perished.
Check too that all the valve pistons are correctly aligned - when you remove a valve to oil or clean it, when you replace it rotate it gently until the alignment bump audibly clicks into the machined slot inside the valve barrel. Beware - some trumpets have two alignment slots, making it possible to align the valve correctly and 180° out.
Or perhaps the valves are inserted out of order. If you suspect this, visually inspect each valve. Hopefully each will be marked with a number. If you're unlucky and the valves are unnumbered, start by inserting a piston into the third barrel. The reason for starting with the third valve is that the mouthpipe connects to the third valve. Blow down the mouthpipe and the airstream should be unobstructed whether the third valve is up or down. Once you've established the correct third valve, move on to the second valve.
Comment: Thanks. in my case it could only be the water key spring or the cork since I haven't cleaned the trumpet yet so I did not remove the valves.


Por que Debugger pula linha com header, não indo para o link?

Question: Quando inicio o debugger php7.0 CLI com essa configuração do php.ini:
;extension=php_soap.dll
;extension=php_sockets.dll
;extension=php_sqlite3.dll
;extension=php_tidy.dll
;extension=php_xmlrpc.dll
;extension=php_xsl.dll
extension=pdo.so
extension=pdo_mysql.so

; XDEBUG Extension

zend_extension = "path"

;;;;;;;;;;;;;;;;;;;
; Module Settings ;
;;;;;;;;;;;;;;;;;;;

[xdebug]
xdebug.remote_enable = On
xdebug.profiler_enable = On
xdebug.profiler_enable_trigger = On
xdebug.remote_autostart = 0
xdebug.remote_handler= "dbgp"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_mode = "req"
xdebug.remote_port = 9000

[CLI Server]
; Whether the CLI web server uses ANSI color coding in its terminal output.
cli_server.color = On

O debugger  entra no if e chega em  header('location:login.php'); mas não vai para a pagina login.php. Em vez disso sai da condicional if passando pelos includes chegando até o final do arquivo.
Não direciona para o " include $fullpath; ".
Vale lembrar que em execução normal o programa funciona entra no login o banco retorna a pesquisa é verificado a veracidade dos dados e então acesso a pagina inicial do programa.Claro que uso o apache que está instalado a parte.

( explicando essa parte - eu instalei o Lampp que vem com Mysql, apache e  Proftpd juntos. Na procura por um debuggador achei as instruções para baixar o php5.1 fiz $ sudo apt-get install php5-xdebug configurei o php.ini como informado em http://www.diogomatheus.com.br/blog/php/depuracao-de-aplicacoes-php-com-xdebug/ .
  Só então percebi que na realidade estou com dois apaches um denominado apache e o outro apache2, se entendi certo. A coisa é que estou com dois php.ini, contudo tomei o cuidado de configurar os dois da mesma forma.)

O que acontece com o caminho ignorado pelo debugger ? Por que ele ignora o caminho do header ?
?php
session_start();

if( !(isset($_SESSION['login']) && $_SESSION['login']==true) ){
header('location:login.php');
}

include 'application/dao/Connection.php';
include 'biblioteca/Conversor.php';
include 'biblioteca/Validator.php';

if( isset($_GET['page']) ){
  $page = $_GET['page'];
  $php='';
  $class='';
  $folder='';
  $fullpath='';
if(strpos($page, "_")!= 0){
    $vetor = explode("_", $page);
    $folder = $vetor[0];
    $class = $vetor[1];

}else{
    $file = "";
    $class = "";
}

$fullpath = "$folder/$class.php";

if(file_exists($fullpath) == false){
    $fullpath = "begin.php";
}
} else {
  $fullpath = "begin.php";
}
?>

Answer:
O debugger entra no if e chega em header('location:login.php'); mas não vai para a pagina login.php.

Para enteder o real funcionamento, é necessário entender como o header funcionar e como ele é tratado.
PHP.net:

header — Send a raw HTTP header

Basicamente, o header envia um cabeçalho HTTP para o browser. O output do cabeçalho nada mais é que texto puro. Grosseiramente falando, é um echo específico para cabeçalhos e que ignora o buffer de saída (output buffer).
No caso de um cabeçalho com location, o que é enviado para o browser é que um direcionamento deve ser executado.
O PHP não sabe executar redirecionamentos, o comando header('location:login.php') envia o cabeçalho de redirecionamento para o browser e quem executa o redirecionamento é o próprio browser.
Outro detalhe é que o header não interrompe a execução do código. Tanto é que é recomendável utilizar um die, exit ou return logo após o header.
header('location:login.php');
die();

Quando o browser recebe o cabeçalho de redirecionamento, o browser realiza o redirecionamento para você.

O que acontece com o caminho ignorado pelo debugger ? Por que ele ignora o caminho do header ?

Isso ocorre, também, pelo lugar que você está executando o código.

Quando inicio o debugger php7.0 CLI com essa configuração do php.ini:

Em toda a explicação, eu enfatizei o uso de browser. Todo o redirecionamento é realizado apenas pelo browser.
No seu caso, você está executando seu código via CLI (commando-line interface). O PHP CLI não realiza redirecionamentos por não utilizar o protocolo HTTP (protocolo o qual é utilizado pelo browser). Tanto que, o PHP CLI ignora completamento a execução do header.
Logo, como a execução do header é completamente ignorada e ele não interrompe a execução do script, é normal o debugger continuar a execução do código como se nada tivesse acontecido.

Não direciona para o " include $fullpath; ".

Não localizei no seu código o include $fullpath.
Mais informações:
https://stackoverflow.com/a/8083152/1628790
https://stackoverflow.com/a/11894758/1628790
https://stackoverflow.com/a/20932511/1628790
Comment: @FabianodeSouzaPereira desculpe pela demora, mas não consegui encontrar relação entre o xDebug e o problema que você apresenta com o `include`/`require`. Não consegui encontrar nenhuma configuração que pudesse comprometer isso, por isso, acredito que seja a forma (ou IDE) que você está utilizando. Talvez tentar outra, como PHPStorm, NetBean ou ZendStudio para ver se ocorre o mesmo. Como a sua pergunta era mais focada no header, creio que esse seu questionamento possa/deva ser outra pergunta.
Comment: O include $fullpath está no body. Eu incluo o include do top.php que é onde está o menu. Depois o "corpo" do site e logo a pós o buttom.php que é o rodapé. Basicamente só troco o conteúdo do  meio da pagina do site.
Comment: Só uma coisa. Como testar o site pelo debugger?  Tenho um problema no carregamento de alguns itens e gostaria de debugar todos os passos até chegar na pagina com o problema. Isto é impossível em php ? Em java é molesa da pra andar em todo o código, passo a passo. Já em php ....
Comment: Chamada para onde Gabriel?
Comment: Se refere a botão direito em index.php -> debug as -> php CLI application ?  Segue github se achar por bem ser mais. https://github.com/FabianoSouzaPereira/myschool.com.br
Comment: Acabei viajando aqui, qual IDE você está usando? Faz tempo que não mexo com o xDebugger. Farei uns testes mais tardes para entender o por que.
Comment: Eclipse Java EE IDE for Web Developers.

Version: Oxygen.1a Release (4.7.1a)
Build id: 20171005-1200


Correct definition of the probability space of a $ \mathcal{F}_{t} $-measurable random variable

Question: Let the triple $ \left ( \Omega, \mathcal{F}, \mathbb{P} \right ) $ designates the probability space of a stochastic event and let us consider the filtration $ \left ( \mathcal{F}_{t} \right )_{t \in \mathcal{T}} $, where $ \mathcal{T} = \left \lbrace 1,2,\dotsc, T \right \rbrace $ and $T \in \mathbb{N}$.
Now, let the following sequence of $\mathcal{F}_{t}$-measurable random variables $\left ( X_{t} \right )_{t \in \mathcal{T}} $ be a stochastic process on the filtered probability space $ \left ( \Omega, \mathcal{F}, \left ( \mathcal{F} \right )_{t \in \mathcal{T}}, \mathbb{P} \right ) $.
I was wondering what of the following statements about a specific $X_{t}$ is formally correct:

$X_t$ is a $\mathcal{F}_{t}$-measurable random variable on $ \left ( \Omega, \mathcal{F}, \mathbb{P} \right ) $
$X_t$ is a $\mathcal{F}_{t}$-measurable random variable on $ \left ( \Omega, \mathcal{F}_{t}, \mathbb{P} \right ) $
Answer: We say that a variable $X_t:\Omega \rightarrow \mathbb{R}$ is $\mathcal{F}_t$-measurable if $X_t^{-1}(A) \in \mathcal{F}_t$ for all $A \in \mathcal{B}(\mathbb{R})$, where $\mathcal{B}$ is the Borel $\sigma$-algebra on the reals.
If by "on the filtered space" you mean adapted to the filtration, then yes, by definition $X_t$ is an $\mathcal{F}_t$-measurable random variable on $(\Omega, \mathcal{F}_t,P)$. The second statement is surely true.
Also, note that $X_t^{-1}(A) \in \mathcal{F}_t \subset \mathcal{F}$ for all $t$ and for all $A\in \mathcal{B}(\mathbb{R})$! Therefore, also the first statement must be correct.


Eclipse Oxygen Java Decompiler plugin

Question: I have noticed that, for eclipse oxygen, it is not available a decompiling plugin
Some times ago I used "Eclipse Class Decompiler plugin" (https://www.eclipse.org/community/eclipse_newsletter/2017/february/article8.php ) but this too does not work anymore...
Can you help me find an alternative for decompiling java sources on eclipse oxygen
Thanks in advance
Comment: Please read the [security bulletin about the Eclipse Class Decompiler](https://eclipse.org/org/press-release/20170814_security_bulletin.php)! How about [Bytecode Outline](http://marketplace.eclipse.org/content/bytecode-outline)?
Comment: Bytecode Outline isn't a decompiler...
Comment: What is your use case? How about running a decompiler (e. g. [CFR](http://www.benf.org/other/cfr/)) from the command line via an _External Tool configuration_?
Comment: I would like to press F3 button and enter in decompiled class like IntellijIdea...
Comment: you can use: https://ecd-plugin.github.io/ecd/
Answer: Try this eclipse plugin update site:
http://cnfree.github.io/Eclipse-Class-Decompiler/update
Comment: As mentioned by howlger, this tool is full of adware. See https://eclipse.org/org/press-release/20170814_security_bulletin.php

Eclipse Oxygen Java Decompiler plugin


how to use two conditions in select conditions in xslt when using Apply template

Question: <xsl:apply-templates mode="block2sequence" select="NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId][position()=1] and NewDataSet/Table[CTD_SEQ_NUM =$strXSLMsgType][position()=1]"/>

why cant i use two conditions in above select condition, can any one suggest me
Comment: THis isn't clear: What do you want to achieve, what do you want selected, which are the two conditions you can't specify (in the above `select` attribute you actually have two conditions specified).
Comment:  since like this we are using in match=" X and y" similarily when i m doin here it was say wrong
Comment: @_pravz: Better edit your question and describe well what the problem is. Your comment is still confusing.
Comment: @DimitreNovatchev yeah i have edit the template y it was throwing error can you please suggest
Comment: @DimitreNovatchev i have two use conditions in select because there $PackageId and $PackSEQ in all newdataset/table packageid will be same and packseq WILL VARY SO BY USING TWO CONDITION THEN MY PROBLEM WILL RESOLVE SINCE WHEN I M TRYING TO UPDATE TWO CONDITIONS IN APPLY TEMPLATE SELECT IT WAS THROWIN AN Error, kindly advice me
Answer:
<xsl:apply-templates mode="block2"
     select="NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId][position()=1] "/>

why cant i use two conditions in above select condition

I guess this is to mean, "why can't the two conditions be specified in the same predicate?"
The answer is that the expression:
NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId and position() = 1]

isn't equivalent at all to the 1st expression above.
The first expression selects the first Table child of NewDataSet such that the string value of its CTD_CTD_PKG_ID child is equal to the string value of $PackageId. In this case we don't know which child (at which position) of NewDataSet will be selected -- any child that happens to be the first with the specified properties, will be selected.
On the other side, the latter expression selects the first Table child of NewDataSet only if the string value of its CTD_CTD_PKG_ID child is equal to the string value of $PackageId. In this case, if anything is selected, it would be the first Table child.
If you want an equivalent expression to the first one, that has only one predicate, one such expression is:
NewDataSet/Table
      [CTD_CTD_PKG_ID =$PackageId
     and
       not(preceding-sibling::Table[CTD_CTD_PKG_ID =$PackageId ])
      ]

Update: The OP has published a code snippet:

 <xsl:apply-templates mode="block2sequence" select=
    "NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId][position()=1]
    and
     NewDataSet/Table[CTD_SEQ_NUM =$strXSLMsgType][position()=1]"/>

This code will cause an error thrown at compile time by the XSLT processor.
The value of the select attribute is a boolean (expr1 and expr2), however templates in XSLT 1.0 and XSLT 2.0 can only be applied on nodes. A boolean isn't a node -- hence the error.
Solution:
My first guess is that you want templates to be applied on both nodes. If this is so, then use:
 <xsl:apply-templates mode="block2sequence" select=
    "NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId][1]
    |
     NewDataSet/Table[CTD_SEQ_NUM =$strXSLMsgType][1]"/>

My second guess is that you want templates applied only on the first of the two nodes. If this is so, then use:
 <xsl:apply-templates mode="block2sequence" select=
    "(NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId]
    |
     NewDataSet/Table[CTD_SEQ_NUM =$strXSLMsgType]
     )
      [1]
"/>

Notes:

Please, learn how to ask a question -- provide all relevant data and explain -- in the question, not in subsequent comments.
Did you know that [1] is equivalent to [position()=1] and is shorter?
Answer: You can use two conditions and your expression looks perfectly correct. If it is failing with an error, please tell us the error. If it is not selecting what you want, then (a) show us your source document, and (b) tell us what you want to be selected.
(You know, your question gives so little information, you don't give the impression that you really want an answer.)
Comment: Expression must evaluate to a node-set.   -->NewDataSet/Table...] [position()=1]<--  this is the error which was getting for me


Window.open opens new tab in safari when maximized

Question: One safari browser window is already open through the Window.open(1st) and from that window,on clicking a button,the callback opens another window(2nd) with a link to outside domain.
Safari opens the outside link in new browser window if the 1st browser window is not maximized , but when the 1st browser window is maximized then outside URL opens in the adjacent tab instead of new browser window.
How do I make the safari browser open the new browser window when the 1st browser window is maximized as well.
Answer: Just stumbled over a similar issue and found out that this is related to a setting for the Dock.

Click the "Prefer tabs when opening documents" pop-up menu, then choose an option—Always, In Full Screen Only, or Manually. By default, documents open in tabs only when an app is full screen.
  ~ https://support.apple.com/kb/PH25079?locale=en_US

I set it to Manually and now it opens a new window for the popup when I am in fullscreen mode.
However be aware that the popup will also be in fullscreen mode!


What test to use for overlapping categories

Question: i am analyzing a surveillance tool where people could be collected by one or both methods. So it kinda looks like a Venn diagram. What test would I use to test if there's significant differences by the methods for different characteristics? The only statistical package I have access to is SAS so please recommend something that can be done in that.
Thanks.
Comment: Neither your question nor your data is clear... I'm guessing your cases are individual people, that two methods of surveillance were applied to every person, sometimes succeeding and sometimes failing?
Comment: I've got a population of sick people who can be captured by hospital, provider or both. I want to see if things like laboratory tests, severity of illness, etc are different between the population captured by hospital and the population captured by provider. About 70% of the population are captured by both hospital and provider.
Comment: Please give specific detail on what sort of differences would be tested.  In other words, please describe your data some more.
Answer: I would focus on just those individuals captured by either the hospital or the provider but not both, and then look for differences beteen the two populations using the usual two-sample tests, such as a t-test.
As an example, consider a binary characteristic, like sex.  Suppose the data were like this:
<code>             male   female  total     percent male
prov only      58       42    100          58
hosp only      83      117    200          42
both          355      345    700          51
</code>
If we're going to compare the percent males captured by providers and hospitals, we could compare (58+355)/(100+700) to (83+355)/(200+700), but the 355/700 are in common, so I suggest just compare 58/100 to 83/200 (say, using a $\chi^2$ test).  Alternatively, as suggested by whuber below, you could compare the three groups.
If the outcome is some continuous number, I'd replace the $\chi^2$ test with a t-test or ANOVA.
Comment: This sounds legitimate, but why throw away those who used both hospital and provider (which is the bulk of the data)?  It seems like comparing all *three* subpopulations (hospital only, provider only, both) would be of interest.  Now the t-tests become (strongly) interdependent, suggesting we work within an ANOVA setting with three categories, bearing in mind that any significant differences can *not* be attributed to hospital vs. provider due to the self-selection that is likely going on.  (But perhaps I misunderstand what "captured by provider" really means.)
Comment: @whuber - Good points; I was thinking along the lines of McNemar's test.  I've added an example that illustrates what I have in mind, as well as your 3-group comparison.
Answer: This sounds like it can solved by two-way ANOVA: treating severity of illness as the dependent variable; then hospital as one factor; provider as another factor and probably include an interaction term.
You may also look into multivariate ANOVA if there are multiple dependent variables that you are interested in.
Comment: Two-way ANOVA doesn't seem quite right, as the goal seems to be to compare hospital and provider rather than look at their separate effects and potential interaction.


BIT(1) HIbernate JPA mapping

Question: In Postgresql I have a column with type BIT(1). In JPA mapping it's like:
<code>@Column(columnDefinition="bit(1)")
private String type;
</code>
But, when I perform tests, this error occurs:
ERROR: column "type" is of type bit but expression is of type character varying
   Tip: You will need to rewrite or cast the expression.
   Rank: 117
I've tried with other Java types: char, int, Boolean, and BitSet. But, the same error occurs.
Do you know how can I map Postgresql type BIT(1) to Hibernate JPA??
Comment: Is there any good reason to use bit(1) here? I suppose a simple boolean would be more straighforward.
Comment: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/types.html
Comment: ERROR: column "type" is of type bit but expression is of type boolean
   Tip: You will need to rewrite or cast the expression.
   Rank: 117
Comment: It is a requirement for the project... I'm just developing the persistence layer.
Comment: Maybe, but i don't see any valid usecase for `bit(1)` - but i am happy to learn something new. IMHO it is just a waste of space (a bit(1) uses 6 bytes of storage).
Comment: In Postgres you should be using `boolean` rather than `bit(1)`
Answer: Hibernate doesn't support type bit of PostgreSQL.
Try to use the native query of spring JPA with the cast. For example:
<code>@Modifying  @Query(value = "update table set is_active = cast(:is_activeas bit) where id = :id", nativeQuery = true)

int updateTable(@Param("is_active") int isActive, @Param("id") long id);
</code>

BIT(1) HIbernate JPA mapping


Robust Coefficients For Differences in Differences

Question: I have a panel data set which I am looking to analyze for relationships/causality using the OLS differences-in-differences method.  The panel data includes multiple observations over time for various groups that are most likely correlated to each other.  Serial autocorrelation also exists within the data, given the nature of the time series component.  My goal is to make my analysis as robust as possible.  I've researched ways to prevent a biased estimation in the coefficients as much as possible due to these effects, but I am struggling with finding and applying a singular approach.
Example:  Lagging the time series component and introducing the lag'd value into the model will minimize the residual autocorrelation attributed to the time series in the model.  But won't account for the between-group relationships.  Using clustered standard errors makes the coefficients more robust, but doesn't seem to deal with the time series autocorrelation component (at least as far as I can tell).  Can I obtain the best (i.e. most robust and accurate) result using both methods? Or would doing so further introduce random noise/bias in the model that I'm just missing? Would just one be more appropriate?
Bonus:  Is there a Bayesian approach to solve this problem?
Comment: The clustering of standard errors doesn't affect the coefficients. If you cluster the standard errors on your panel units this will take care for autocorrelation and heteroscedasticity.
Comment: For clarity, the "two methods" you are referring to are (1) including a lagged y value as an additional covariate, & (2) using clustered SE's, is that correct?
Comment: @Gung, you are correct in your assumption
Comment: @Andy, could you please provide any additional information?
Answer: First we should probably clear out the distinction between a bias in the coefficients and a bias of the standard errors.
In order to obtain an unbiased estimate of the treatment effect in a difference in differences setting you need the parallel trends assumption to hold. See here for a detailed explanation. If this assumption holds, treatment selection is not endogenous, and you don't have any time varying factors which affect the outcome deferentially across treatment groups at the same time your treatment kicks in (i.e. no other confounding factors), then you will get an unbiased coefficient.
The adjustment to standard errors to account for serial correlation and heteroscedasticity is an entirely different matter. This is not about correct estimation of the treatment effect coefficient but about the correct estimation of its standard errors. For appropriate inference in difference in difference settings you can have a look at Bertrand et al. (2004) "How much should we trust difference-in-differences estimates?" (link, ungated working paper version here).
One approach they suggest in order to correct for both autocorrelation and heteroscedasticity is to cluster standard errors on the panel unit id. This is easily implemented in most statistical packages. If your unit identifier is id then in Stata you would just use the variance-covariance estimation option cluster(id) at the end of the regression command. To me this seems to be the "singular approach" that you were looking for. One word of caution regarding lagged dependent variables: since difference in differences is a type of fixed effects regression adding a lagged dependent variable requires very strong assumptions in order to yield unbiased estimates (you can find a discussion of the issue in any book on panel data econometrics such as Angrist and Pischke (2009) or Wooldridge (2011)).


TemplateBinding and ContentPresenter in Silverlight/WPF

Question: I have a listbox which has templates defined for the ItemContainer and the ItemTemplate styles.
My ItemTemplate is a DataTemplate which is very simple:
<DataTemplate x:Key="DataTemplate1">
    <Grid x:Name="grid">
    <TextBlock TextWrapping="Wrap" Text="{Binding}" Foreground="White" FontSize="24" />
    </Grid>
</DataTemplate>

and the ItemContainer is also very simple:
<Grid x:Name="Grid" HorizontalAlignment="Stretch" Height="Auto" SnapsToDevicePixels="true" Width="373" Background="{x:Null}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="37"/>
    </Grid.ColumnDefinitions>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="SelectionStates">
            <VisualState x:Name="Unselected"/>
            <VisualState x:Name="Selected"/>
            <VisualState x:Name="SelectedUnfocused"/>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <ContentPresenter x:Name="contentPresenter" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Stretch" Margin="2,0,0,0" d:LayoutOverrides="Width">
    </ContentPresenter>
    <Image x:Name="image" HorizontalAlignment="Center" Margin="0,0,0,1" Source="/MyApp;component/Images/icon_arrowcircle.png" Stretch="Uniform" Width="37" Grid.Column="1" VerticalAlignment="Center" Opacity="0"/>
</Grid>

Which all works fine.
But what I want to be able to do is, when an item is selected (i.e. the Selected visual state) I want the TextBlock in the DataTemplate to change its Foreground color to Black instead of white and make the font size larger. But I cannot seem to find out a clean way of doing this as TemplateBinding does not seem to be available from a DataTemplate.
Any ideas?
Answer: If you want the template for the ItemContainer to control the Foreground you can set it there instead of inside the ItemTemplate. TextBlock.Foreground and TextBlock.FontSize can be used as attached properties and will inherit from a parent value:
<ContentPresenter TextBlock.Foreground="White" TextBlock.FontSize="18"/>

The settings for these properties will need to be removed from the ItemTemplate to avoid overriding the inherited values. You can then set whatever values you need from the VisualState animations.
Comment: That works! Thanks so much John, but as an extension to this, how can I then trigger the changing of these values in different visual states?
Comment: Actually you can :) I just found this blog by Charles http://www.charlespetzold.com/blog/2007/09/080231.html
Answer: Don't think the answer works anymore in current Silverlight versions, attached orpoerties on the ContentPresenter don't even build anymore. Anyone else figure this out?


The right distance for the clustering. Maybe Mahalanobis?

Question: I have to do a cluster analysis and I'm asking which distance should I used.
I know that 99% of the clustering are made using a euclidean distance, but I heard about the Mahalanobis distance and it seems to be better because it takes into account the covariance matrix of the data.
Question : Why the Mahalanobis distance isn't more used ?
For instance with this data (70% of the variance within these 2 Dim) :
The euclidean distance doesn't fit, so does the Mahalanobis distance can better fit ?
Edit : By the euclidean distance doesn't fit I mean the clusters which become apparent haven't a circle shape

Comment: `Why the Mahalanobis distance isn't more used?` In _most_ cases of clustering, using Mahalanobis in place of Euclidean is not much gain. Mahalanobis is Euclidean attuned to the ellipsoid shape of the data cloud. Ellipsoid or circular - the clusters _in_ the cloud can be any shape and orientation. I would be nice to use Mahalanobis _if_ one knew these characteristics (in a form of covariance matrix) for _each_ separate cluster. But you can't know it beforehand! Sooner than the clusters are discovered.
Comment: Ophelie, if shown above is the real data you want to cluster then I would bet there is hardly any clusters at all. If you don't mind apophenia just cluster as you did, by eye.
Comment: I don't have much to offer except that Mahalanobis distance basically measures the distance between group means. It's good for prediction which cluster a new data point will be in
Comment: I must agree with @ttnphns, I do not think these data are well-suited for clustering.
Answer: The distance measure you use for cluster analysis should depend on your data. For example, in Ecology we frequently use data on species presence/absence/abundance of ecological communities, and use distance (i.e., similarity) measures such as the Sorensen and Bray-Curtis measures.
There should not be anything specifically against using Mahalanobis distance. Euclidean distance may be the most intuitive to use, and perhaps for the field that you are in, it generally works well. However, it does not work well for all datasets. One thing you can do is try different distance measures and different clustering techniques, and compare cophenetic correlations across analyses to see what is showing the pattern best-supported by the data; also, look at the resulting clusters to see what makes sense and is explainable based on existing literature in your field.
Also, there is a relevant post on CrossValidated here - also, a google search for "non-euclidean distance cluster analysis" looks like it brings up some useful results.
Hope that helps a bit!
Comment: Another thing to consider is why you want to use cluster analysis - if you know the groups already, perhaps a classification analysis might be more informative? or a multivariate comparison to test for significant differences?
Comment: I don't already know the groups
Comment: Okay, then Cluster Analysis seems like it would make sense. I apologize - I thought you did since you circled the groups in your diagram, but now I see that you are identifying he patterns that you see through visual representation of the data.
Comment: Ok. But which distance should I used in this case for instance ?
Comment: The best distance measure depends on the data. If I were you, I would try doing the Cluster Analysis with a few different distance measures (at least Euclidean and Mahanalnobis), and see which are the most interpretable, and might be supported by the literature in your field. If you can post about the nature of your data, I or somebody else on here could help think of what distance measures might be most appropriate. Also, read up on the available distance measures in your stats package to see what might make the most sense also.
Comment: @Ophelie "I don't already know the groups" Yes but why do you think there are groups? It doesn't look like it. What is your data?
Comment: In real world data, we never have perfect distinct groups.
If we can't apply a clustering on this data we can't often perform a clustering.
Answer: Maybe have a look at  correlation clustering, which is meant to find clusters that have a non-spherical shape.
If you want to give Mahalanobis a try, note that Gaussian Mixture Model EM clustering does use Mahalanobis distance.


What's pupose for using the third [ ] in a 2D vector?

Question: vector<char>  T[3][4];  //this is a 2d vector table right?
vector<char> v;
for (int x = 0; x <3; x++)
{
  for (int y = 0; y <4; y++)
  {
    for (int z = 0; z <T[x][y].size(); z++) //T.[x][y].size() is the size of?
    {
      v.push_back(T[x][y][z]);  //Why we need use [z] for copying values in T to v?
    }                           //T is a 2D vector, it should only have two []'s, right?
  }
}

Hi,everyone. Here is a piece of C++ code wrote by my tutor, but I really confused about it. Please see the comment part in this code. Thank you in advance!
Answer: vector<char>  T[3][4];  //this is a 2d vector table right?
No, it is a 2D array of 1D vectors of char.
So in total it is 3D, which matches/supports the triple [] construct.
for (int z = 0; z <T[x][y].size(); z++) //T.[x][y].size() is the size of?
... the vector found at position x,y of the 2D array.
v.push_back(T[x][y][z]);  //Why we need use [z] for copying values in T to v?
What gets pushed to v is the content of index z in the vector found at the position x,y of the 2D array T.
Comment: Maybe you can phrase your new question like "I learned here () that this is a 2D array of 1D vectors. Now I wonder why it only gets initialised like ( show an MRE ) instead of ( describe what you expect )." Compare [mre].
Comment: Hi, Yunnosch. Thank you for helping me! Then I have two more questions.
1. If it's a 3D, why we initialize T only in two[ ]'s , but to copy it's value in 3 [ ]'s?
2.  Another piece of code:

       T[row][col].push_back(v[i])

//Why when we copy v into T, we use only 2[ ]'s, but we use 3 [ ]'s by copying T into v?
Comment: Creating actual new questions, instead of cramming them into comments on an answer, will give you the space you need to explain in detail what you mean. That will really help with getting good answers. Do not misunderstand please, I will be happy to look at your new questions. But "moving target" questions are simply not appreciated on StackOverflow. Have fun.
Comment: This really helps! Thanks a lot!
Comment: My pleasure. :-)


Circular Dependency in my SecurityConfig with Spring Boot

Question: I tried to create a simple login module with Spring Boot and Spring Boot Security.
One of the updates happens in creating SecurityConfig is some of classes like
WebSecurityConfigurerAdapter is now deprecated so I try the following code to make a SecurityConfig but unfortunately, I caught in a circular dependency.
Actually, I used Lombok to minimize the used of @Autowired in every field injection.
I tried the following approach:

I create another class for PasswordEncoder to avoid circular dependency if I used Password Encoder in the other parts of the Application.

Error Message.

Description:

The dependencies of some of the beans in the application context form a cycle:

┌──->──┐
|  securityConfig defined in file [C:\Users\jgeronimo\Documents\jp_geronimo\sample_projects\spring-security-tutorial\target\classes\com\workshop\application\config\SecurityConfig.class]
└──<-──┘

Action:

Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.

SecurityConfig.java
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthFilter jwtAuthFilter;

    private final JwtUserDetailsService userDetailsService;

    private final PasswordEncoder passwordEncoder;

    private final JwtAuthenticate jwtAuthenticate;

    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public JwtAuthenticate jwtAuthenticationEntryPointBean() throws Exception{
        return new JwtAuthenticate();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .cors().and().csrf().disable()
                .authorizeHttpRequests()
                .requestMatchers("/**/auth/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(jwtAuthenticate).and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        final DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return daoAuthenticationProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

Encoder.config
@Configuration
public class EncoderConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Comment: `SecurityConfig` depends on `JwtAuthenticate` bean, which is instantiated in `SecurityConfig`
Answer: The field JwtAuthenticate jwtAuthenticate is redundant - remove it.
And while constructing the SecurityFilterChain refer to the method producing JwtAuthenticate Bean:
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPointBean())

Comment: @JohnPauloA.Geronimo I almost certain that this apparent issue in not related to the cyclic dependency you've introduced. There's a little I can say about the cause from this chunk of exception message. You need to provide a **full** *exception stack-trace*, also *dependencies* in the `pom.xml` might contain a clue. I would advise to post a new Question with all the details related to the problem. That would allow you to draw and to collect opinions from a larger number of user (and you can share a link to the question here as well).
Comment: @JohnPauloA.Geronimo [`spring-boot-starter-security`](https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security/3.0.0) as well as any other `spring-boot-starter` dependency basically is a **group** of dependencies. `spring-boot-starter-security` includes `spring-security-web` and `spring-security-config` (which in turn comes with `sping-context` and `spring-core`). You can examine it though the link to repository (or by selecting dependencies in your `pom.xml`).
Comment: Thank you it removes the circular dependency but it creates new error:

Caused by: java.lang.ClassNotFoundException: org.springframework.security.core.context.DeferredSecurityContext
Comment: I already solved it by removing the spring-security-core and spring-security-web from the pom.xml. I just use spring-starter-security. Thank you very much sir. But may I know why spring-security-core and spring-security-web is not needed by spring?


Como converter variáveis numéricas para string?

Question: Eu tenho uma série de 45 variáveis do tipo numeric que representam as respostas certas ou erradas de um conjunto de alunos (são 45 questões ao todo) e gostaria de criar uma única string com as 45 respostas e gostaria de ter uma string Q_CN com todas elas concatenadas
alguém pode ajudar? o programa que eu uso é o SPSS da IBM
Answer: <code>STRING  Q_CN (A45).
COMPUTE Q_CN=CONCAT(VAR00001 TO VAR00045).
EXECUTE.
</code>


Recurrence Relation

Question: So I am just making sure I am on the right track with this.
I have the recurrence:
T(n) = 2T(n-2) + 1
I am trying to solve this recurrence to get the time complexity
T(n) = 2(2T(n-4) + 1) + 1
T(n) = 4(2T(n-6) + 1) + 3
…
T(k) = 2^k T(n-2*k) 2^k -1
Am I on the correct path so far? Where do I go from here how do I find the time complexity. Please explain it and don't just give me an answer I really want to understand / think in the right way to get to the solution.
Answer: First of all, in order to solve this explicitly you will need to know what $T(0)$ and $T(1)$ are.
There are two reasonable approaches: first, you can just write down $T(k)$ for, say, $k$ from $1$ to $10$, see what the pattern is, and move on from there.
Second, you can use generating functions: define $f = \sum_{i=0}^\infty T(i)x^i$; then your recurrence gives
$$f = T(0) + T(1)x + \sum_{i=2}^\infty (2T(i-2)-1)x^i.$$
You can rewrite this in such a way that you get $f$ on the right-hand side as well (I'm being vague here because you said you wanted to work it out for yourself); solving for $f$ will give you an explicit formula for $f$ as a function of $x$. Then $T(n)$ is just the coefficient of $x^n$ in the corresponding power series.

Recurrence Relation


Why do my Ruby / Sinatra methods not print all the strings to the screen?

Question: I am programming a game in my spare time for fun and to try to show off my knowledge to my teachers. When I call this method in sinatra, it knows how many hits you chose if it is more than 2 it will only add 1 hit to your acid amount, then tell you how much it added . However if you choose more than 2 hits it should also tell you you can only start with 1 or 2 and the message stating that. However its not showing the first message or the second one. it just tells the message stating either 1 or 2 hits was added . any ideas on why or how to fix it?
My back-end
class Trippy_methods

def start_with_amount(hits)
    "You wanna start with 1 or 2 hits?"
@acid_amount = 0

    if hits == 2
         @acid_amount += 2
    else @acid_amount += 1
        "You may only start with 1 or 2 Hits...Ill give you the 1 hit for now. Don't Worry you will get more as time progresses  "
    end
        "You Started off with taking #{@acid_amount} hits of acid....Enjoy"
end
end

In my front-end
post '/stick_out_tounge' do
tounge = params[:tounge]
name = session[:name]
session[:hits] = params[:hits]
hits = session[:hits].to_i
  if tounge == "Yes"
    erb :stick_out_your_tounge, :locals => {:yes => you_say.ok_to_acid, :places => trippy_messages.places_acid_on_tounge, :leave => trippy_messages.dosed_now_leave?,
                                            :start_amount => trippy_methods.start_with_amount(hits) }

elsif tounge == "No"
    erb :chillathome2, :locals => {:message1 => "You Say \" Gee I don't know man why what is it ?......\"",
                                   :stick_out_tounge => "Dave says to you... \"Hey #{session[:name]} if you need to know than it wont be as fun..... \"",
                                   :doyou => "Do you still wanna know what it is ?"}
end
end

Comment: You need to pass the strings to the view layer.
Comment: The back end has random strings inserted in the source that do nothing except evaluate. Is that on purpose?
Comment: Yes those are the messages that I want it display if that condition is met, and the first string is the start message to ask how much you want
Comment: and it works perfectly fine in irb if i include puts , which i cant in sinatra
Answer: Methods in ruby always return the last evaluated expression. So, in your example you have
def start_with_amount(hits)
  "You wanna start with 1 or 2 hits?"
  @acid_amount = 0

  if hits == 2
    @acid_amount += 2
  else @acid_amount += 1
    "You may only start with 1 or 2 Hits...Ill give you the 1 hit for now. Don't Worry you will get more as time progresses  "
  end
  "You Started off with taking #{@acid_amount} hits of acid....Enjoy" # <- This is the last evaluated expression.
end

So no matter what the method does, it will always return "You Started off with taking #{@acid_amount} hits of acid....Enjoy"
The solution is to move ""You wanna start with 1 or 2 hits?" out of the method, and send it to the view separately, and display it before the user selects how many hits they want.
To fix the other message no displaying, you need to fix your conditions.
def start_with_amount(hits)
  @acid_amount = 0
  result = "You Started off with taking #{@acid_amount} hits of acid....Enjoy"
  if hits == 2
    @acid_amount += 2
  elsif hits == 1
    @acid_amount += 1
  else
    result = "You may only start with 1 or 2 Hits...Ill give you the 1 hit for now. Don't Worry you will get more as time progresses  "
  end
  result
end

Comment: Thanks I kinda went a little bit of a different I ended up taking out the strings and just putting them in to a method by themselves and just called the method need  when i needed to display that string, but I like this better.


Use decision tree to learn precise classification rules: need accuracy of 1

Question: I'm trying to use a decision tree algorithm to learn how general ledger transactions (10 digit code) are classified into revenue, expense, G&A et cetera without actually scripting every combination. There are general rules in our accounting software, and each digit of the 10-digit code has a specific meaning.
There are about ~6000 used combinations of these 10 digits, but only 6 to 9 categories that I want to classify them into. The rules are precise and there is no ambiguity, there are no outliers (e.g. if the 1st digit = 3, then it is revenue; if 2nd digit = 4 and 4th digit = 8 then it is cost of sale. And so on). By knowing which digits to check, one can write a compact if else set of statements.
I am using an rpart decision tree in R to get the rules, which I'm planning to then put into a CASE WHEN SQL statement.
My problem is that the rpart algorithm is good, but it is not 100% precise. It drops a few smaller sized categories, and misses a few times.

How do I adjust the arguments of rpart (or use a different function and/or a different package, e.g. caret) to get a decision tree with an accuracy of 1?
Thank you!
Comment: So basically you are asking how to force decision tree to overfit?
Comment: It seems that you found out how to disable the pruning in your decision tree function. You still need to be careful that your training set contains all possible combinations if you want to be sure to have accuracy 1.
Answer: I'm not sure, but does setting the cp parameter in rpart to a negative value (let's say, -1) work? Also try setting the minsplit parameter to 2.

The complexity parameter (with default value of 0.01) is there to prune the tree of nodes that would not decrease overall lack of fit by a factor of cp. By setting it to -1 you're telling it that you want it to be as precise as possible. In your case overfitting is actually desirable.
Minsplit (with default value of 20) is the lowest amount of observations in a node at which split is attempted.

Let us know if it solved the problem completely or is there something more to it.
Comment: @gung :This was my first answer on the site and I tried to cut to the chase as fast as possible, because the question was rather simple. I understand that even now after the edit, the answer does not provide as much information as other beautiful answers i have seen from many users of stackexchange. Next time I'll try to explain it better right away.
Comment: Don't take it too hard, @ExabytE. I appreciate your efforts here. Thanks again.
Comment: It worked! I think... I will validate tomorrow, but my tree just expanded!
Comment: I definitely got what I needed. I wasn't aware of the cf argument, and setting it to -1 solved the issue, as I wanted to overfit.

Now my task to to gather all of these branches into a concise `CASE WHEN` statement
Comment: @Taraas chechout the rpart.utils package that should do just what you want.


Why is success block being called with incorrect path?

Question: I accidentally mistyped the post path and noticed that although it's being wrong, the success block is called:
[[APIClient sharedInstance]
 postPath:@"api_url"
 parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSLog(@"Result: Success %@",[responseObject description]);

 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //handle error
     NSLog(@"Result: Failure + %@",error.userInfo);

  }];

Of course the data are not being sent to server and the transaction is not processed, but I want to know why it's not the failure block which is supposed to be called in case the path is wrong? Thanx.
Comment: Well it depends on the error you made... maybe the request in itself worked and returned an error message as an http 200 response
Comment: Hi, but how can the request reach the server while the path itself is wrong!!!
Comment: It may be that some kind of http errors, if not all, are considered "success", while failure is only for "server not answering". I don't know where exactly you were wrong in your path though. Have you tried hitting the wrong path from your browser (although this is a get and not a post...) ?
Answer: Failure is called if the requestOperation has an associated error after finishing. Reasons for an error include the response having the incorrect Content-Type, not having an acceptable status code (2XX range, by default), or an error processing the downloaded data.
Why your server returned a 200 response with the correct content type is a question only something you can determine.


Number translation with 118n module

Question: I have developed a multi-lingual site with i18n module (7.x-1.13) and everything works as expected.My Drupal version is 7.34.
Recently, my client have asked not to translate the number. The website works in English and Arabic.
To be more specific, when Arabic is chosen, we do not want the numbers to be displayed in Arabic, instead we need to display the same in English. Now, each numbers are translated to Arabic when the language is chosen as Arabic, even the user input.
The default language is Arabic and I haven't installed any modules for translation of numbers.
Any help would be much appreciated.
Answer: You can use PersianTools modules,
Features

This module is going to cover some basic features required for Persian
websites.
Fix possible misplaced chars in mixed Persian and English texts
Find a way to fix Calendar.
Convert English numbers to Persian numbers.
Fix sort issues for persian characters.

One of its features is Convert English numbers to Persian numbers. ( indeed Persian number is Arabic digits ).
Install this module and go to its settings and just active convert digits.
Also you can convert all Latin digits to Arabic with some Js code.
Try something like this (put it in custom JS file and load in each page_
String.prototype.toIndiaDigits= function(){
  var id= ['list of arabic digits'];
 return this.replace(/[0-9]/g, function(w){
  return id[+w]
 });
}
var content= $('body').html();
$('body').html(content.toIndiaDigits());

See this articles about how change Latin digits to Arabic
https://stackoverflow.com/questions/1675786/convert-from-english-digits-to-arabic-ones-in-html-page
https://stackoverflow.com/questions/21415121/convert-english-digits-to-arabic-digits-in-html-documents
http://jsfiddle.net/McxL5/
Answer: Thanks for the solution. But, the main problem was with the font that I was using when Arabic is loaded. This made the English numeric digits to convert to Arabic automatically.
I have now made the same font to be loaded in both the languages.
This solved my problem.

Number translation with 118n module


let U be a set which is both closed and open

Question: prove or disprove
Let (X,T ) be a topological space and let U be a set that is both closed and open. Then Int(Cl(U)) = Cl(Int(U)).
I think it is true statement ,I am stuck on "let U be a set that is both closed and open" I do not know what means exactly and does it affect my prove ?
my proof
since U is both open and closed then Cl(U)=U and Int(U)=U
Hence ,Int(U) = Cl(U)=U.
Is it right ?
Comment: Yes, that's right
Comment: You have only shown that $\operatorname{Int}(U) = \operatorname{Cl}(U)$, not that $\operatorname{Int}(\operatorname{Cl}(U)) = \operatorname{Cl}(\operatorname{Int}(U))$.
Comment: because Cl(U)=U and Int(U)=U
Answer: It indeed means that $U$ is open and $U$ is closed as well. This can surely happen for some sets $U$ ("sets are not doors, they can be open and closed at the same time", as a teacher of mine once said).
So indeed $\operatorname{Int}(U) = U = \operatorname{Cl}(U)$ for this $U$ and so indeed $\operatorname{Int}(\operatorname{Cl}(U)) = \operatorname{Int}(U) = U$ an similarly for the other order. There is no more to it than that.


Suppose every subsequence of X converges to 0. Show that lim(X)=0

Question:
Question: Suppose that every subsequences of $X = (x_n)$ has a subsequence that converges to $0$. Show that $\lim(X) = 0$

My attempt:
Suppose that $\lim(X) =L \neq 0$
Let $\epsilon > 0$, and let $K(\epsilon)$ be s.t. $n \ge K(\epsilon)$
then $|x_n-L| < \epsilon$
let $n_k \ge k$, and then $k \ge K(\epsilon)$ and $n_k \ge k \ge K(\epsilon)$ s.t. $|x_{n_{k}}-L| < \epsilon$, which is a contradiction. therefore $\lim(x) =0$
Comment: Your sequence can fail to converge to 0 without converging to something else. It may not converge to anything at all.
Answer: Right when you say let $\lim X = L$ you've already assumed that $X$ has a limit. A priori, you can't just assume this. It may very well be that $X$ doesn't converge. The way to do this is by contradiction, assume that we don't have $\lim X = 0$. Then for some $\epsilon > 0$, we have the following: for any $k \in \mathbb N$, there is an $n_k \ge k$ such that $\|x_{n_k} \| \ge \epsilon$. Without loss of generality, $n_k$ is an increasing sequence (indeed, after finding $n_1$, there must be $n_2 > n_1$ with $\| x_{n_2} \| \ge \epsilon$ and then there must be $n_3 > n_2$, etc). Now we have assumed that every subsequence of $X$ converges to 0. However, we have constructed a subsequence which is always larger than $\epsilon$ in absolute value. This subsequence cannot converge to 0, a contradiction. Hence our original assumption was incorrect, and so we must have $\lim X = 0$.