What is the difference between circuit satisfiability and q-sat?

Question: Also, why is QSat PSPACE-Complete and Circuit Satisfiability NP-Complete? Aren't they the same thing?
Answer: QSAT is the problem relating to TQBF (true quantity Boolean formulae). These formula have their variables bound at the very beginning. If the formula evaluated to true or false then the formula is a in the language of TQBF. If it is PSPACE-complete then the language resides in PSPACE and it is also PSPACE-hard. Using a recursive algorithm to determine the evaluation of the formula (depending if it has quantifiers or not) will tell you if those statements are true. By showing it is PSPACE-hard you show that the language must be reducible to TQBF in polynomial time.
The CSAT problem is the problem regarding the decision problem of determining if a Boolean circuit has a set of inputs that evaluate, in terms of the output, to true. It is proven to be NP-complete as it is in NP space and is reducible in polynomial time.
QSAT evaluation of its space classing and also its reduction time is determined without regard to the state of the output (true or false), solving the recursive algorithm is determined by whether the formula has no quantifiers (thus returning the formula) or checking both possible values for the first variable (if it has quantifiers). This evaluation is for the amount of memory space required to solve it, specifically logarithmic space. CSAT is evaluated based on the output state (true being the solvable one in this case) and as such is determined not by spacial requirement but by total reduction time. Specifically containing n arbitrary gates, it can be decided in O(2^0.4058n).


Make Strawberry Shake request from Blazor with or without credentials

Question: In my Blazor app (which uses Azure B2C), I want to be able to call an endpoint whether the user is authenticated or not.
I've searched quite a bit, and everything I find says I should create two HttpClients (example), one for anonymous and one for authenticated, or use IHttpClientFactory with named clients.
The problem is I am using Strawberry Shake which only allows me to configure HttpClient once (it is using a named client and IHttpClientFactory internally).
Their documentation gives a simple example of setting authentication:
services
    .AddConferenceClient()
    .ConfigureHttpClient((serviceProvider, client) =>
    {
        var token = serviceProvider.GetRequiredService<ISomeService>().Token;
    });

I thought I could use this to conditionally select which handler(s) I wanted, but the only ways I can find to get the token (IAccessTokenProvider.RequestAccessToken()) or validate authentication (Task<AuthenticationState>) require async calls, which are not allowed in this context. Even .Result doesn't work (not that I wanted to use it anyway).
My last thought is that maybe I could accomplish this by inheriting from BaseAddressAuthorizationMessageHandler or chaining handlers, but I can't figure out how. I even tried copying the source code and modifying it, but still couldn't get it to work (UPDATE: Actually, that did work, but it still seems less than ideal).
So many approaches seem workable, but ultimately fail me. How can I get this to work? Please provide code example if possible.
Answer: It's a bit old question already but I encountered the same issue and couldn't find any proper solution.
I was able to make it work, by registering the GraphQL client and custom AuthorizationMessageHandler like this:
builder.Services.TryAddTransient<GraphQlAuthorizationMessageHandler>();
builder.Services
    .AddConferenceClient()
    .ConfigureHttpClient(client =>
    {
        client.BaseAddress = new Uri("http://localhost:5000/graphql");
    },
    configureClientBuilder =>
    {
        configureClientBuilder.AddHttpMessageHandler<GraphQlAuthorizationMessageHandler>();
    });

Where my GraphQlAuthorizationMessageHandler is simply:
public sealed class GraphQlAuthorizationMessageHandler : AuthorizationMessageHandler
{
    public GraphQlAuthorizationMessageHandler(IAccessTokenProvider provider, NavigationManager navigation)
        : base(provider, navigation)
    {
        base.ConfigureHandler(new [] {"http://localhost:5000/graphql" });
    }
}

It works because the existing AuthorizationMessageHandler (github) class already contains the logic that adds the token to the Authorization header. The only requirement to make it work is to configure the handler with the URLs for which we want it to inject the header.
EDIT:
If you would like to handle both authenticated and unauthenticated users then it will require a little bit more code.
Simply overriding AuthorizationMessageHandler will not work and you will need to implement your own handler.
As an example, I based my handler on AuthorizationMessageHandler with the required changes to make it work also for unauthenticated user - in such case, it will not inject the authorization header.
You can implement your own custom logic inside SendAsync if you would like to add additional checks or maybe use a separate service for providing the authentication state.

public sealed class GraphQlAuthorizationMessageHandlerSettings
{
    public IEnumerable<string> AuthorizedUrls { get; set; } = null!;
    public IEnumerable<string>? Scopes { get; set; }
    public string RedirectUri { get; set; }
}

///
/// Entirely based on AuthorizationMessageHandler from Microsoft.AspNetCore.Components.WebAssembly.Authentication
/// src: https://github.com/dotnet/aspnetcore/blob/main/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs
///
public sealed class GraphQlAuthorizationMessageHandler : DelegatingHandler, IDisposable
{
    private readonly IAccessTokenProvider _provider;
    private readonly AuthenticationStateChangedHandler _authenticationStateChangedHandler;
    private AccessToken _lastToken;
    private AuthenticationHeaderValue _cachedHeader;
    private Uri[] _authorizedUris;
    private AccessTokenRequestOptions _tokenOptions;

    ///
    /// Initializes a new instance of <see cref="AuthorizationMessageHandler"/>.
    ///
    /// <param name="provider">The <see cref="IAccessTokenProvider"/> to use for provisioning tokens.</param>
    /// <param name="navigation">The <see cref="NavigationManager"/> to use for performing redirections.</param>
    public GraphQlAuthorizationMessageHandler(
        IAccessTokenProvider provider,
        NavigationManager navigation,
        IOptions<GraphQlAuthorizationMessageHandlerSettings> configuration)
    {
        _provider = provider;

        // Invalidate the cached _lastToken when the authentication state changes
        if (_provider is AuthenticationStateProvider authStateProvider)
        {
            _authenticationStateChangedHandler = _ => { _lastToken = null; };
            authStateProvider.AuthenticationStateChanged += _authenticationStateChangedHandler;
        }

        ConfigureHandler(configuration.Value.AuthorizedUrls, configuration.Value.Scopes, configuration.Value.RedirectUri);
    }

    /// <inheritdoc />
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var now = DateTimeOffset.Now;
        if (_authorizedUris == null)
        {
            throw new InvalidOperationException($"The '{nameof(AuthorizationMessageHandler)}' is not configured. " +
                $"Call '{nameof(AuthorizationMessageHandler.ConfigureHandler)}' and provide a list of endpoint urls to attach the token to.");
        }

        bool userAuthenticated = false;
        // check if user is authenticated
        if (_provider is AuthenticationStateProvider authStateProvider)
        {
            userAuthenticated = (await authStateProvider.GetAuthenticationStateAsync()).User.Identity?.IsAuthenticated == true;
        }

        if (userAuthenticated && _authorizedUris.Any(uri => uri.IsBaseOf(request.RequestUri)))
        {
            if (_lastToken == null || now >= _lastToken.Expires.AddMinutes(-5))
            {
                var tokenResult = _tokenOptions != null ?
                    await _provider.RequestAccessToken(_tokenOptions) :
                    await _provider.RequestAccessToken();

                if (tokenResult.TryGetToken(out var token))
                {
                    _lastToken = token;
                    _cachedHeader = new AuthenticationHeaderValue("Bearer", _lastToken.Value);
                }
                else
                {
                    Console.WriteLine("Failed to get token");
                }
            }

            // We don't try to handle 401s and retry the request with a new token automatically since that would mean we need to copy the request
            // headers and buffer the body and we expect that the user instead handles the 401s. (Also, we can't really handle all 401s as we might
            // not be able to provision a token without user interaction).
            request.Headers.Authorization = _cachedHeader;
        }

        return await base.SendAsync(request, cancellationToken);
    }

    ///
    /// Configures this handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of
    /// <paramref name="authorizedUrls" /> is a base of <see cref="HttpRequestMessage.RequestUri" />.
    ///
    /// <param name="authorizedUrls">The base addresses of endpoint URLs to which the token will be attached.</param>
    /// <param name="scopes">The list of scopes to use when requesting an access token.</param>
    /// <param name="returnUrl">The return URL to use in case there is an issue provisioning the token and a redirection to the
    /// identity provider is necessary.
    /// </param>
    /// <returns>This <see cref="AuthorizationMessageHandler"/>.</returns>
    public GraphQlAuthorizationMessageHandler ConfigureHandler(
        IEnumerable<string> authorizedUrls,
        IEnumerable<string> scopes = null,
        string returnUrl = null)
    {
        if (_authorizedUris != null)
        {
            throw new InvalidOperationException("Handler already configured.");
        }

        if (authorizedUrls == null)
        {
            throw new ArgumentNullException(nameof(authorizedUrls));
        }

        var uris = authorizedUrls.Select(uri => new Uri(uri, UriKind.Absolute)).ToArray();
        if (uris.Length == 0)
        {
            throw new ArgumentException("At least one URL must be configured.", nameof(authorizedUrls));
        }

        _authorizedUris = uris;
        var scopesList = scopes?.ToArray();
        if (scopesList != null || returnUrl != null)
        {
            _tokenOptions = new AccessTokenRequestOptions
            {
                Scopes = scopesList,
                ReturnUrl = returnUrl
            };
        }

        return this;
    }

    void IDisposable.Dispose()
    {
        if (_provider is AuthenticationStateProvider authStateProvider)
        {
            authStateProvider.AuthenticationStateChanged -= _authenticationStateChangedHandler;
        }
        Dispose(disposing: true);
    }
}

Now the ConfigureHandler method is called from within the constructor so it is needed also to Configure the new options like that:
builder.Services.Configure<GraphQlAuthorizationMessageHandlerSettings>(config =>
{
    config.AuthorizedUrls = new [] { "http://localhost:5000/graphql" };
});

Comment: But how does it work for unauthenticated users?
Comment: @DanFriedman You are right, it only works for authenticated. For unauthenticated users, there is a need to add a lot of boilerplate code. I added an example of a handler based on the existing AuthorizationMessageHandler. It's not an ideal solution, but I couldn't see a better way of doing this with the current implementation of DelegationHandler and Request pipeline.


O que é um SDK?

Question: Até pouco tempo atrás, eu sempre via SDK como algo relacionado ao universo do Android. Porém tenho percebido algumas bibliotecas PHP que também usam o nome SDK.
Por exemplo:

pagseguro-php-sdk
facebook/graph-sdk

Mas afinal, o que seria um SDK?
Por que nos casos acima, não chamar o SDK de biblioteca? Teria alguma diferença?
O termo SDK pode variar do Android para outras linguagens, ou vice-versa?
Comment: O SDK pode incluir uma IDE. Não significa que vai. SDKs de softhouses incluem até mesmo hardware. É uma definição mais abstrata. Tem mais haver com as ferramentas, do que tipo de ferramentas elas serão.
Comment: SDK (como o próprio nome indica ) é um kit de desenvolvimento completo. Pode incluir a IDE, exemplos de código, drives, etc.
Já biblioteca é conjunto de implementação rotineiras. Uma forma de reaproveitamento de código (dentre muitas)
Comment: @PauloSérgioDuff não faz sentido para PHP... No caso, a *biblioteca* do PagSeguro por exemplo não inclui uma IDE :p
Comment: https://pt.wikipedia.org/wiki/Kit_de_desenvolvimento_de_software
Comment: @ArmandoMarquesSobrinho a pobre explicação do Wikipédia não fala nada sobre PHP :\
Comment: SDKs mais completas são mais comuns em sistemas embarcados e linguagens compiladas. Tem muita gente que acha que PHP só faz site.
Comment: Talvez caia aqui => http://pt.stackoverflow.com/q/17501/91
Comment: @rray de fato tem SDK na resposta
Comment: @rray eu até pensei em não perguntar por conta dessa, mas o que complicou foi o "SDK costuma vir com IDE e afins", sendo que em PHP isso não é verdade :p
Comment: Da uma lida nesse link [*Aqui*](https://aws.amazon.com/pt/sdk-for-php/) talvez você encontre oque esta procurando.
Comment: Creio que quase qualquer resposta aqui vai estar correta, creio que um kit de desenvolvimento de software pode ser qualquer coisa que seja usado completamente para desenvolver outras aplicações ou funcionalidades sem depender de quase mais nada, como o Bacco me disse, é um nome genérico.
Comment: pobre, @WallaceMaxters? kkkkkk, é miserável, rerere
Comment: @ArmandoMarquesSobrinho é que o Wiki costuma ter mais detalhamento. Dessa vez, esse artigo tá pequenininho... E não responderia diretamente a pergunta do PHP :p
Answer:
Mas afinal o que seria uma SDK?

Software Development Kits podem assumir a forma de toolkits ou de frameworks e fornecem tudo o que precisa para programar em cima de uma plataforma (sistema operacional, banco de dados, aplicação, etc.). Estes kits costumam englobar:

ferramentas adicionais que ajudam certas tarefas além das bibliotecas,
documentação e exemplos de códigos que ajudam a usar a biblioteca adequadamente.

Referência: Qual é a diferença de API, biblioteca e framework?

Por que nos casos acima, não chamar a SDK de biblioteca? Teria alguma diferença?

No link acima tem a diferença do SDK e da biblioteca. A biblioteca é só uma uma coleção de algoritmos, o SDK é um conjunto de ferramentas entre elas a(s) biblioteca(s).

O termo SDK pode variar do Android para outras linguagens, ou vice-versa?

Android não é uma linguagem, é uma plataforma. SDK é o SDK, como cada um funciona é problema de cada plataforma. É possível ter SDKs diferentes para cada linguagem ou o SDK pode conter capacidade de lidar com várias linguagens.
Oficialmente é isso. Claro que sempre é possível alguém inventar um termo novo, usar este mesmo termo para outra coisa. Não podemos olhar para o uso errado para fazer uma definição.
Wikipedia.
Coloquei no GitHub para referência futura.
Answer: TL;DR: Uma biblioteca pode fazer parte de um SDK mas nem todo SDK é apenas uma biblioteca.
Um SDK é como um baú. Dentro de uma SDK você vai encontrar, no geral, diversos itens. Por exemplo:

Bibliotecas
Documentação
Exemplos de uso de código; e, em alguns casos,
IDEs

Entre outras coisas, o propósito da SDK (Kit do Desenvolvedor de Software, em tradução livre) é garantir que você já tenha tudo pronto pra desenvolver/implementar/estender a aplicação cujo SDK você baixou.
Por exemplo, o SDK do Android inclui:

Android Studio
Documentação
Emulador do Android
Exemplos e tutoriais

Alguns outros termos que geralmente são associados:
API
Uma API é uma interface usada para interagir com uma biblioteca ou com um sistema. Quando você faz uso de um SDK, você vai, muito provavelmente, estar também fazendo uso de uma API do sistema em questão.
Bibliotecas
Bibliotecas são conjuntos de funções e/ou classes que estendem a funcionalidade do seu programa.
Answer: Creio que todas respostas estão quase inteiramente corretas, isso porque SDK do ponto de vista pode ser quase qualquer coisa, não que basta você dizer "isso é um SDK" para ele se tornar algo assim.
Pelo que andei observando o SDK não necessariamente precisa de um IDE, ou ferramenta completa e pronta, o PHP é uma linguagem voltada para servidor e ocasionalmente para CLI, ou seja, pode-se editar seus documentos em qualquer editor e pelo que entendi com os exemplos citados tanto na pergunta quanto nas demais respostas é que SDK deverá ser um "kit" completo para desenvolver na plataforma especifica, então se é possível com estes repositórios "desenvolver" a sua aplicação (independente de qualquer coisa extra) para o PHP especificamente, então sim, estes repositórios são SDKs.
Claro que para poder desenvolver completamente, no caso do pagseguro-sdk, me parece que ele contem um simulador do pagseguro junto as bibliotecas, escrito em PHP mesmo (https://github.com/pagseguro/pagseguro-php-sdk/tree/master/public).
Outra coisa que notei no repositório do facebook-sdk é que eles tem a pasta docs (https://github.com/facebook/php-graph-sdk/tree/5.4/docs), nela contém a documentação, não vejo como obrigatório para um SDK, creio que isto também deva definir um SDK escrito em PHP, pois o tornará independente de fontes onlines.
Conclusão
Não quer dizer que são de fato bons SDKs, ou que para estes repositórios o termo SDK vai se encaixar bem, mas é bem provável que para algo ser um SDK na plataforma especificada ele vai precisar de algo no minimo como:

Biblioteca completa ou software
Documentação (seria opcional se tiver fontes acessíveis externas)
Esta biblioteca tem que funcionar quase independente de qualquer coisa (na plataforma especificada, no caso PHP)

Sendo assim, na linguagem PHP o software que o pagseguro-sdk e o facebook-sdk dependem são unicamente de suas próprias bibliotecas para o desenvolvimento, ou seja as bibliotecas e as coisas adicionais são o seu Kit de desenvolvimento de software (SDK), então um SDK pode incluir qualquer coisa, desde que sirva de "ferramenta" para o desenvolvimento na tal plataforma.
Pontos que gerariam o contra da conclusão

Pagseguro não tem documentação junto:

Eu diria que é uma boa biblioteca, mas não um bom SDK

Facebook depende de conexão com a internet e usar no minimo o sandbox (creio eu):

Talvez simular tudo que o facebook faz não seja tão fácil ainda, não estou certo se tem como simular.

Ambas dependem do PHP para executar os scripts:

No Android SDK é necessário Java para rodar, no Microsoft SDK é necessário o Windows para rodar, tudo tem alguma dependência, por isto eu disse "quase independente".
Answer: SDK é a sigla para Software Development Kit (ou Software Developers Kit – pacote de desenvolvimento de software). É esse pacote que permite à programadores elaborarem aplicativos para rodarem em uma plataforma específica como Facebook, Android, IOS, Windows e outras plataforma.
SDK facilitam a integração com os recursos da plataforma escolhida.
Answer: SDK, ou "source development kit", é:

um framework proprietário, que é tornado público
o propósito é o de que utilizadores externos possam contribuir para o desenvolvimento de uma plataforma.
permite por norma integrar serviços daquela plataforma especifica

Exemplos de SDK:

Android SDK, (Google -> android)
UBUNTU SDK, (UBUNTU)

O que é um SDK?


Variáveis e o *ngFor não funcionam no Html - Angular

Question: Pessoal quando quero usar o *ngFor="let animal of produtos">
no html no meu projeto angular não funciona não da para usar e as variáveis dentro do {{}} também não funcionam !
CÓDIGO HTML

Produtos:

      Nome: {{ animal.name }} - tipo: {{ animal.type }}
      <button (click)="showAge(animal)">Show Age</button>
      <button (click)="removeAnimal(animal)">Excluir</button>

{{ animalDetails }}

Como mostra a imagem ele não funciona diferente da video aula que estou acompanhando!
inserir a descrição da imagem aqui
imagem da video aula:
inserir a descrição da imagem aqui
Comment: A única coisa que está diferente é de **`of animals`** para **`of produtos`**. Só podemos ajudar com esta informação!
Answer: Veja se o array dentro do seu typescript que você quer percorrer com o *ngFor está com o nome correto. No vídeo mostra como animals você usou produtos, a variável que vc chama no html e no typescript precisam possuir o mesmo nome. Se isso não resolver pode ser a importação do CommonModule.
Para utilizar *ngIf, *ngFor e outras diretivas nativas do Angular você precisa fazer a importação do módulo nativo CommonModule dentro do módulo onde seu componente foi declarado.
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    MeuComponenteComponent
  ]
})

export class MeuModuloModule { }

Certifique-se que fez a importação, esse tipo de problema não emite erro então pode passar despercebido mesmo.


Function after d in integral

Question: How do you interpret this?
$$\int[y-f(x, c)] \text{d}g(x,y)$$
I only saw things such as $\text{d}x\text{d}y$? But here a function ($g$) is after $\text{d}$. c is a constant.
Answer: In general,
$$dg(x,y)=\frac{\partial g}{\partial x}(x,y)dx+ \frac{\partial g}{\partial y}(x,y)dy$$
Comment: And how should I calculate the primitive function for the above integral then? Or what does it mean intuitively? 2 dimensional integrals can be thougt of as volumes for example but what does this integral mean?
Comment: You can't really say anything about a primitive without knowing exactly what $f$ and $g$ are. I also can't comment on what it means other than going back to the definition of an integral. Certainly an integral need not represent a volume. Perhaps the source where you found it has some explanation.
Comment: I'm on a phone so I can't link articles, but perhaps you should look at the Wikipedia article on differential forms
Answer: This seems an instance of the Riemann-Stieltjes integral, in two variables. Primitives of functions are not related to the specific kind of integral that you're dealing with. What happens is that if the function satisfies enough differentiability conditions, then we have results relating the derivative with said integral (e.g., the fundamental theorem of calculus for Riemann and Lebesgue integrals). That being said, everywhere I saw, people only computed definite Riemann-Stieltjes integrals.

Function after d in integral


Proof that a multiplication verification can be done in log space

Question: In Sipser's Introduction to Theory of Computation, he asks us to show that the language $MULT=\{(a,b,c):ab=c\}$ with $a,b,c\in\mathbb{Z}^+$ can be decided in log space.
I originally started out with a variant of the grade school long division algorithm: take the first few bits of $c$ and divide it by $a$ via repeated subtraction, and verify that you get the first digit of $b$. Wipe the slate clean and continue with the second, third,... digit.
If $a$ has $\log |c|$ digits I think this will run in log space, but there is no guarantee of that that I can see. (I may be confusing myself here, but I think this would require $\log a = \log\log c$, or $a=\log c$, which can fail if e.g. $a=b=\sqrt{c}$.)
Any hints?
Comment: There is a nice explanation here: https://www.mtholyoke.edu/courses/barring/341/lecture/7.htm
Answer: Why not use grade-school long multiplication instead? You can compute any digit of a 1-by-$|b|$ digit multiplication in logarithmic space, and then you can also sum the $|a|$ staggered multiples of $b$ in logarithmic space. The only mildly non-trivial part of the latter is seeing that you can represent the sum of each column, plus the carry from the previous column, in $O(\log |a|)$ space.


Weighted entropy as a measure of diversity

Question: Suppose that you are a company manager and you are looking for a statistical measure that defines the international reputation of your company. So, you collect data on your clients and the countries they come from.
You want this measure to have the following properties:

The larger the number of countries where your client come from, the more your company is international.
If all of your clients are from a single country, i.e., the number of countries is 1, your international reputation should be the lowest value (let's say 0 for convenience).
Unfortunately, you have to discriminate between the countries on your client list. For business reasons, you prefer to have more clients from high-income countries and fewer clients from low-income countries and there are countries that you can't deal with because of sanctions, embargoes or similar reasons.

Let's say you have the following data:

$n_i$: The number of clients from the i-th country.
$p_i$: The fraction of your clients that come from the i-th country.
$w_i$: The desirability of dealing with clients from the i-th country.
$N$: The sum of $n_i$'s. i.e. the number of countries.

I am currently reading about Rényi entropy as a potential method. Rényi entropy of order $q$ is given by the formula
$$^qH = \frac{1}{1-q} \ln\left(\sum_{i=1}^{N}p_i^q\right)$$
And I'm thinking of modifying it to a new formula taking "desirability coefficients" $w_i$ into account. My suggestion is this:
$$^qH = \frac{1}{1-q} \ln\left(\sum_{i=1}^{N}w_ip_i^q\right)$$
Do you think this is a valid method? Are there any better methods or suggestions available?
UPDATE:
One way to take the desirability of trade into account is to update the probabilities in this way:
$$\tilde p_i = \frac{w_i\cdot n_i}{\sum_{i=1}^N(w_i \cdot n_i)}$$
But I'm not sure if this actually works. How can I know that it's a good choice?
Comment: For weighting probabilities there's much more choices (often argued as better) than weighted mean, e.g. weighted geometric mean: https://stats.stackexchange.com/questions/155817/combining-probabilities-information-from-different-sources/188554#188554
Answer: You want some effective formula, so there is a lot of freedom you can do.
For rescaling I would do something slightly different:
$$ \tilde{p}_i = \frac{w_i p_i}{\sum_i w_i p_i} $$
where $\tilde{p}_i$ is the estimated percent of money coming from country $i$. So that if e.g. Germans pay twice as much as Poles, you weight them twice as much.
Then you can use $H_q(\{\tilde{p}_i\})$.
BTW: For communicating results I would rather use some diversity index (see https://stats.stackexchange.com/a/135153/6552 or https://stats.stackexchange.com/a/144235/6552). Then you can say something like "we have money coming from effectively 3.4 countries".
Comment: What do you mean by saying that something is interpretable as probability? What is a probability?
Comment: @H.Z. https://en.wikipedia.org/wiki/Probability W.g. tomorrow is going to be raining with probability 40%.
Comment: Well, mathematically speaking, the probabilities sum to 1 and there's no obstacle. But I am not sure if there's a good interpretation for $\tilde(p)_i$'s. Is that what you mean?
Comment: Do you suggest to use $^q H= \frac{1}{1-q} \ln ( \sum_{i=1}^N (\frac{w_i p_i}{w})^q)$ where $w=\sum_i w_i$? In other words, you're adjusting the probabilities in a way that the coefficients determine the new probabilities. Is that right? But the new probabilities do not sum to 1. Would you please extend your answer and explain why you chose that?
Comment: OK. I thought about it again. The approach you're suggesting is different. What I had in mind is to adjust the probabilities by multiplying the weights and the number of customers from the i-th country, and then divide by the sum of all such multiplications for all i's. That's a different approach, but I guess that one would work too. Please see the update on my main post.
Comment: @H.Z. My error, I meant normalizing by $\sum_i w_i p_i$ (so that probabilities sum up to 1) rather than $\sum_i w_i$. Yes, in the corrected formula it is equivalent to $w_i n_i  / (\sum_i w_i n_i)$. And I really recommend selecting $w_i$ such that $\tilde{p}_i$ it has some probabilistic interpretation (e.g. with this this money flow; or e.g. paying customers, or - customers who do something). Otherwise the choice of $w_i$ may be too subjective & hard to interpret.
Comment: @H.Z. For Stack Exchange it may be not ideal to update question with an answer (now may answer makes little sense, as it repeats what you already said). For "does it makes sense": 1. What is your goal? Showing it to management, using it in machine learning, predicting it, etc? 2. In general, Renyi entropy makes sense only when $\tilde{p}_i$ can be interpreted (in some way) as probabilities.
Comment: Well, I want this function to be more sensitive to countries with higher weights. So, if a country, say the i-th one, has a higher $w_in_i$, I want it to contribute to the output value more. I think that should be adjusted by choosing a proper value for $q$. Am I right?
Comment: @H.Z. "adjust" is not a well defined term. I mean, if you can adjust with weight $w_i$, then also you can adjust with weights $\sqrt{w_i}$, $w_i^3$, $\exp(w_i)$, etc. All of them will do, but the effective weights will be different, and the numerical results will be different. Also, one $\tilde{p}_i$ cannot be interpreted as probability, $H_q(\{\tilde{p}_i \})$ is pretty much meaningless (even if you get the numerical result).


Eigenvalues problem for the Laplacian operator on a free domain

Question: I want to ask a question about the eigenvalues and eigenvectors if they exist for the following question:
$$ - \Delta u = \lambda u{\text{  x}} \in \mathbb{R}$$
I have tried to do the Fourier transform of both side of the equation, I got
$$({\xi ^2} - \lambda )\hat u = 0{\text{ }}\xi  \in \mathbb{R}$$
then, I can not go further than that. Any help would be appreciated.
Answer: You mention "Dirichlet" in the title but haven't said anything about boundary conditions... in case, certainly
$$-u''(x) = \lambda u(x)$$
can be solved for $u$ on $\mathbb{R}$ for any $\lambda$. This is a standard linear second-order homogeneous ODE. For background on how to solve these, see for instance this chapter of Stewart.
For $\lambda\geq 0$ the solutions are
$$u(x) = Ae^{ix\sqrt{\lambda}} + Be^{-ix\sqrt{\lambda}}$$
where $i$ is the imaginary unit and $A,B$ are arbitrary constants. You can apply Euler's formula to extract the real solutions,
$$u(x) = C\cos\left(x\sqrt{\lambda}\right) + D\sin\left(x\sqrt{\lambda}\right)$$
for real constants $C,D$.
For $\lambda <0$ instead the real solutions are
$$u(x) = Ce^{x\sqrt{-\lambda}} + De^{-x\sqrt{-\lambda}}.$$
Comment: Thank you, sir, for the answer, I did a mistake in the title, I want to know how to solve the above problem without any boundary conditions, on a free domain.
Comment: @Gustave Well, the above shows the solutions to $\Delta u = -\lambda u$ on a free domain (for $u\in C^2(\mathbb{R})$). These may or may not be the eigenfunctions you're looking for, depending on precisely what Hilbert space you're considering, etc.
Comment: Thanks sir, let us say that  $u$ is in $L^2$ space,  can wa expect something interesting?


Proofs that: $\text{Sp}(2n,\mathbb{C})$ is Lie Group and $\text{sp}(2n,\mathbb{C})$ is Lie Algebra

Question: Consider following Lie Group:
$$
\text{Sp}(2n,\mathbb{C})=\{g\in\text{Mat}_{2n}(\mathbb{C})\mid J=g^TJg\}\quad\
where\quad J=\begin{pmatrix}
0 & 1_n \\
 -1_n & 0
\end{pmatrix}
$$
And the corresponding Lie Algebra:
$$
\text{sp}(2n,\mathbb{C})=\{g\in\text{Mat}_{2n}(\mathbb{C})\mid g^TJ+Jg=0\}
$$
Are there any basic proofs that $\text{Sp}(2n,\mathbb{C})$ is a Lie Group and that  $\text{sp}(2n,\mathbb{C})$ is the corresponding Lie Algebra without using submersions (seen here: Why is $Sp(2m)$ as regular set of $f(A)=A^tJA-J$, and, hence a Lie group.)? Can I proove the first statement by showing that $\text{Sp}(2n,\mathbb{C})$ is a subgroup of $\text{GL}(n,\mathbb{C})$?
Thanks!
Comment: Subgroup is not enough. You also need that it is a submanifold.
Comment: If you're willing to accept the [Closed Subgroup Theorem](http://en.wikipedia.org/wiki/Cartan%27s_theorem), then I think you can find a more basic proof. However, the Closed Subgroup Theorem is somewhat involved, by no means trivial.
Comment: On the Lie group part. You can identify $Sp(2n,\mathbb C)$ with a closed subset of $\mathbb C^{4n^2}$ using the usual distance between matrices as metric. The idea is that each matrix in  $Sp(2n,\mathbb C)$ is a long vector with $4n^2$ components satisfying the complicated equality in the definition of $Sp(2n,\mathbb C)$ itself. Once you have done this, you should prove that the composition and inverse maps are smooth. The composition produces polynomials, while the inverse map can be studied with the Cramer rule.
Comment: For the first Part i tried the following thing: Let $G \subset\mathbb{C}^{4n^2}$ be a closed subset of $\mathbb{C}^{4n^2}$.
$$\vec{j}=\vec{v}^T\vec{j}\vec{v}\quad\text{is valid}\quad\forall\vec{v}\in\mathbb{C}^{4n^2}\quad(\text{The equation satisfying}\quad\text{Sp}(2n,\mathbb{C}))$$
Defining then the map:
$$
f(\vec{v})=\vec{v}^T\vec{j}\vec{v}-\vec{j}
$$
Is this the right function to show composition and inverse map?
What is then the purpose of the metric?
Hmm I think Im getting it wrong..
Answer: On the Lie algebra part. By definition, $sp(2n,\mathbb C)$ is the real vector space of complex matrices
$$sp(2n,\mathbb C)=\{ A\in Mat_{2n}(\mathbb C): \exp(tA)\in Sp(2n,\mathbb C), \forall t\in \mathbb R \}.$$
$\exp(tA)$ denotes the exponential of the matrix $tA$. By definition of
$Sp(2n,\mathbb C), $ we have that
$$J=\exp(tA)^{t}J\exp(tA)=\exp(tA^{t})J\exp(tA),   (*)$$
where the second equality can be proved using the definition of the exponential of a matrix.
Using ($\exp(0)=1$)
$$\frac{d\exp(tA)}{dt}|_{t=0}:=\lim_{t\rightarrow 0}\frac{\exp(tA)-1}{t}=
\lim_{t\rightarrow 0}\frac{(1+tA+\frac{1}{2!}t^2A^2+\dots)-1}{t}=A$$
we arrive at
$$0=(\text{using (*)})=\frac{d}{dt}(J-\exp(tA)^{t}J\exp(tA))|_{t=0}=0-A^{t}J+JA,$$
i.e.  $A^{t}J+JA=0$, as $J$ is independent of $t$.
Comment: You are welcome!


Yii2 Model Unique Rules for combination of more than one attribute

Question: How can I specify a unique rule in my models for a combination of more that one attributes?
I want a rule that can't allow insert of a record with a combination of the same FIELD100,FIELD3
return [
    [['FEETYPE_F_V_R_','FIELD32','IS_CUSTOMER_EXPENSE','IS_BANK_EXPENSE','IS_BANK_EXPENSE','FIELD100'], 'required'],
    [['ID', 'ACTIVE', 'APPROVED', 'REWORKED', 'IS_CUSTOMER_EXPENSE', 'IS_BANK_EXPENSE', 'IS_BANK_EXPENSE'], 'integer'],
    [['AMOUNT'], 'number'],
    [['REWORKEDON'], 'safe'],
    [['FIELD3', 'FIELD32'], 'string', 'max' => 10],
    [['FEETYPE_F_V_R_', 'FIELD24'], 'string', 'max' => 2],
    [['FIELD100', 'CREATEDBY', 'APPROVEDBY', 'REWORKEDBY'], 'string', 'max' => 50],
    [['CREATEDDATE', 'APPROVEDDATE'], 'string', 'max' => 7],
    [['MEMOCODE'], 'string', 'max' => 20],
    [['ID'], 'unique'],
];

Comment: https://www.yiiframework.com/doc/api/2.0/yii-validators-uniquevalidator
Answer: You can use CompareValidator in your Model.
public function rules()
{
    return [
        [
            'FIELD100',
            'compare',
            'compareAttribute' => 'FIELD3',
            'operator' => '!=',
            'message' => 'Both values can not be the same'
        ]
    ];
}

For more info see the docs


Perl script - como calcular frequências com base no tamanho das sequências?

Question: Eu tenho este código em perl para calcular a contagem de di-peptídeos nas minhas sequências (sao 400 combinacoes, por examplo AA, AC, AD, AE...). Porém quero calcular a frequência destas contagens, para isso so preciso dividir a contagem pelo tamanho de cada sequência (length), porém tentei de diversas formas e nao consegui fazer o cálculo correto.
Meu script:
use strict;
use warnings;
use Bio::SeqIO;

my @amino=qw/A C D E F G H I K L M N P Q R S T V W Y/;
my @comb=();

foreach my $a (@amino){
    foreach my $b (@amino){
                push (@comb,$a.$b)
        }
}
my $in  = Bio::SeqIO->new(-file => "myfile.fasta" , '-format' => 'Fasta');
while ( my $seq= $in->next_seq ) {
my @dipeps=($seq->seq()=~/(?=(.{2}))/g);
my %di_count=();
$di_count{$_}++ for @dipeps;
print $seq->id();
map{exists $di_count{$_}?print " ",$di_count{$_}:print " ",0}sort @comb;
print "\n";
}

Eu tentei:
map{exists $di_count{$_}?print " ",$di_count{$_}:print " ",0}sort @comb/length;

map{exists $di_count{$_}?print " ",$di_count{$_}:print " ",0/length}sort @comb;

Mas nao resultou no esperado.
Ou preciso calcular o tamanho das sequências antes e definir antes? Sugestoes?
Comment: cuidado que `lenght` sozinho dá o comprimento de `$_` no teu caso o comprimento de combinação (=2).
Answer: Em vez do map (que fica neste caso um pouco confuso) propunha:
$len=scalar @dipeps;
for(sort keys %di_count){
   print " ",$di_count{$_}/$len}

(não testado)
Comment: nao deu certo, os resultados ficam incorretos.


Use Apache Commons Kalman Filter for 2D Positioning Estmation

Question: I want to improve the accuracy of my indoor positioning framework and therefore apply the kalmanfilter. I found that the apache commons math library supports Kalmanfilter so I tried to use it and followed the tutorials: https://commons.apache.org/proper/commons-math/userguide/filter.html
I think I got the matrices setup correctly for 2D positioning while the state consists of the position and velocity. My Problem lies in the Method estimatePosition(). How do I get the correct pNoise and mNoise variable? And why must i specify them. I thought this is what the Q and R matrices are for...
I appreaciate every help!
public class Kalman {

    //A - state transition matrix
    private RealMatrix A;
    //B - control input matrix
    private RealMatrix B;
    //H - measurement matrix
    private RealMatrix H;
    //Q - process noise covariance matrix (error in the process)
    private RealMatrix Q;
    //R - measurement noise covariance matrix (error in the measurement)
    private RealMatrix R;
    //PO - error covariance matrix
    private RealMatrix PO;
    //x state
    private RealVector x;

    // discrete time interval (100ms) between to steps
    private final double dt = 0.1d;
    // position measurement noise (10 meter)
    private final double measurementNoise = 10d;
    // acceleration noise (meter/sec^2)
    private final double accelNoise = 0.2d;
    // constant control input, increase velocity by 0.1 m/s per cycle [vX, vY]
    private RealVector u = new ArrayRealVector(new double[] { 0.1d, 0.1d });
    private RealVector tmpPNoise = new ArrayRealVector(new double[] { Math.pow(dt, 2d) / 2d, dt });
    private RealVector mNoise = new ArrayRealVector(1);
    private KalmanFilter filter;

    public Kalman(){
        //A and B describe the physic model of the user moving specified as matrices
        A = new Array2DRowRealMatrix(new double[][] {
                                                        { 1d, 0d, dt, 0d },
                                                        { 0d, 1d, 0d, dt },
                                                        { 0d, 0d, 1d, 0d },
                                                        { 0d, 0d, 0d, 1d }
                                                    });
        B = new Array2DRowRealMatrix(new double[][] {
                                                        { Math.pow(dt, 2d) / 2d },
                                                        { Math.pow(dt, 2d) / 2d },
                                                        { dt},
                                                        { dt }
                                                    });
        //only observe first 2 values - the position coordinates
        H = new Array2DRowRealMatrix(new double[][] {
                                                        { 1d, 0d, 0d, 0d },
                                                        { 0d, 1d, 0d, 0d },
                                                    });
        Q = new Array2DRowRealMatrix(new double[][] {
                                                        { Math.pow(dt, 4d)/4d, 0d, Math.pow(dt, 3d)/2d, 0d },
                                                        { 0d, Math.pow(dt, 4d)/4d, 0d, Math.pow(dt, 3d)/2d },
                                                        { Math.pow(dt, 3d)/2d, 0d, Math.pow(dt, 2d), 0d },
                                                        { 0d, Math.pow(dt, 3d)/2d, 0d, Math.pow(dt, 2d) }
                                                    });

        R = new Array2DRowRealMatrix(new double[][] {
                { Math.pow(measurementNoise, 2d), 0d },
                { 0d, Math.pow(measurementNoise, 2d) }
        });

        /*PO = new Array2DRowRealMatrix(new double[][] {
                                                        { 1d, 1d, 1d, 1d },
                                                        { 1d, 1d, 1d, 1d },
                                                        { 1d, 1d, 1d, 1d },
                                                        { 1d, 1d, 1d, 1d }
                                                     });*/

        // x = [ 0 0 0 0] state consists of position and velocity[pX, pY, vX, vY]
        //TODO: inititate with map center?
        x = new ArrayRealVector(new double[] { 0, 0, 0, 0 });

        ProcessModel pm = new DefaultProcessModel(A, B, Q, x, PO);
        MeasurementModel mm = new DefaultMeasurementModel(H, R);
        filter = new KalmanFilter(pm, mm);
    }

    /**
     * Use Kalmanfilter to decrease measurement errors
     * @param position
     * @return
     */
    public Position<Euclidean2D> esimatePosition(Position<Euclidean2D> position){
        RandomGenerator rand = new JDKRandomGenerator();

        double[] pos = position.toArray();
        // predict the state estimate one time-step ahead
        filter.predict(u);

        // noise of the process
        RealVector  pNoise = tmpPNoise.mapMultiply(accelNoise * pos[0]);

        // x = A * x + B * u + pNoise (state prediction)
        x = A.operate(x).add(B.operate(u)).add(pNoise);

        // noise of the measurement
        mNoise.setEntry(0, measurementNoise * rand.nextGaussian());

        // z = H * x + m_noise (measurement prediction)
        RealVector z = H.operate(x).add(mNoise);

        // correct the state estimate with the latest measurement
        filter.correct(z);

        //get the corrected state - the position
        double pX = filter.getStateEstimation()[0];
        double pY = filter.getStateEstimation()[1];

        return new Position2D(pX, pY);
    }
}

Answer: Those are part of their example simulation.  They're generating test data by adding Gaussian noise (as pNoise and mNoise) to simulate real world conditions.  In a real application you wouldn't add any noise to your real measurements.
Answer: The one dimensional car acceleration example provided in Apache commons math Kalman filter library is from  this paper. That paper is programmer oriented and easy to follow to start programming.
In practice, u and z is from control and measure sensor data input during every iteration. so the estimatePosition will be like:
public Position<Euclidean2D> esimatePosition(Measurement z){
        u = readControlInputFromSomeWhere();
        filter.predict(u);
        filter.correct(z);
        double pX = filter.getStateEstimation()[0];
        double pY = filter.getStateEstimation()[1];
        return new Position2D(pX, pY);
    }

http://commons.apache.org/proper/commons-math/userguide/filter.html
Apache commons Paper


Difference between '&' and '==' while using Qt mouse functions?

Question: I was reading the documentation of Qt example of "scribble". There I stumbled across the following piece of code:
 void ScribbleArea::mouseMoveEvent(QMouseEvent *event)
 {
     if ((event->buttons() & Qt::LeftButton) && scribbling)
         drawLineTo(event->pos());
 }

 void ScribbleArea::mouseReleaseEvent(QMouseEvent *event)
 {
     if (event->button() == Qt::LeftButton && scribbling) {
         drawLineTo(event->pos());
         scribbling = false;
     }
 }

One question arised in my mind on whether there's actually any difference between event->button() == Qt::LeftButton and (event->buttons() & Qt::LeftButton). Could you please explain? Thanks.
Comment: I am not  that familiar with QT but maybe its that (event->buttons() & Qt::LeftButton) will also check right button...
Answer: The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand.
The operator== compare both operands to see if the values are equal.
That is, for you:
event->buttons() & Qt::LeftButton

Will be true if the LeftButton bit is set and other bits may also be set.
event->button() == Qt::LeftButton

Will be true if only the LeftButton bit is set and other bits should not be set.

An example on how it works :
enum
{
    BUTTON_LEFT = 1 << 0,
    BUTTON_RIGHT= 1 << 1,
    BUTTON_MID  = 1 << 2
};

int a = 0;
a |= BUTTON_LEFT;
a |= BUTTON_RIGHT;
a |= BUTTON_MID;

if ( a & BUTTON_RIGHT )
    std::cout << "The button right is pressed." << std::endl;

if ( a == BUTTON_RIGHT )
    std::cout << "There is only the button right." << std::endl;

The output of this will be: The button right is pressed.. http://ideone.com/BunrTs
Answer: event->buttons() & Qt::LeftButton

This is true if the LeftButton bit is set; other bits may also be set.
event->button() == Qt::LeftButton

This is true if only the LeftButton bit is set; other bits may not be set.
Comment: @the_naive: That's right. `&` is testing a single bit, while `==` is testing all bits.
Comment: So, the codes `((event->buttons() & Qt::LeftButton) && scribbling)` and `(event->button() == Qt::LeftButton && scribbling)`  will yield different results? I could see that the second one would produce `true` if only the left button is pressed, but the first one will yield `true` despite the right button is pressed?
Answer: Looks like a bug to me.
Assuming the mouse buttons are represented as unique bit "flags", the first tests if the left mouse button is pressed, while filtering out any other buttons that might have been pressed at the same time.
The second, however, requires that only the left button has been released. So if you do a double-press to start scribbling, then release both buttons at the same time, it should fail to detect the release.
UPDATE:
This random Qt reference seems to support the assumption, at least:
Qt::LeftButton    0x00000001 The left button is pressed, or an event refers to the left button. (The left button may be the right button on left-handed mice.)
Qt::RightButton   0x00000002 The right button.
Qt::MidButton     0x00000004 The middle button.

Also, as pointed out by brilliant commentor @svk, the two use different ways to access the mouse button flags, so it should be fine.
The fact that release events don't ever report multiple buttons is one of those things you learn after working with Qt for a while, something I haven't done. Sorry for the confusion.
Comment: Not sure this is a bug. Notice that there are two different methods: `button()` and `buttons()`. For a mouse release event, there's only one button being released.
Comment: @svk Thanks! That's weird, your comment is the best answer.
Comment: As I found out, `button()` or `buttons()` is always 0 on release. Don't know if this is a bug.
Answer: Please note that in case of mouseMoveEvent method event->buttons() is used (it has "s" at the end) and it returns state of multiple buttons. So if many buttons are down many flags will be set.
In contradiction in case of mouseReleaseEvent and mousePressEvent method event->button() is used (no "s" at the end), and this return which button invoke this event this means that only ONE flag is set and it is possible to use equal operator.
When you note that check already excepted answer from Mike Seymour.
Off-topic: in Qt flags have also testFlag method.


Swing mouse drag identification problem?

Question: How do I identify mouse dragged in downward direction? Suppose I dragged down, I need code such as this:
int graphy = e.getY();
System.out.println("this is y axises " + graphy);
_graph._verticalScroll.setValue(graphy + _graph._headerWidth
    + _graph._verticalScroll.getValue());

What code should i put when mouse dragged down?
Comment: Have you read [How to Write a Mouse Listener](http://download.oracle.com/javase/tutorial/uiswing/events/mouselistener.html).
Comment: @trashgod i saw that link but im did not  get answer specific code to identify as mouse dragged  down direction
Comment: Please post an [sscce](http://sscce.org/) showing what you've tried. Your current example has no context.
Answer: You can use a MouseAdapter and implement mouseDragged(MouseEvent e).
You have to check the coodrinates using e.getPoint() or e.getY() and compare with the previous event to get the direction.
You can detect if the mouse is dragged upwards or downwards with code similar to this:
if(e.getY() > previousY) {
  // drags downwards
} else if (e.getY() < preiousY) {
  // drags upwards
}
previousY = e.getY();

Comment: @jones Its working  fine i used same method for identify left and right it causes problem
Comment: @jones exactly in moused dragged function i want to identify wether mouse dragged upward or downward
Comment: @Ganesh: You need to show more of your code. And you need to write what error you get or why it doesn't work.
Comment: @Ganesh: You can not start with `previousY = e.getY();` then it can't work.
Comment: if(e.getY() > previousY) {

 int  graphy = e.getY();
 System.out.println("this is y axises "+graphy);
      _graph._verticalScroll.setValue(graphy+_graph._headerWidth+ _graph._verticalScroll.getValue());

      // drags downwards
} else if (e.getY() < previousY) {
  int  graphy = e.getY();

      _graph._verticalScroll.setValue(graphy+_graph._headerWidth+ _graph._verticalScroll.getValue());

      // drags upwards
    }
Comment: @Ganesh: What error do you get? It's better if you post the code in your question.
Comment: @jones befor that i declare previousY = e.getY()
Comment: @jones control is not giving inside that condition means condition not satissified
Comment: @Ganesh: Does the control have a mouslistener? you need to provide more information.
Comment: @jones It is going inside mouse dragged but not in this condition if(e.getY() > previousY)
Comment: @Ganesh: print the value for `e.getY()` and `previousY`


Riemann integrable function which does not take its maximum on the interval

Question: I made the following assertion on an exam I thought was true:

If a function is Riemann-integrable on $[a,b]$ then it attains its maximum on the interval.

Apparently this is false. This is definitely true if $f$ is continuous. Thus I'm trying to argue that there exists a discontinuous function that is Riemann-integrable and does not attain its max on the interval. I'm having a tough time though -- ideas?
Edit: Sorry for all the edits!
Comment: A simple example is taking a continuous function on a compact set, which attains its maximum, and then removing the maximum (so you have a single hole-type discontinuity where the maximum is) and replacing that value with something else. The integral remains the same, but the maximum is no longer attained.
Comment: @rubikscube09: That won't work as written for an _arbitrary_ continuous function on a compact interval -- consider a "flat-topped" function such as $x\mapsto3-|x-1|-|x-2|$ on $[0,3]$. Removing all the maxima will leave too large a hole to fill in without changing the integral.
Comment: So after graphing I see that the function is constant and maximal on the interval $[1,2]$. Would we lose integrability if we shifted that entire interval by some value? It seems that we would only have 2 discontinuity points in that case.
Answer: How about
$$ f(x) = \begin{cases} 1-x^2 & \text{when }x\ne 0 \\ 0 & \text{when }x=0 \end{cases} $$
on $[-1,1]$?
This is Riemann integrable because a Riemann sum for it differs from a Riemann sum for $1-x^2$ by at most the width of the subinterval containing $0$. So we can make the difference as small as we want by insisting on a sufficiently fine partition.


Phrase to describe numbers which are powers of a common base

Question: I'm looking for a succint phrase to describe the set of numbers
$$S_b = \{i\in\mathbb{Z}: b^i\}. $$
That is, the numbers which are all powers of a (specific) common base $b$.
I've played with "exponent-b numbers", "base-b power" numbers, etc. but they don't seem to fit.
For example, consider units of computer memory, where the total number of bytes is typically an exponent of 2.
I'd like to say something more succinct than "on systems with memory that is an exponent of 2, you get...".
For instance, "on systems with base-2 memory".
What's a sensible phrase to use here? Do such sets of numbers have a particular name?
Answer: Simplest one would be just the "Powers of B" or "B-Powers". Otherwise "Exponent Set of B", "Set of Powers of B". I wouldn't recommend using the "Power Set of B" as it already has a different meaning in set theory.
Comment: I appreciate you made your account to answer this question, but please read the original example; I don't think the phrase "2-powers memory" is natural.


How to validate ip address in C#

Question: I'm doing an application that uses IP address. I have to validate them to start from at least 220.127.116.11 but with the codes below it accepts 0.0.0.0:
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

I also tried changing it to:
\b(25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

This code does not accept 0.0.0.0 but does not accept 188.8.131.52 to 126.96.36.199 either.
Can someone help?
Comment: @spender, @ba_friend: Why not help edit the post to improve the formatting rather than just complaining? You both have the rep to help!
Comment: But did it really need to be -1? surely that is what notes are for? You nurture and get the information, someone with a low 100 score isnt going to know how the site works off the bat. Help them to grow and become part of the community. I'll get off my soapbox in a sec. I think this is a constant debate. I'll see if this on meta. I understand that as a community site we are responsible for content, but for a youngling to come in and be marked down by -2 before they even get going. how are we suppose to grow the community with such harsh ideals. Nurture a Noob today. you'll feel a lot better.
Comment: Please learn how to format your questions properly.
Comment: -1 for not explaining that you are using regex (if that's what it is). What is "bt"? Why is the formatting so poor? Read this: http://stackoverflow.com/editing-help
Comment: Using Regex for this kind of validation seems needlessly brain-taxing. Why not split by `.` and validate each portion of the IP address in a more conventional way?
Comment: everyone is really harsh today...
Comment: Frankly, the initial edit of the question was sufficiently poor that in order to make it proper, I would need to make assumptions about OPs intent that might not be correct.
Comment: @Luke, @xan I edited this post before @Mat and before I commented on this. Changed the title, tags, and formatting even fixed the `bt` typo. ;)
Comment: @Luke, I understand your concern. Just to be clear I edited the post **but** I did not downvote, even if it looked like because 2 comments and 2 downvotes at that moment.
Comment: \/ Save your self even more pain and prepare for IPV6 with IPaddress.tryparse !
Answer: Use
IPAddress addr = IPAddress.TryParse(str);

Then, if that worked get the numbers using
addr.GetAddressBytes();

and then check the byte values for the correct conditions using normal if-cases.
Comment: bye the way it also validates 1 as true and set the ipaddress to 0.0.0.1
Comment: Yap for network expert it might be understandable, but validation on input text box on an application for non-professional user is not desired.
Comment: I already voted up the answer, i just added my first note for developer who are looking for ip address string validation. like me. :) cheers
Comment: Yes "1" is a valid IP address, meaning 0.0.0.1
Comment: The question was how to validate that the individual bytes in the address have appropriate values. In this specific case the requirement was that it was at least 126.96.36.199, which would only be possible from a string containing four octets. If you want to accept *any* IP address but validate that the user has input all four octets then parsing in this way will not be sufficient.
Answer: Save yourself the pain! Convert to a string, split on the dot character and check whether each of the 4 segments is in the range 0 or 1 to 255.
Otherwise if you use RegexBuddy (which is a fantastic app for RegEx) it has a bunch of IP address examples in the Library inc for 0.0.0.0 to 255.255.255.255:
\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b

Answer: Try using this,
ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

How to validate ip address in C#


Unable to render title field on node template

Question: For my content type - Article I have a template
node--article.tpl.php

I currently render other fields such as the body text just fine. However the title cannot be displayed.
I'm using
print render($content['title']);
print render($content['body']);

But only the title is displayed. To make sure I'm using the right machine name, I looked at the content type configuration.

Is there something missing? Or is there something special I have to do to to the 'title' field?
Answer: I was able to print the title using
print $title;


Unseen Problem based on area of triangle

Question: In $\triangle ABC$, $BD=2CD$ and $AE=ED$, prove that $6\triangle ACE=\triangle ABC$
If $A,X$ is joined such that $X$ is the mid point of $BC$ then:
$\triangle ABX=\triangle AXC$
Also,
$\triangle AEC=\triangle EDC$
now, what should I do next?
Answer:
Use lemma:
Let $\frac{AM}{MC}=\frac mn$. Then $$\frac{S_{AMX}}{S_{CMX}}=\frac{\frac12AM\cdot XD}{\frac12 MC \cdot XD}=\frac{AM}{MC}=\frac mn$$
The proof of the problem:
Let $S_{ACE}=x$. If $AE=ED$ then $S_{ACE}=S_{CED}=x$. Then $S_{ADC}=2x$. If $BD=2DC$, then $S_{ABD}=2S_{ADC}=4x$. Then $S_{ABC}=S_{ABD}+S_{ADC}=4x+2x=6x$
Comment: @ Roman83, your figure explanation is unclear to me as it doesn't match with my figure. Could you put it a bit clearly?
Answer: Since $DC=\frac{1}{3} BC$ it follows that $\triangle ADC= \frac{1}{3} \triangle ABC$ since they have the same height on DC and BC.
$\triangle ACE = \triangle EDC$ , because $AE=ED$, and $\sin \angle AEC = \sin \angle DEC \Rightarrow \triangle ACE= \frac{1}{2} \triangle ADC = \frac{1}{6} \triangle ABC $
Answer: Dividing the base into three equal parts means dividing the area of triangle in three equal parts. Here $\triangle ADC$ is one of the $3 $ parts.So $\triangle ADC=\frac{1}{3}\triangle ABC$
Now we have to prove that $\triangle AEC=\frac{1}{2}\triangle ADC$.As given the area has been divided into two equal parts by dividing the base AD into two equal parts ,hence proved .
Answer: Then, combine $\triangle AEC$ and $\triangle DEC$ into $\triangle ADC$ whose area is then 2 parts if that of $\triangle AEC$ is 1 part. The process goes on.....


Using ScriptEngine in java, How can I extract function list?

Question: using Jsoup, I extract JavaScript part in html file. and store it as java String Object.
and I want to extract function list, variables list in js's function using javax.script.ScriptEngine
JavaScript part has several function section.
ex)
function a() {
var a_1;
var a_2
...
}

function b() {
    var b_1;
    var b_2;
...
}

function c() {
    var c_1;
    var c_2;
...
}

My Goals is right below.
List funcList
a
b
c
List varListA
a_1
a_2
...
List varListB
b_1
b_2
...
List varListC
c_1
c_2
...
How can I extract function list and variables list(or maybe values)?
Comment: Do you want to execute the code or do you want to inspect the code statically? `ScriptEngine` may be suitable for execution, though it will lack things like the DOM. If you want to inspect the code, an AST parser would be more suitable (e.g. Antlr or Mozilla Rhino's AST parser.)
Comment: thanks. I want to inspect the code, then modify the code(change function name, variable name.. and so on). I'll try an AST parser!!
Answer: I think you can do this by using javascript introspection after having loaded the javascript in the Engine - e.g. for functions:
ScriptEngine engine;
// create the engine and have it load your javascript
Bindings bind = engine.getBindings(ScriptContext.ENGINE_SCOPE);
Set<String> allAttributes = bind.keySet();
Set<String> allFunctions = new HashSet<String>();
for ( String attr : allAttributes ) {
    if ( "function".equals( engine.eval("typeof " + attr) ) ) {
        allFunctions.add(attr);
    }
}
System.out.println(allFunctions);

I haven't found a way to extract the variables inside functions (local variables) without delving in internal mechanics (and thus unsafe to use) of the javascript scripting engine.
Answer: It is pretty tricky. ScriptEngine API seems not good for inspecting the code. So, I have such kind of pretty ugly solution with instance of and cast operators.
       Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
       for (Map.Entry<String, Object> scopeEntry : bindings.entrySet()) {
           Object value = scopeEntry.getValue();
           String name = scopeEntry.getKey();
           if (value instanceof NativeFunction) {
               log.info("Function -> " + name);
               NativeFunction function = NativeFunction.class.cast(value);
               DebuggableScript debuggableFunction = function.getDebuggableView();
               for (int i = 0; i < debuggableFunction.getParamAndVarCount(); i++) {
                   log.info("First level arg: " + debuggableFunction.getParamOrVarName(i));
               }
           } else if (value instanceof Undefined
                   || value instanceof String
                   || value instanceof Number) {
               log.info("Global arg -> " + name);
           }
       }

Comment: What is NativeFunction here ? Code doesn't recognise it.
Answer: I had similar issue. Maybe it will be helpfull for others.
I use groove as script lang. My Task was to retrive all invokable functions from the script. And then filter this functions by some criteria.
Unfortunately this approach is usefull only for groovy...
Get script engine:
public ScriptEngine getEngine() throws Exception {
    if (engine == null)
        engine = new ScriptEngineManager().getEngineByName(scriptType);
    if (engine == null)
        throw new Exception("Could not find implementation of " + scriptType);
    return engine;
}

Compile and evaluate script:
public void evaluateScript(String script) throws Exception {
    Bindings bindings = getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.putAll(binding);
    try {
        if (engine instanceof Compilable)
            compiledScript = ((Compilable)getEngine()).compile(script);
        getEngine().eval(script);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

Get functions from script. I did not found other ways how to get all invokable methods from script except Reflection. Yeah, i know that this approach depends on ScriptEngine implementation, but it's the only one :)
public List getInvokableList() throws ScriptException {
    List list = new ArrayList();
    try {
        Class compiledClass = compiledScript.getClass();
        Field clasz = compiledClass.getDeclaredField("clasz");
        clasz.setAccessible(true);
        Class scrClass = (Class)clasz.get(compiledScript);
        Method[] methods = scrClass.getDeclaredMethods();
        clasz.setAccessible(false);
        for (int i = 0, j = methods.length; i < j; i++) {
            Annotation[] annotations = methods[i].getDeclaredAnnotations();
            boolean ok = false;
            for (int k = 0, m = annotations.length; k < m; k++) {
                ok = annotations[k] instanceof CalculatedField;
                if (ok) break;
            }
            if (ok)
                list.add(methods[i].getName());
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {

    }
    return list;
}

In my task i don't need all functions, for this i create custom annotation and use it in the script:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CalculatedField {
}

Script example:
import com.vssk.CalculatedField;

def utilFunc(s) {
    s
}

@CalculatedField
def func3() {
    utilFunc('Testing func from groovy')
}

Method to invoke script function by it's name:
public Object executeFunc(String name) throws Exception {
    return ((Invocable)getEngine()).invokeFunction(name);
}


Android Studio: MainActivity.java file is depreacted

Question:
Suddenly my Android Studio is giving me deprecated MainActivity.java files for any new projects.
I resinstalled Android Studio, but still the problem is not solved.
Answer: Java files cannot be deprecated. References to Java classes, methods, and fields can be deprecated.
The only thing that I see that is deprecated in that screenshot is the call to setDrawerListener() on the DrawerLayout. Presumably, you decided to use the Navigation Drawer activity template when you created your project.
Your options are:

Ignore the deprecation warning, as setDrawerListener() is not shown as deprecated in the JavaDocs. UPDATE The JavaDocs are out of date. You could change the call to addDrawerListener(), which is the recommended replacement, if you wanted.
Do not use that template.
Comment: My [edit suggestion](http://stackoverflow.com/review/suggested-edits/12207961) got rejected, I could see same edit to the question.
Comment: @Raju: The edit suggestion diff indicated that you only changed the caption. I did not realize that the diff would not show the inline image. My sincere apologies.
Comment: @CommonWare, That's quite alright & I understand. Because markdown won't show any difference, but rendered view does.


Time and space complexity for removing duplicates from a list

Question: I've the following code and I'm trying to get the time complexity.
seen = set()
a=[4,4,4,3,3,2,1,1,1,5,5]
result = []
for item in a:
    if item not in seen:
        seen.add(item)
        result.append(item)
print (result)

As far as my understanding goes as I'm accessing the list the time complexity for that operation would be O(n). As with the if block each time I've a lookup to the set and that would cost another O(n). So is the overall time complexity O(n^2)? Does the set.add() also add to the complexity?
Also, with the space complexity is it O(n)? Because the size of the set increases each time it encounters a new element?
Any input or links to get a proper insight into time and space complexities is appreciated.
Answer: Sets in Python are implemented as hash tables (similar to dictionaries), so both in and set.add() are O(1). list.append() is also O(1) amortized.
Altogether, that means the time complexity is O(n), due to the iteration over a.
Space complexity is O(n) as well, because the maximum space required is proportional to the size of the input.
A useful reference for the time complexity of various operations on Python collections can by found at https://wiki.python.org/moin/TimeComplexity … and the PyCon talk The Mighty Dictionary provides an interesting delve into how Python achieves O(1) complexity for various set and dict operations.
Comment: Thank you so much, a quick question: What if I use a `list` instead of a `set` will that change anything? Because `lists` in Python are implemented using `C arrays`(correct me if I'm wrong), and the access time is `O(n)` and assume I'm using `insert` instead of `append` so, insert cost is `O(n)`. Will the over all time still remain the same now?
Comment: As noted in the wiki page linked above, `in` for lists is O(N) because the list has to be iterated over until a match is found (and yes, they're C arrays). Since you only care about membership, the order of `seen` isn't important, so you might as well append items to it – which is O(1) amortized because of the way "spare" space is managed – rather than insert them. Either way, the upshot would be an O(n²) algorithm.
Comment: ahh, I get it now. Thank you so much!
Comment: You're welcome :-) Aside: I'm guessing this is a homework-related question. That's fine … they're only frowned on around here when people beg for an answer without showing any evidence of having put any thought in for themselves, which is clearly not so in your case. That said, I would highly recommend the PyCon video linked in the answer, which is both fascinating and educational.
Comment: No this ain't homework, I'm preparing for an interview. So, apart from programming I need to understand the run time complexities too. Yea, I'm going through the video now. Thanks again. :)


What are the duties of the coach in a football team?

Question: This question came up in our exams. The Laws don't mention duties of the coach. I understand they aren't supposed to mention everything. But, there must be some common duties of the football coaches of different leagues and tournaments.
What are they?
Answer: Assuming you are asking about head coach as management team of football club can have other coaches like fitness coach, goalkeeper coach and like. See: Chelsea FC management team
Responsibilities of a head coach in a professional football club usually include (but are not limited to) the following:

Selecting the team of players for matches, and their formation.
Planning the strategy, and instructing the players on the pitch.
Motivating players before and during a match.
Scouting for young players for eventual training in the youth academy or the reserves, and encouraging their development and improvement.
Facing the media in pre-match and post-match interviews.
Delegating duties to other coaching and medical staff.*

*The management of the team (coaching and medical staff) might be under the club board.
For more information read this wikipedia article.

References:
1. Manager (association football)
2. What is the difference between a manager and a coach in case of a soccer team?


How to tell Drupal to use tpl file from my module?

Question: I have a custom module and placed comment.tpl.php here:
/sites/all/modules/mymodule/comment.tpl.php
But Drupal is not looking for that file in my custom module directory. How can i make it work?
Answer: You need to use hook_theme:
<code>/**
 * Implements hook_theme().
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {

  if($type != 'module') {
    return [];
  }

  // If you want to put your templates in a templates directory
  // in your module directory add .'/templates' to the end.
  $module_path = drupal_get_path('module', 'MY_MODULE');

  return [
    'comment' => [
      'template' => 'comment',
      'path'     => $module_path,
    ],
    'other_template' => [
      'template' => 'comment',
      'path'    => '/my/custom/path/here',
    ],
  ];
}
</code>
This has set up our custom theme, then when you want to use it you can:
<code>$tpl_data = [
  'param1' => $foo,
  'param2' => $bar,
];

return theme('comment', $tpl_data);
</code>
Now $param1 and $param2 will be available in your template file too.
If you don't need any custom data in your template then $tpl_data can be omitted.
Happy days.
Comment: It worked! Thanks. If i want to use templates from a page,node i just have to change comment on page/node, right?
Comment: If you want to use another template file you can just add another line in your hook_theme function and supply the path to it (answer updated)
Comment: I mean what if i want to use node.tpl.php in my module directory, sorry for such a silly questions :), oh i see now, So it would be 'node' => array('template' => 'node', $path) right?
Comment: Yes, that's right.
Answer: You can do this by using hook_theme() as described on api.drupal.org. It allows you to register your module's theme implementation.
Comment: Can you throw an example please?


Is there a standard reduced numbers version of Australian Rules Football?

Question: In several forms of football (and probably other sports) there are standard variants of the game using a reduced number of players. For instance Rugby Union and Rugby League 7s (normally played by 15 and 13 a side respectively). Soccer also has futsal (5 a side instead of 11). In some of the above cases the field is a different size in others it remains the same but in all cases there are changes in the rules in addition to the reduced number of players.
My question is whether there is a similar variant for Australian Rules Football? I do know junior leagues play with less players on smaller fields but that is a somewhat different thing to a 'senior' game just played with less players.
Answer: Standardised? No.
For anything as low as twelve players per team, the rules as they stand work pretty well, although a smaller field may be preferable. For less than twelve players there would definitely need to be some re-working of the rules, but I've never seen any commonly used rules for smaller teams apart from the rules as they stand normally.


Python find all the words with less than 5 letters in the string in a given text

Question: This code doesn't work right now because I don't know the exact code I should use. I need to print out the number of words containing less than 5 letters.
This is what I've been trying:
text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
words = text.split()
letterCount = {w: len(w) for w in words}

lessthan5 = '1,2,3,4'
count = 0
if words == lessthan5 :      #i put words to refer to line 3(letter count)
     result = count + 1
     print(result)

The output I need is an integer, ex.17.
Pls help thank u so much
Comment: You don't really need the `if`clause; you can just sum the boolean: `sum(len(word) < 5 for word in words)`
Comment: `sum([1 for i in text.split() if len(i)<5])`
Answer: Hope this help:
text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
words = text.split()
count = 0
for word in words:
    if len(word) < 5:
        count = count + 1

print(count)

Comment: @Ruby You welcome, don't forget to upvote and/or accept as answer.
Answer: Here's one simple solution using a regular expression. The advantage of using a regular expression rather than just splitting the input at whitespace is that you can more precisely define what a "word" is. For example, you can exclude punctuation, so that "a full stop." counts as three words less than five characters long. (With str.split and a filter on string length, the last word would be "stop." instead of "stop", so it wouldn't show up, leaving only two words.)
>>> import re
>>> rg = re.compile(r"\b\w{1,4}\b")

The above regular expression means "starting at a word boundary, followed by from one to four word characters followed by a word boundary.
>>> text = ("It is a long established fact that a reader"
            " will be distracted by the readable content"
            " of a page when looking at its layout.")
>>> rg.findall(text)
['It', 'is', 'a', 'long', 'fact', 'that', 'a', 'will', 'be', 'by', 'the', 'of', 'a', 'page', 'when', 'at', 'its']
>>> len(rg.findall(text)
17

re.findall, as its name indicates, finds all of the instances of a regular pattern in a string, returning the matches in a vector.


How to make specific characters in edittext bold?

Question: I have a EditText and a toggle button.
Scenario 1 :- I am typing normally in the EditText using softKeyboard.
Scenario 2 :- I press the toggle button. It's status changes to true. So, in this scenario, i want that when the toggle button is ON, my typeface of the Edittext should be Bold, But only for the string from that point on.
For Example :-
Scenario 1 : - I type "abcdef" in my EditText
Result : - abcdef
Scenario 2 : - Toggle Button Status is ON
Scenario 3 : - I type " ghijkl" in my EditText
Result : - abcde ghijkl
I Hope the scenario is clear now
Comment: please be clear what is requirement
Comment: i have edited my requirement with detailed scenario
Comment: @RahulGupta did you implement it? where did you put the current cursor position?
Comment: @kittu88 - The current position of the cursor that is. Wherever the current position is, i start from there only
Comment: @RahulGupta basically there are 2 static values in the answer below, s.length() >= 4 and android.graphics.Typeface.BOLD), 3, s.length() - 1. I have tried changing  if (s.length() >= editText1.getSelectionStart()+1) and android.graphics.Typeface.BOLD), editText1.getSelectionStart(), s.length() - 1 but, this crashes the app when I try to clear the edittext. It will be very helpful if you give me the code snippet with the current cursor position.
Answer: For this in your Textwatcher add code like this..
<code>@Override
        public void afterTextChanged(Editable s) {
            if (s.length() >= 4) {
                s.setSpan(new android.text.style.StyleSpan(
                        android.graphics.Typeface.BOLD), 3, s.length() - 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
</code>
you have check the condition and apply it to the text..here i am testing for only 4 chars.you have to change it based on your condition..
Comment: Where should I put the current cursor position?


HasMap Function returning null value

Question: I working on android csv file reading library. I create a function in library and calling it in other project. The library function reads the csv file ( which is in the assets folder of my project which is extended from library class ) ,store the name and value in strings GotDbname and GotDbValue respectively . But it is not returning anything. Any type help will be appreciated.
public class ReadFile extends Activity {
String GetDbName = "DBName";
String GetDbVersion = "DbVersion";
String GotDbName;
String GotDbVersion;
HashMap<String, String> DatabaseMap = new HashMap<String, String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
}

public void hello() {
    Log.d("Library Is working ", "Hello  ");

}

public HashMap<String, String> read(Context con, String name, String version) {
    Log.d("Read File", "Getting Assest Manager");

    AssetManager assetManager = con.getAssets();
    Log.d("Read File", "Assest Manager Object Created");
    if (assetManager == null) {
        Log.d("Reading file", "Nothing in assets");
    }
    else {
        InputStream inputStream = null;
        Log.d("Read File", "Getting input Stream");
        try {
            Log.d("Read File", "Getting File");
            inputStream = assetManager.open("Db.csv");
            Log.d("Read File", "File read");
            String text = loadTextFile(inputStream);

            String[] text1 = text.split(",");

            Log.d("Read File", "LoadTextFile" + text + " " + text1);

            String id[] = new String[text1.length];
            String value[] = new String[text1.length];
            Log.d("Read File", "Getting Strings" + "DbName " + id
                    + "DbVersion  " + value);
            int c = 0;
            for (int i = 0; i < text1.length; i += 2)
            {
                id[c] = text1[i].replace('"', ' ');
                Log.d("Read File", "Getting Db name" + "  " + id[c]);
                c++;
            }
            int d = 0;
            for (int i = 1; i < text1.length; i += 2)
            {
                value[d] = text1[i].replace('"', ' ');
                Log.d("Read File", "Getting getting Version" + "  "
                        + value[d]);
                d++;
            }
            int indexofid = -1;
            for (int i = 0; i < id.length; i++) {
                Log.d("Reading CSV", "In for Loop");
                if (GetDbName.equals(id[i].trim())) {
                    indexofid = i;

                    GotDbName = value[indexofid].toString();
                    Log.d("Read File final", "Getting Db Name" + "  "
                            + GotDbName);
                    break;

                }
            }
            for (int i = 0; i < id.length; i++) {

                if (GetDbVersion.equals(id[i].trim())) {
                    indexofid = i;

                    GotDbVersion = value[indexofid].toString();
                    Log.d("Read File final", "Getting Db Version" + "  "
                            + GotDbVersion);
                    break;

                }

            }
        } catch (IOException e) {
            Log.d("Read File", "No file found");
        }

    }
    DatabaseMap.put(name, GotDbName);
    DatabaseMap.put(version, GotDbVersion);
    Log.d("Read File", " Database Name =" + GotDbName
            + "Database Version =" + GotDbVersion);
    return DatabaseMap;

}

    public String loadTextFile(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    byte[] bytes = new byte[4096];
    int len = 0;
    while ((len = inputStream.read(bytes)) > 0)
        byteStream.write(bytes, 0, len);
    return new String(byteStream.toByteArray(), "UTF8");
}
}

And here is the class of other project which is using that library
public class MainClass extends ReadFile {
String DbName;
String DbVersion;
String a, b;
TextView txt_dbName, txt_version;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt_dbName = (TextView) findViewById(R.id.txt_dbName);
    txt_version = (TextView) findViewById(R.id.txt_version);
    HashMap<String, String> map = new HashMap<>();
    map = read(this, DbName, DbVersion);
    String abc = map.get("name");
    Log.d("Main Class", "Map =" + abc);

    Log.d("MainClass", "DbName = " + DbName + ": DbVersion = "
            + DbVersion);

    txt_dbName.setText(DbName);
    txt_version.setText(DbVersion);
}
}

Answer: String DbName;
String DbVersion;
...
map = read(this, DbName, DbVersion);

//The DbName and DbVersion is null or empty?

public HashMap<String, String> read(Context con, String name, String version) {

    ...
    DatabaseMap.put(name, GotDbName);   // If name is null, how to get?
    DatabaseMap.put("name", GotDbName); // Maybe
    DatabaseMap.put(version, GotDbVersion);
    Log.d("Read File", " Database Name =" + GotDbName
            + "Database Version =" + GotDbVersion);
    return DatabaseMap;
}

Comment: and what do you expect?
Comment: Set a string for DbName and DbVersion, then you could get something here:
String abc = map.get(DbName);
String abc2 = map.get(DbVersion);
Comment: Values of string that they got from csv file. Which are stored in GotDbName and GotDbVersion. I can see their value in this log of library class Log.d("Read File", " Database Name =" + GotDbName
            + "Database Version =" + GotDbVersion);
Comment: Code only answers are specifically defined to be low quality unless the code is short, concise and self-documenting. This is neither of the 3.

HasMap Function returning null value


prove $a,b,c \in\mathbb{Z}$ Show that $\gcd(a,b)=1$ and $\gcd(a,c)=1$ iff $\gcd(a,[b,c])=1$

Question: I have to prove that if $a,b,c,d \in\mathbb{Z}$ Show that $gcd(a,b)=1$ and $\gcd(a,c)=1$ iff $\gcd(a,[b,c])=1$ I've tried proving the forward direction and im stuck.
Proof:
Suppose that $\gcd(a,b)=1$ and $\gcd(a,c)=1$. Let $d=\operatorname{lcm}[b,c]$. By definition we know that $b\mid d$ and $c\mid d$ But by assumption we get $a\nmid b$ and $a \nmid c$... I'm stuck right here. I just need a little hint to show that $a\nmid d$.
Comment: Can someone explain to me what (a,b) notation means?
Comment: oh it means gcd
Answer: Hint:
Suppose, $p\mid(a,[b,c])\implies p\mid a \ \text{and} \ p\mid[b,c]$.
$p\mid[b,c]\implies p\mid b$ or $p\mid c$
....continue!
Prime factorization of $a,b,c$ will be a good way to think about (at least for $\impliedby$ direction).
Comment: ok ill take it from here tomorrow. thanks


Confidence interval and sample size multinomial probabilities

Question: I'm an absolute beginner in statistics. Please excuse any wrong assumptions or missing information in my question.
I have a question that relates to a multinomial distribution (not even 100% sure about this) that I hope somebody can help me with.
If I take a sample (lets assume $n=400$) on a categorical variable that has more than two possible outcomes (e.g. blue, black, green, yellow) and plot the frequencies so that I can derive the probabilities. E.g.:
black 10%
blue 25%
green 35%
yellow 30%
How could I compute the 95% confidence interval for those probabilities?
And how could I determine the sample size required in order to get an accurate result within +-3% for each probability?
Please let me know if the answer to the question requires any additional information.
Comment: Welcome to the website, you may want to do a search on `maximum likelihood estimation` and `standard error`, this [link](http://stats.stackexchange.com/questions/88481/what-is-meant-by-the-standard-error-of-a-maximum-likelihood-estimate) may be a good start. P.S: Although they are talking about a different distribution (Pareto) in the link, the concepts apply to your case.
Comment: Then you can simply do this for each category separately (e.g. black vs. non-black).
Comment: Also check this out: http://sites.stat.psu.edu/~sesa/stat504/Lecture/lec3_4up.pdf
Comment: Hi Michael, I think in this case it could work with a binomial distribution and I would use the normal distribution (since it's approximately the same) to calculate the confidence interval. Please correct me if I'm wrong.
Comment: Would you know how to do it if you got only two categories instead of four?
Comment: Hi Zhubarb, thanks a lot for the links I will read through them and try to follow the instructions.
Answer: Thank you very much again for your help. Below is the (hopefully correct) solution using the "Normal Approximation Method" of the Binomial Confidence Interval:
Comment: For the sample size in binomial designs, sometimes one uses the 'worst' case p = 0.5 because usually the proportions are not known in advance. Further note that there are slightly better methods that the simple z approximation, e.g. Wilson's method. But your solution looks nice anyway.
Comment: Hi Michael, thanks a lot for the additional tips and the confirmation. Really appreciated.
Comment: I think there might be a mistake in the equation in the spreadsheet. In the standard error (s.e.) you need to divide by the overall sample size (n=400), not the number of realizations for each category.
Answer: I would like to add Wilson's method mentioned by Michael M in a comment.
From Wikipedia: Binomial proportion confidence interval - Wilson_score_interval.
You can get a 95% confidence interval by using the following:
$\frac{n_s + \frac{z^2}{2}}{n+z^2} \pm \frac{z}{n+z^2}\sqrt{\frac{n_s n_f}{n}+\frac{z^2}{4}}$
The left term is the center value and the right term gives the value you have to add / subtract to get the interval bounds.
$n_s$ is the number of samples in that category, $n_f$ the number of samples not in that category, $n$ the total number of samples and $z$ is 1.96 if you want a 95% confidence interval*
For high counts it gives the same results of the normal approximation, however this should be better for low counts or extreme values.
As an example, I had a category with 0 samples and the normal approximation returned a 0 s.e., and thus an absured confidence interval of 0-0 (as it was certain that it has 0% probability, while actually it had 0 occurence only because of the few samples).
$ $
* The method is actually for a binomial distribution and $n_s$ and $n_f$ are successes and failures on that distribution.
However, I think it can be reasonably used for a multinomial, even though it does not account for the fact that estimated probabilities must sum up to 1.
The normal approximation doesn't account for that either afaik.
Answer: There are several methods to get confidence intervals for multinomial proportions, and many of them are implemented in R's function MultinomCI() from the DescTools package:
> DescTools::MultinomCI(400 * c(0.10, 0.25, 0.35, 0.30), sides = "two.sided", method = "sisonglaz")
      est lwr.ci    upr.ci
[1,] 0.10   0.05 0.1549989
[2,] 0.25   0.20 0.3049989
[3,] 0.35   0.30 0.4049989
[4,] 0.30   0.25 0.3549989

For details, see https://cran.r-project.org/web/packages/DescTools/DescTools.pdf


jupyter notebooks-safe asyncio run wrapper method for a library

Question: I'm building a library that leverages asyncio internally.
While the user shouldn't be aware of it, the internal implementation currently wraps the async code with the asyncio.run() porcelain wrapper.
However, some users will be executing this library code from a jupyter notebook, and I'm struggling to replace the asyncio.run() with a wrapper that's safe for either environment.
Here's what I've tried:
ASYNC_IO_NO_RUNNING_LOOP_MSG = 'no running event loop'

def jupyter_safe_run_coroutine(async_coroutine, _test_mode: bool = False)
    try:
        loop = asyncio.get_running_loop()
        task = loop.create_task(async_coroutine)
        result = loop.run_until_complete(task) # <- fails as loop is already running
        # OR
        asyncio.wait_for(task, timeout=None, loop=loop) # <- fails as this is an async method
        result = task.result()
    except RuntimeError as e:
        if _test_mode:
            raise e
        if ASYNC_IO_NO_RUNNING_LOOP_MSG in str(e):
            return asyncio.run(async_coroutine)
    except Exception as e:
        raise e

Requirements

We use python 3.8, so we can't use asyncio.Runner context manager
We can't use threading, so the solution suggested here would not work

Problem:
How can I wait/await for the async_coroutine, or the task/future provided by loop.create_task(async_coroutine) to be completed?
None of the methods above actually do the waiting, and for the reasons stated in the comments.

Update
I've found this nest_asyncio library that's built to solve this problem exactly:

ASYNC_IO_NO_RUNNING_LOOP_MSG = 'no running event loop'

HAS_BEEN_RUN = False

def jupyter_safe_run_coroutine(async_coroutine, _test_mode: bool = False):
    global HAS_BEEN_RUN
    if not HAS_BEEN_RUN:
        _apply_nested_asyncio_patch()
        HAS_BEEN_RUN = True
    return asyncio.run(async_coroutine)

def _apply_nested_asyncio_patch():
    try:
        loop = asyncio.get_running_loop()
        logger.info(f'as get_running_loop() returned {loop}, this environment has it`s own event loop.\n'
                    f'Patching with nest_asyncio')
        import nest_asyncio
        nest_asyncio.apply()
    except RuntimeError as e:
        if ASYNC_IO_NO_RUNNING_LOOP_MSG in str(e):
            logger.info(f'as get_running_loop() raised {e}, this environment does not have it`s own event loop.\n'
                        f'No patching necessary')
        else:
            raise e

Still, there are some issues I'm facing with it:

As per this SO answer, there might be starvation issues
Any logs written in the async_coroutine are not printed in the jupyter notebook
The jupyter notebook kernel occasionally crashes upon completion of the task

Edit
For context, the library internally calls external APIs for data enrichment of a user-provided dataframe:
# user code using the library
import my_lib

df = pd.DataFrame(data='some data')
enriched_df = my_lib.enrich(df)

Comment: I don't understand why you would need to start the event loop yourself? Packages will typically provide asynchronous functions that will be consumed by a user who already has a running event loop. You (most likely) don't need to worry about how the user will start its loop. Nonetheless, I've come across one guy that made such a prototype for fun here https://stackoverflow.com/a/61331974/1720199
Comment: I don't need to start the event loop, I need to register the provided `async_coroutine` as a task with the existing running loop and then wait for its completion.
Answer: It's usually a good idea to expose the asynchronous function. This way you will give your users more flexibility.
If some of your users can't (or don't want to) use asynchronous calls to your functions, they will be able to call the async function using asyncio.run(your_function()). Or in the rare situation where they have an event loop running but can't make async calls they could use the create_task + add_one_callback method described here. (I really have no idea why such a use case may happen, but for the sake of the argument I included it.)
Hidding the asynchronous interface from your users is not the best idea because it limits their capabilities. They will probably fork your package to patch it and make the exposed function async or call the hidden async function directly. None of which is good news for you (harder to document / track bugs). I would really suggest to stick to the simplest solution and provide the async functions as the main entry points.
Suppose the following package code followed by 3 different usage of it:
async def package_code():
    return "package"

Client codes
Typical clients will probably just use it this way:
async def client_code_a():
    print(await package_code())

# asyncio.run(client_code_a())

For some people, the following might make sense. For example if your package is the only asynchronous thing they will ever use. Or maybe they are not yet confortable using async code (these you can probably convince to try client_code_a instead):
def client_code_b():
    print(asyncio.run(package_code()))

# client_code_b()

The very few (I'm tempted to say none):
async def client_code_c():
    # asyncio.run() cannot be called from a running event loop:
    # print(asyncio.run(package_code()))
    loop = asyncio.get_running_loop()
    task = loop.create_task(package_code())
    task.add_done_callback(lambda t: print(t.result()))

# asyncio.run(client_code_c())

Answer: I'm still not sure to understand what your goal is, but I'll describe with code what I tried to explain in my comment so you can tell me where your issue lies in the following.
If you package requests the user to call some functions (your_package_function in the example) that take coroutines as arguments, then you shouldn't worry about the event loop.
That means the package shouldn't call asyncio.run nor loop.run_until_complete. The client should (in almost all cases) be responsible for starting the even loop.
Your package code should assume there is an event loop running. Since I don't know your package's goal I just made a function that feeds a "test" argument to any coroutine the client is passing:
import asyncio

async def your_package_function(coroutine):
    print("- Package internals start")
    task = asyncio.create_task(coroutine("test"))
    await asyncio.sleep(.5) # Simulates slow tasks within your package
    print("- Package internals completed other task")
    x = await task
    print("- Package internals end")
    return x

The client (package user) should then call the following:
async def main():
    x = await your_package_function(return_with_delay)
    print(f"Computed value = {x}")

async def return_with_delay(value):
    print("+ User function start")
    await asyncio.sleep(.2)
    print("+ User function end")
    return value

await main()
# or asyncio.run(main()) if needed

This would print:
- Package internals start
- Package internals completed other task
+ User function start
+ User function end
- Package internals end
Computed value = test

Comment: Ok, then why not expose the async function? So the user can call `await my_lib.enrich(df)`. It makes more sense than giving no opportunity to make an async call. Your function makes async call, don't try to hide it. People using it will soon notice the function is very slow, then understand it makes async calls. At that point they will probably fork your package to patch it and make the function async. If it is async, some (probably rare) users will have a use case where they need to call it synchronously, but for them it will only require to use the techniques linked above (no patch needed).
Comment: The client isn't passing any async coroutines; that's an internal implementation detail. Specifically, it makes API calls to get some data enrichment from some vendor.
Comment: Ah ok, I see, the client gives a function (not a coroutine) and your packages makes calls depending on some results of the input function? When you say "internal implementation detail" does that mean you expose a synchronous interface to your client? If that's the case then you probably want to expose asynchronous functions instead. The client, if he wishes to ignore that functionality you are offering, will then be able to decide how to call your asynchronous function.

If you really want to limit your functionalities then you can do this : https://stackoverflow.com/a/61331974/1720199
Comment: But I really think you should expose the better version of your API (the async one). And if you are worried that some clients will refuse to use async code, then you can document how to call your functions when there is no event loop running (like the `add_done_callback` strategy proposed in the previous link).
Comment: Added context to how the library is used to the question
Comment: Thank you @cglacet, this is sensible advise
Comment: I just added another answer that better fit your actual question (basically my earlier comment in a nicer form). I will soon remove that answer.
Comment: I think that is an acceptable answer, why would you want to remove it?
Comment: I can leave it as is. But it doesn't really answer your question. I'll leave the decision to reviewers then.
Comment: That's a fair point, but sometimes the answer should be you shouldn't do it, here's why, and here's what you can do insted.