Computing limiting transition probabilities with absorbing states

Question: A bank classifies loans as paid in full (F), in good standing (G), in arrears (A), or as a bad debt (B). Loans move between the categories according to the following transition probability:
$$B = \begin{pmatrix}1.0000 & 0 & 0 & 0 \\\ 0.1000 & 0.8000 & 0.1000 & 0 \\\ 0.1000 & 0.4000 & 0.4000 & 0.1000 \\\ 0 & 0 & 0 & 1.0000 \end{pmatrix} $$
What fraction of loans in good standing are eventually paid in full? What is the answer for those in arrears?
My Work
I am not sure how to go about this. I know how to compute transition probabilities for irreducible, aperiodic chains, but when I raise this transition matrix to a high power on MATLAB, I get
$$ ans = \begin{pmatrix} 1.0000 & 0 & 0 & 0 \\\ 0.8750 & 0 & 0 & 0.1250 \\\ 0.7500 & 0 & 0 & 0.2500 \\\ 0 & 0 & 0 & 1.0000\end{pmatrix} .$$
So I can answer this question, I'm just not sure how to symbolically find these limiting probabilities.
Answer: To answer that question you need to know a bit of linear algebra, and in particular about matrix diagonalization.
You can decompose matrix $B$ as the following matrix product.
$$B = P \Lambda P^{-1}, $$
where the columns of P are eigenvectors and $\Lambda$ is a diagonal matrix, with eigenvalues on the diagonal. Note that
$$B^n = P \Lambda P^{-1} \ldots P \Lambda P^{-1} = P \Lambda^n P^{-1},$$
and that $\Lambda^n$ is very easy to compute, because it consists of the eigenvalues raised to the power $n$. In addition, all we need to know in order to compute the limit of $\Lambda^n$ is whether the values qre larger or smaller than 1.
When all values in $B$ are positive, the Perron-Frobenius guarantees that 1 is the unique largest (in modulus) eigenvalue. In general you can prove that 1 is always an eigenvalue of $B$ and in your case it is an eigenvalue of order 2 because you have two absorbing states. The other two eigenvalues are smaller than 1, and quickly go to 0 when raised to the power $n$. So the answer is the result of
$$ P \begin{pmatrix}1 & 0 & 0 & 0 \\\ 0 & 1 & 0 & 0 \\\ 0 & 0 & 0 & 0 \\\ 0 & 0 & 0 & 0 \end{pmatrix} P^{-1}.$$
Here is how you can do it with R
<code>B = matrix(c(1, .1, .1, 0, 0, .8, .4, 0, 0, .1, .4, 0, 0, 0, .1, 1), ncol=4)
eig = eigen(B)
# Show the eigen values.
eig[['values']]
# [1] 1.0000000 1.0000000 0.8828427 0.3171573
# Notice that 1 is there two times and the other two are
# less than 1.
P = eig[['vectors']]
# Show the matrix P.
P
# Show the answer.
P %*% diag(c(1,1,0,0)) %*% solve(P)
</code>
Answer: For a system this small, you can do everything by hand.
Let $x_i$ be the probability that you end up paid in full starting in state $i$. Use the transition probabilities to write one equation per state, saying that $x_i$ equals the weighted average of $x_j$, where the weight is the transition probability from $i$ to $j$ in one step. In other words, the chance to end up paid in full equals the expected value of the chance to be paid in full after the next step. For example, $x_G = 0.1 x_F + 0.8 x_G + 0.1 x_A$.
This gives you $4$ equations in $4$ unknowns, which should sound promising. However, $2$ of those equations are $x_F = x_F$ and $x_B = x_B$. You should replace those with $x_F = 1$ and $x_B = 0$.


Is there way for create custom "add userpoints transaction" form

Question: Good day to everyone!
I have view which show user list, current userpoints, and email. I want set some link, which will lead to add transaction form where name will already fill. Is there way to add userpoints transaction for specific user except standard form?
Answer: Step 1
Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Grant user points, to the user specified as a parameter for this Rules Component.
For an example of a Rules Action to grant user points, refer to the rule included in the answer to "How to grant User Points to viewing user when user has viewed content?".
Step 2
Create a view of the group of users for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.
Tutorial
To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.
Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
Comment: you are the greatest answer writer! Thank you a lot!!!
Comment: @NashGC merci for the kudos (and accept), though "greatest" is probaby too much. So "what else" or "what's your next challenge"? PS: can you fix your typo in your title (at the end)?
Comment: I will learn about VBO, it's my nearest challenge and I think it's my last part "technical side" of my project. I hope so)


How do I hand off a file from an ASP page to a C# function?

Question: I am writing a part of a web application that takes a user provided file from the browser, saves it to the server and then hands the file off to an automated excel script, then returns the processed file to the browser. I am getting the file using an <asp:FileUploader> which hands if off to a VB script. Is there a way to call a C# script from within the VB code?
Comment: By the way, try to avoid the word "*script*" when talking about C#/VB. Both are not scripting languages. Instead, try "C# project" or "C# application". This will lead to less confusion when communicating your problem in the future.
Answer: Create a separate C# class library project that is referenced by your VB.NET ASP site (but exists within the same solution). That's the only (easy) way you can mix C# and VB code.


fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'

Question: I use Visual Studio 2010 Premium. I have two project A and B and I try to compile both to a 64-bit platform.
Project A outputs a .dll and a .lib file which project B relies on.
I already compiled successfully project A to a 64-bit platform, yet when I compile project B I get the following error :

mfcs100d.lib(nolib.obj) : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'

What could be the problem ? I don't really know what is this mfcs100d.lib file.
I've used "Dependency Walker" on project A's dll file and it seems to be relying solely on 64-bit dll files.
Additionally, I went to the Project B's (Property Pages -> Configuration Properties -> Linker -> Advanced) and confirmed that 'Target Machine' is set to "MachineX64".
Also, On the Configuration Manager the Platform is set to x64.
Someone infromed me that the problem may be such :
Going to project B's (Property Pages -> Configuration Properties -> C\C++ -> Preprocessor -> Preprocessor Definitions) I have the following values there :
<code>WIN32
_DEBUG
_WINDOWS
_AFXEXT
</code>
Is that truly related ? Should I replace the 'WIN32' value ? if so, then how ? I don't really understand the meaning of those definitions and how to change them.
Edit : I just realized that probably it's not related at all. Those are simply definitions for the preprocessor, such as the ones which can be determined by a C++ #define command. Yet I could be wrong.
Comment: Don't get rid of WIN32, even compiling 64-bit code it's still the Win32 API so you need WIN32 defined.
Answer: Pretty hard to get this wrong.  Start with Build + Configuration Manager and double-check that x64 is selected for both projects.  Next step is to verify the library search path.  Right-click the project, Properties, VC++ Directories, Library Directories.  Click on the combobox arrow to view the "Inherited values".  $(VCInstallDir)atlmfc\lib\amd64 should be the second in the list, that's where the 64-bit version of mfcs100d.lib is located.
Comment: The 1st value on the list is $(VCInstallDir)bin\x86_amd64
The 2nd is $(VCInstallDir)bin.
How can I change the 1st value to $(VCInstallDir)atlmfc\lib\amd64 ? It seems like I can not rewrite this iteam and adding a new item caused me an error.
Comment: You are looking at the wrong setting, look at *Library Directories*, not Executable Directories.
Comment: Oh yeah, sorry.
Yes, the value $(VCInstallDir)atlmfc\lib\amd64 is written there indeed, so I wonder to myself what is the problem.
Answer: When you add the x64 target, go into the General settings and look at Output Directory and Intermediate Directory.  For the Debug target change from "Debug" to "Debug64", same for Release target.
Comment: Can you add a screen shot of this please?


Separar dados na tabela

Question: Eu gostaria de fazer uma tabela separada por "temporadas". Exemplo:
Tabela estatisticas:
Temporada 1:
    ID | JOGADOR | PTS | AST |
    0  | Leonard | 12  | 7   |
    1  | Pedro   | 10  | 5   |
    Temporada 2:
    ID | JOGADOR | PTS | AST |
    0  | Leonard | 08  | 02  |
    1  | Pedro   | 09  | 03  |

Gostaria que fosse apenas uma tabela, isso é possível? Se sim como eu posso fazer?
Comment: Caso a resposta esteja certa, por favor não se esqueça de marcar como correta.
Answer: Só adicionar uma coluna a mais, não?
Como ficaria:
ALTER TABLE estatisticas ADD COLUMN 'temporada' INT(1) NOT NULL FIRST;

E quando for fazer o select:
SELECT * FROM estatisticas ORDER BY temporada ASC;

Comment: Eu poderia adicionar dois jogadores iguais com temporadas diferentes?
Comment: Sim, mas o nome do jogador nem o ID pode ser `unique`.
Comment: O certo mesmo seria você ter uma tabela só para os jogadores e outra para as estatísticas, dai você faria uma chave estrangeira para o ID do jogador.
Comment: Eu tenho uma tabela apenas para os jogadores, como eu faria isso?
Comment: Pode me mostrar suas tabelas?
Comment: tabela players: http://i.imgur.com/IoF2MVR.png e tabela stats: http://i.imgur.com/DrdNZdx.png
Comment: No seu caso, a maneira do qual eu fiz na resposta cabe bem.

Separar dados na tabela


Presenting the assumptions of Pearson's chi-squared test with Yates' Correction

Question: One of the assumptions of Pearson's chi-squared test (for independence) is that expected frequencies are all >=5 in a 2x2 table OR 80% of the expected frequencies are >=5 in larger tables.
If this is not the case for a 2x2 table, Yates' correction can be applied.
When presenting data, it is good practice to state the assumptions. If Yates' correction has been applied, is it correct to:
a) show that the expected frequency assumption is NOT met (hence the use of Yates' correction)
OR
b) not state the expected frequency assumption at all i.e. does it cease to be an assumption of the test?
Comment: These criteria are *not* "assumptions" of the test: they are rules of thumb to indicate when you should be cautious about interpreting the p-value as computed from a chi-squared distribution.  The 80% rule of thumb, in particular, is too crude for really large tables.  The communications issues, then, are that when you are aware the computed p-value might be misleading, (a) how *should* you determine the p-value and (b) how should you explain your determination to your readers?
Comment: The idea is to tell people what they need to know to duplicate what you have done, so the answer is a).
Comment: Thanks for replying. Why did you not post that as an answer?
Answer: The idea is to tell people what they need to know to duplicate what you have done, so the answer is a) show that the expected frequency assumption is NOT met (hence the use of Yates' correction). In general, when doing something that is more correct, for example, correcting standard deviation for small number bias, using Student's t rather than a normal distribution when it is correct to do so, it is incumbent upon the author present with clarity such that the ability of the reader to duplicate independently whatever was done is maintained. However, one does not have to belabor the point, e.g., "with Yate's correction" is enough.


Looking for philosophical subject for my Bachelor Thesis

Question: In may 2013 I have to write a Bachelor Thesis for my bachelor Mathematics. I prefer to choose a subject which involves philosophy. At the same time I have the feeling that my university wants me to write a more technical thesis (which I do not prefer). So I want to be prepared to claim that a philosophical subject is technically enough.
What are great subjects that combine mathematics with philosophy?
I thought for example about what mathematical structures really are. What is the relation between mathematics and the reality? Are we discovering the reality or are we constructing while we learn/discover mathematics.
I have followed courses about logic: on introductionary level and some more advanced logical topics (like modal logic, many-valued logic, time logic, non-monotonic reasoning). Maybe I can combine philosophy with such topics? If anyone has a good idea, I would like to hear it!
Comment: Ask your advisor.
Comment: You might get some ideas here: http://mathoverflow.net/questions/94354/essential-reads-in-the-philosophy-of-mathematics-and-set-theory
Comment: I'm not sure what exactly can a bachelor thesis be, but perhaps people in the mathematics department are expecting it to be *about mathematics neto*. What you probably want to do could perhaps better fit in graduate school, unless you made heavily philosophical flavoured undergraduate title...\
Comment: Try mathematical logic or axiomatic set theory.
Comment: I don't know if it counts as related to philosophy, but I always enjoyed mathematical, sometimes counterintuitive paradoxes such as Monty Hall's problem. More related to set theory, you have e.g. Russell's paradox and the Banach-Tarski paradox.
Answer: It very much depends what maths you have already done. It would be a lot of work to both learn enough about a new topic $X$ and then engage with broadly philosophical discussions about $X$.
But if you have done/are doing a course in set theory, there are obviously interesting questions to be discussed there. You are unlikely to be in a position to write usefully about e.g. large cardinal axioms ("do we need new axioms?"), but there are more basic questions. What's so great about ZFC? Why this set theory rather than one of its rivals? Does it even best encapsulate the hierarchical conception of the set universe? Michael Potter's Set Theory and its Philosophy could be useful here.
If you have done/are doing a course on computability, there are other interesting questions to be discussed. The significance of limitative results like Gödel's theorem and/or the unsolvability of the Halting Problem. Or: why should we believe the Church-Turing Thesis? My Introduction to Gödel's Theorems could be useful here.
Topics in these areas would give you a chance to show some mathematical knowledge (presumably a requirement). Very general discussion about the notion of structure is unlikely to go down so well for a maths degree (though you can only find out by consulting your advisors), while discussing e.g. the light thrown on on the notion of structure by category theory will require going too far beyond the BA level maths you know.
So my summary advice: for a BA-level thesis, look for some relatively narrow topic related to sufficiently advanced topics you already know something of. Avoid over-general topics like "what mathematical structures really are". [I'd say the same, mutatis mutandis, for BA level philosophy theses!]
Comment: @JoyeuseSaintValentin: If you want to investigate questions like "what is the relation between reality and mathematics?" and "what are mathematical structures?" and enjoy a logical approach, can I suggest looking into some of the ultrafinitists and related?  Some take the approach that mathematics is a physical process, something occuring in a universe with limited finite resources, and so one cannot validly reason about things with infinite characterisations.  There are several flavors, and plenty of opportunity to discuss semantics, models, and what mathematical reasoning is _about_.
Comment: TY. This is a useful answer.

In addition to my question: I have followed courses about logic: on introductionary level and some more advanced logical topics (like modal logic, many-valued logic, time logic, non-monotonic reasoning). Maybe I can combine philosophy with such topics? If anyone has a good idea, I would like to hear it!
Comment: What are ultrafinits?
Answer: I guess you could try to look something about foundation of mathematics, which I believe it's considered a subfield of the broader philosophy of mathematics.
There's a lot of interesting stuff here set theory and logical system which I think are interesting from a philosophical point of view, although they are really mathematical and involve also a lot application in ,maths but also in computer science (in particular I'm aware of the interconnection of this subject with calculability theory).
Hope this help.
Answer: You may be interested in this paper by Barry Mazur at Harvard.
"When is one thing equal to some other thing"
What motivated me to mention it to you is a remark early on:
"I don't even see how questions about these issues can even be raised within the framework of vocabulary that people employ when they talk about the foundations of mathematics for so much of the literature on philosophy of mathematics continues to
keep to certain staples: formal systems, consistency, undecidability, provability and unprovability, and rigor in its various manifestations."
So I thought that perhaps this might open a somewhat different door.
It is linked in the "Further Reading" section of the first answer to this very interesting question here:
Why do we look at morphisms?
There are two sections that might be of special interest:
-- Defining Natural Numbers
-- Equality vs. Isomorphism
Comment: This looks good. Thank you for sharing. I will definitely consider it.
Comment: My pleasure. Best of luck


Setup Simple Injector with ASP.NET Identity 2.2.1

Question: So I've been trying to setup ASP.NET Identity 2.2.1 and I keep hitting roadblocks.  For being something that is supposed to be auto-generated by the framework it sure seems complicated to configure.  I think I'm almost there but I'm still having issues setting up IoC with Simple Injector.
I've been reading through other StackOverflow questions and blogs about these issues.  Most of them seem out of date because they deal with ASP.NET Identity 1.0.  There's even been enough changes from 2.0 to 2.2.1 I've run into some issues with out of date solutions.  Or the solutions deal with other IoC frameworks and I just can't translate them to Simple Injector. I've used other IoC Frameworks but I'm new to Simple Injector.
UPDATE - Ric .Net's first link in his comment was very helpful.  I've reformatted my work to fit his suggestions and I think I'm almost there.  But I'm still having one issue.  I've completed replaced the previous code with the code below.
1) I updated ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(string connectionstring)
        : base(connectionstring, throwIfV1Schema: false)
    {
    }
}

2) I removed the Create() method from ApplicationUserManager and moved it into a class that initializes all of my Simple Injector code:
public static class SimpleInjectorInitializer
{
    public static Container Initialize(IAppBuilder app)
    {
        var container = GetInitializeContainer(app);

        container.Verify();

        DependencyResolver.SetResolver(
            new SimpleInjectorDependencyResolver(container));

        return container;
    }

    public static Container GetInitializeContainer(
              IAppBuilder app)
    {
        var container = new Container();

        container.RegisterSingle<IAppBuilder>(app);

        container.RegisterPerWebRequest<
               ApplicationUserManager>();

        container.RegisterPerWebRequest<ApplicationDbContext>(()
          => new ApplicationDbContext(
           "Your constring goes here"));

        container.RegisterPerWebRequest<IUserStore<
          ApplicationUser>>(() =>
            new UserStore<ApplicationUser>(
              container.GetInstance<ApplicationDbContext>()));

        container.RegisterInitializer<ApplicationUserManager>(
            manager => InitializeUserManager(manager, app));

        container.RegisterMvcControllers(
                Assembly.GetExecutingAssembly());

        return container;
    }

    private static void InitializeUserManager(
        ApplicationUserManager manager, IAppBuilder app)
    {
        manager.UserValidator =
         new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        //Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator()
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        var dataProtectionProvider =
             app.GetDataProtectionProvider();

        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
             new DataProtectorTokenProvider<ApplicationUser>(
              dataProtectionProvider.Create("ASP.NET Identity"));
        }
    }
}

3) I changed the Configuration method in Startup.cs:
public void Configuration(IAppBuilder app)
{
    var container = SimpleInjectorInitializer.Initialize(app);
    ConfigureAuth(app, container);
}

4)  I updated ConfigureAuth in Configure.Auth.cs:
public void ConfigureAuth(IAppBuilder app, Container container)
{
    // Configure the db context and user manager to use a single instance per request
    //app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext(container.GetInstance<ApplicationUserManager>);
    // Rest of code here ...

5) Then I removed the default constructor and UserManager property from AccountsController.
The problem I'm having now is that since ASP.NET Identity 2.0, they have added the parameter ISecureDataFormat<AuthenticationTicket> accessTokenFormat to the AccountsController constructor.
public AccountController(ApplicationUserManager userManager,
    ISecureDataFormat<AuthenticationTicket> accessTokenFormat)

So now, how do I add DI for ISecureDataFormat<AuthenticationTicket> in Simple Injector?
Comment: Did you read [this](https://simpleinjector.codeplex.com/discussions/564822) already? It doesn't discuss the 'IdentityFactoryOptions' but must give some guidance. Also see [this](http://stackoverflow.com/a/28948205/3294832) for a better method than the factory you mention.
Comment: Have you read [this](https://simpleinjector.readthedocs.io/en/latest/LifestyleMismatches.html)? You should register the IdentityFactoryOptions as scoped or singleton. And no, it's not really you who is violating best peactices; it's Identity Feamework with its amazingly bad Visual Studio template.
Comment: [Here is a walkthrough](http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/) that covers how to refactor the default MVC 5 template for integration with Autofac, SimpleInjector, or Unity.
Comment: Thanks everyone for the help and comments.
@Ric.Net - Thanks for your first link.  It was very helpful.  This way seems much clearer than the way I previously cobbled together.  I'm still running into a small issue though.
Comment: @Steven - I had seen that, but it didn't help.  I'm glad I'm not the only one that questions Identity Framework's VS template.
Comment: @NightOwl888 - I tried using that version before, but it was very out of date.  I believe it uses Identity 1.0.
Answer: So between the help Ric .Net (which I've posted above as part of the question) and Lucas Teles answer in another question I've finally got my answer. Lucas suggested adding these lines to my Simple Injector setup:
container.Register<ISecureDataFormat<AuthenticationTicket>,
    SecureDataFormat<AuthenticationTicket>>(Lifestyle.Scoped);
container.Register<ITextEncoder, Base64UrlTextEncoder>(Lifestyle.Scoped);
container.Register<IDataSerializer<AuthenticationTicket>, TicketSerializer>(
    Lifestyle.Scoped);
container.Register<IDataProtector>(
    () => new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider()
        .Create("ASP.NET Identity"),
    Lifestyle.Scoped);

So now my container building method looks like this:
public static Container GetInitializeContainer(IAppBuilder app)
{
    var container = new Container();

    // IoC for ASP.NET Identity
    container.RegisterSingleton<IAppBuilder>(app);
    container.Register<ApplicationUserManager>(Lifestyle.Scoped);
    container.Register<ApplicationDbContext>(
        () => new ApplicationDbContext("Your constring goes here"),
        Lifestyle.Scoped);
    container.Register<IUserStore<ApplicationUser>>(
        () => new UserStore<ApplicationUser>(
            container.GetInstance<ApplicationDbContext>()),
        Lifestyle.Scoped);
    container.RegisterInitializer<ApplicationUserManager>(
        manager => InitializeUserManager(manager, app));
    // Setup for ISecureDataFormat
    container.Register<ISecureDataFormat<AuthenticationTicket>,
        SecureDataFormat<AuthenticationTicket>>(Lifestyle.Scoped);
    container.Register<ITextEncoder, Base64UrlTextEncoder>(Lifestyle.Scoped);
    container.Register<IDataSerializer<AuthenticationTicket>,
        TicketSerializer>(Lifestyle.Scoped);
    container.Register<IDataProtector>(
        () => new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider()
            .Create("ASP.NET Identity"),
        Lifestyle.Scoped);

    // Register all controllers
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    return container;
}

Comment: This article also has some good notes about the `DataProtectionProvider` that normally comes from `IdentityFactoryOptions` - http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/


What does $f(5x)$ mean when I differentiate?

Question: if
$$f(5x)=x^2 + x$$
$$f '(2) = ?$$
Answer is 9/25
But I do not know how it came
How i can factor or simplify $$f(5x)$$
but i want understand what f(5x) mean?
Comment: chain rule :$5f'(5x)=2x+1$ put $x=2/5$. here
Comment: Firstly, you need $f(y) = y^2/25 + y/5$.
Comment: that's wrong the answer is 9/25 when x=2
i want know how !
Comment: I think the point here is finding $f'(2)$ without finding a general formula for $f(y)$.
Comment: @johnwick But we just left you $2$ answers below.
Comment: @Rebellos i will see you answer
Comment: @johnwick Sorry, I find that daulomb's method is correct. Please double check it.
Answer: The derivative of the expression $f(g(x))$ is given as :
$$[f(g(x))]'=f'(g(x))\cdot g(x)$$
supposing that $f,g$ are differentiable functions.
This means that :
$$[f(5x)]'=f'(5x)\cdot (5x)'=5f'(5x)$$
which means, taking the derivative on both sides of $f(5x) = x^2 + x$, you'll get :
$$[f(5x)]'=\frac{2}{5}x+\frac{1}{5}$$
Now, just setting $x=2/5$, you'll yield your result for $f'(2) = 9/25$.
This is important to know (the chain rule) because such differentation issues occur often.
Alternatively, you could just let $t=5x$ and substitute and calculate from there on.
Comment: @GNUSupporter No worries :-)
Comment: Thanks for your answer. [+1] Yet, when setting $x = 2/5$, you still assume there is a $y = 5x$ in your mind.
Comment: @Ryan Sure I do, yes. Better not to say that $y=5x$ by the way, since $y=f(x)$ in the cartesian coordinates system. Let's say that in order to get the number $2$ from the expression $5x$ you'd need $x=2/5$. Alternatively, it just follows from letting $t=5x$ and substituting.
Comment: Yes, you are right. Using $y$ is indeed confusing. Thanks :-)
Comment: @johnwick I have edited Rebellos' answer, and please wait it for peer review.
Comment: @Ryan okay .. also i have edited my question to be more clear
Comment: @Ryan Sorry for rejecting your edit.  I didn't see the comments during the review.
Comment: I don't why my eyes saw a random function but thanks for the edit/correction !
Answer: Setting $$t=5x$$ then we get
$$f(t)=\left(\frac{t}{5}\right)^2+\frac{t}{5}$$
then we get $$f'(t)=...$$
Comment: yes Dr this is the correct answer thx
but why we setting t = 5x ?
Comment: @johnwick This is probably because you need $5x = 2$ and $2$ can be regarded as $t = 2$.
Comment: @Ryan but i want (5x)' =2 Is there a difference
Comment: @johnwick $(5x)' = 5$ and it cannot be $2$.
Comment: @johnwick You do **not** want $5x=2$, you want $f'(5x) \to f'(2)$ which means $5x=2 \Leftrightarrow x = 2/5$


Proof of an identity with a nested summation

Question: Suppose for all $n>1$ the following equation is true:
$$\sum_{i=1}^{n}\sum_{j=1}^{n} |i-j|=\frac{n\left(n^{2}-1 \right)}{3}$$
Can I prove this by induction?
Is it possible to combine the two summations into one?
Comment: You can also try to break the second sum as $\sum_{ji}^n$ .
Comment: Hint: if the left side is $f(n)$, what is $f(n) - f(n-1)$?
Comment: Actually, we need not suppose that it is true, because it is indeed true. Of course, for an induction, we may assume that it is true for $n$, and deduce that it is true for $n+1$. Also, one should do the base case. Why do you exclude $n=1$?
Answer: Let us assume that the result is true for $n$, so
$\displaystyle \sum_{i=1}^{n}\sum_{j=1}^{n} |i-j| = \frac{n(n^{2} - 1)}{3}$.
So $\displaystyle \sum_{i=1}^{n+1}\sum_{j=1}^{n+1} |i-j| = \displaystyle \sum_{i=1}^{n}\sum_{j=1}^{n} |i-j| + \displaystyle \sum_{i=1}^{n}| i - (n+1)| + \displaystyle \sum_{j=1}^{n}|(n+1) - j|
\\= \frac{n(n^{2} - 1)}{3} + 2 \displaystyle \sum_{j=1}^{n}|(n+1) - j| =  \frac{n(n^{2} - 1)}{3} + 2 \frac{n(n+1)}{2}
\\= n(n+1)(\frac{n-1}{3} + 1)
\\= \frac{n(n+1)(n+2)}{3} =\frac{(n+1)((n+1)^{2} -1)}{2}$
So, the result is also true for $n+1$. By induction, rest follows...
Answer: For what its worth, my first try here would not be induction.
Tools
T-1 $~: ~\displaystyle \sum_{s=1}^t s = \frac{t(t+1)}{2}.$
T-2 $~: ~\displaystyle \sum_{s=1}^t s^2 = \frac{t(t+1)(2t+1)}{6}.$

For $~i \in \{1,2,\cdots,n\},~$ let $~f(i)~$ denote $~\displaystyle \sum_{j=1}^n |i - j|.~$
Then, you have that
$$\sum_{i=1}^n \sum_{j=1}^n |i - j| = \sum_{i=1}^n f(i).$$
To compute $~f(i),~$ consider the following tableau
<code>  j   =  1    2    3   ... i-1  i  i+1 i+2 ...  n
|i-j| = i-1  i-2  i-3  ...  1   0   1   2  ....n-i
</code>
So,
$$f(i) = \sum_{r=1}^{i-1} i-r ~~~~+ ~~~~ \sum_{r=1}^{n-i} i$$
$$= [ ~(i-1)i~] - \frac{(i-1)i}{2} + \frac{(n-i)(n+1-i)}{2}$$
$$= \frac{i^2 - i}{2} + \frac{n^2 + n - 2ni - i + i^2}{2}$$
$$= (i^2) - (n+1)(i) + \frac{n^2 + n}{2}. \tag1 $$

So, using the tools T-1 and T-2, and using (1) above, the final computation is
$$\sum_{i=1}^n f(i)$$
$$= \sum_{i=1}^n \left[ ~(i^2) - (n+1)(i) + \frac{n^2 + n}{2} ~\right]$$
$$= \frac{n(n+1)(2n+1)}{6} - \frac{(n+1)^2n}{2} + \frac{n \times (n^2 + n)}{2}$$
$$= n(n+1) ~\left[ ~\frac{2n+1}{6} - \frac{n+1}{2} + \frac{n}{2} ~\right]$$
$$= n(n+1) ~\left[ ~\frac{2n+1}{6} - \frac{1}{2} ~\right]$$
$$= n(n+1) ~\left[ ~\frac{2n-2}{6} ~\right]
 = n(n+1) ~\left[ ~\frac{n-1}{3} ~\right].$$
Answer: There is an instant proof via figurate numbers if you reframe the problem.
Consider an $n x n$ matrix $M$, with rows and columns indexed by $i,j$. If each entry $M_{ij}$ contains $|i-j|$, the sum of the whole matrix is the problem you pose.
The matrix $M$ is easy to envision: $0$ on the main diagonal, $1$ on the 1-diagonals, $2$ on the 2-diagonals, etc. Since the matrix is symmetric, the desired sum will be twice that of the upper triangle.
So consider the upper triangle. To the right of the main diagonal, each row reads ${1,2,3,..}$ until the matrix ends. The top row will run to $n-1$, and each successive row is one entry shorter until the $n^{th}$ row has no entry. The sum of the series ${1,2,3... \ n}$ is called a triangular number, $T_n$. Think of bricks, 1 on top of 2 on top of 3, etc. So the rows of the upper triangle represent $T_{n-1}, T_{n-2},... T_{1}$. Now, lay those triangles flat and imagine you start stacking them to form a triangular pyramid (1 on 3 on 6 on 10, etc.). The sum of the triangular numbers $T_1, T_2,... \ T_n$ is called the tetrahedral number, $Te_n$. The upper triangle of matrix $M$ contains $Te_{n-1}$.
The tetrahedral number for $n$ is $\frac{n(n+1)(n+2)}{6}$.
Thus $Te_{n-1} = \frac{(n-1)(n)(n+1)}{6}$, and the sum you seek is twice that.
You can read more here: https://en.wikipedia.org/wiki/Tetrahedral_number
Comment: The suggestion from @Deif is good, it's the same as working about the diagonal in the matrix approach above. Also, mildly interesting is that the sum has the form of a volume of a rectangular pyramid. So there must also be a point of view of growing the answer in that manner.


LEFT JOIN delaying query by 5 seconds

Question: SELECT DISTINCT(journey.id), line.name, journey.departure
FROM journey
INNER JOIN journey_day ON journey_day.journey = journey.id
INNER JOIN service ON service.id = journey.service
INNER JOIN operator ON operator.id = service.operator
INNER JOIN line ON line.service = service.id
INNER JOIN pattern ON pattern.id = journey.pattern
INNER JOIN pattern_link pl ON pl.section = pattern.section AND pl.from_stop = "370023292"
INNER JOIN pattern_link pl2 ON pl2.section = pattern.section AND pl2.from_sequence < pl.from_sequence
WHERE journey_day.day = 1 AND CURDATE() BETWEEN service.date_start and service.date_end AND operator.id = "TMTL"
ORDER BY journey.departure

Above is a MySQL query that takes approximately 0.05 seconds to run.
As soon as I append this LEFT JOIN journey_code ON journey_code.journey = journey.id it adds another 4-6 seconds to the query. I feel this is something to do with a second reference to the journey.id column in the ON clause. Why is this LEFT JOIN delaying the query results so much?
Information  about journey_code table:
id(INT 11 PK AI) | journey(VARCHAR 128) | code(VARCHAR 16)

Both the journey and code have indexes. I've tried a composite index on the two and this didn't speed up the query in any way.
The result of an EXPLAIN prepended to the query: https://i.stack.imgur.com/tKrTn.png
Any ideas why this is happening?
Comment: Please add the output of EXPLAIN  to your question.
Comment: @VMai Sure, I will add this now. Please bear with me 1 moment.
Comment: @VMai I have updated the question with an `EXPLAIN`
Comment: You are seriously joining 8 tables?
Comment: @TJ What is the alternative? Have you not joined multiple tables before? The fact it takes 0.05 seconds to join 7 tables and 6 seconds to join 8 tables doesn't tell you something might be up with the join on the last table?
Comment: What is the type of `journey.id`? It is not `VARCHAR 128`, is it?
Comment: No, it is INT 11 primary key, auto inc
Comment: Can you try to reproduce it using something like http://sqlfiddle.com/ ?
Comment: @jskidd3 so why isn't `journey_code.journey` not an `INT 11` as well?
Comment: @Keeper I could do but I've just had to annonyingly run out of the office so I'm on my phone, will do as soon as I'm back
Answer: Try making the above query a subquery:
SELECT j.*, jc.<whatever>
FROM (SELECT DISTINCT journey.id, line.name, journey.departure
      FROM journey
      INNER JOIN journey_day ON journey_day.journey = journey.id
      INNER JOIN service ON service.id = journey.service
      INNER JOIN operator ON operator.id = service.operator
      INNER JOIN line ON line.service = service.id
      INNER JOIN pattern ON pattern.id = journey.pattern
      INNER JOIN pattern_link pl ON pl.section = pattern.section AND pl.from_stop = "370023292"
      INNER JOIN pattern_link pl2 ON pl2.section = pattern.section AND pl2.from_sequence < pl.from_sequence
      WHERE journey_day.day = 1 AND
            CURDATE() BETWEEN service.date_start and service.date_end AND
            operator.id = 'TMTL'
    ) j left join
    journey_code jc
    ON jc.journey = j.id
ORDER BY j.departure

The way MySQL works, it should run the subquery and materialize it.  If you have an index on journey_code(journey), the join should be fast.
Comment: Thanks Gordon, I will try this in a moment and let you know if it's an improvement
Comment: Absolutely fantastic! Thank you so much this works a dream! The 12 hour investigation is drawn to a close 8-)

LEFT JOIN delaying query by 5 seconds


Image of a circunference by a complex-valued map

Question:
Let $f(z)=az+b\overline{z}$, where $|a|>|b|$. Proof that $f(S^1)$ (the unit circunference) is an ellipse cantered at the origin, with the following characteristics:
i) The measure of the major semi-axis is $|a|+|b|$ and the minor's is $|a|-|b|$.
ii) If $b\neq 0$, $a=|a|(\cos \alpha+i\sin\alpha)$ and $b=|b|(\cos \beta+i\sin\beta)$m then the angle betwenn the semi-major axis and the real axis is$\frac{\alpha+\beta}{2}$.

I am really struglling to solve this question. I tried to write $z=x+iy$ and apply the definition of $f$, but I did a bunch of calculations and got nowhere. I don't see where I could apply the fact that $x^2+y^2=1$, because the expression of $f(x+iy)$ has only first degree terms.
Any help would be welcome.
Answer: first, notice that in point ii $a$ and $b$ are complex numbers too, so you'll need to remember that later. the way you apply $x^2+y^2=1$ is by finding the inverse function, then you apply the equation to that. You should get
$\left(\frac{x_1}{a+b}\right)^2+\left(\frac{y_1}{a-b}\right)^2=1$
(where $f(z)=x_1+iy_1$), which would be the equation of an ellipse with its major and minor axes aligned with the $x$ and $y$ axes, if $a$ and $b$ were real. Try to work from there, I hope this was helpful!


Using Ansatz to find a solution for the differential equation

Question: I have Newton's second law equation: $F=ma$ where I consider mass $m$ as a constant. The net force $F$ is a sum of two forces $F_a$ and $F_b$ acting on it. $F_a$ is constant and $F_b$ varies according to $u(t)$.
So, the entire equation is, $F_a - F_b(u) = m \dfrac{du}{dt}$, which resembles the form $u' = a - bu$ where $a=F_a$ and $b=F_b$.  How can make use of an educational guess (Ansatz form) and proceed for the above differential equation to solve for $u(t)$?
Comment: Expression for $F_b$ is needed to give an educated guess.
Answer: The equation is separable.
$$m\frac{du}{F_a-F_b(u)}=dt,$$
then
$$m\int_{u_0}^u\frac{du}{F_a-F_b(u)}=t.$$
After integration, you will need to invert the antiderivative.


imagecache permissions

Question: How to allow authenticated users to see all versions of images but prevent anonymous users to see 'large' images created with an imagecache preset?
I've ticked the correct boxes under the permissions tab of imagecache so that anonymous users aren't able to see these images but still they show up.
What am I doing wrong? (I've flushed the cache of the imagecache)
Cheers.
Comment: can you define "show up" and perhaps some more information/specifics?
Comment: With 'show up' I mean that when the anonymous user clicks on the thumbnail Lightbox2 still shows the large image. Could it be that it's the lightbox2 permissions then or is it related to Imagecache? I'm not sure.
Comment: I just checked and there are no permissions settings which prevent the viewing of certain Imagecache presets on Lightbox2. There are permissions in the Imagecache permissions section and none of them are selected for anonymous users. So I don't understand why they are able to see the 'original' size and all other sizes created by Imagecache. (pondering)
Answer: A quick look through the imagecache module suggests that the only time the module itself enforces the "view imagecache [preset]" permission is when it is serving private files.  This makes sense in that once the image derivative is created in the public files structure, it is never called; once a file "really exists" drupal is never bootstrapped up, it is only booted up to create the derivative the first time it's not found.
So, then, what are these permissions useful for?  Well I'd imagine so you could do something like this...
<code>$presets=array('small', 'medium', 'large');

foreach($presets as $preset) {
  if (user_access('view imagecache ' . $preset)) {
    // do whatever your module wants with that preset, create a link, show the image, whatever
  }
}
</code>
...in your own module.
As for lightbox2, a quick look there shows it just presents a list of possible Display Field options using all of the imagecache presets.  As to why it doesn't check these permissions when building these links is a question for that module's maintainer on its issue queue on drupal.org.
Comment: Thanks Jimajamma! Much appreciated! However, I have no understanding really on how to create a module. I could possibly create a 'very' simple module but how to string things together.. no idea. Can you either help me out with this one or point me to a great resource (if possible related to permissions) so I can learn how to create my first actual 'useful' module? That'll be awesome.
Comment: in the meantime I'll go ahead and read this: https://drupal.org/node/416986

imagecache permissions


Hitting the back button after a batch process cause a nasty error

Question: I have a batch process (using batch API) that runs when a user on my site tries to launch a non signed Java applet. The batch process does all the needed codesigning and other things and then redirects the user to the applet when it is finished. This all works well but if the user hits back from the applet page they get this nasty error with the text from my batch_error function.

It seems that this occurs because when you hit back you end up trying to run a batch process that no longer exists. Is there anyway to avoid this?
EDIT:
Here is my function that sets up the batch process:
function batch_codesign($node) {
$batch = array(
   'operations' => array(
        array('batch_codesign_process', array("create_jar_files", $node)),
        array('batch_codesign_process', array("output_new_agentsheets_applet_html", $node)),
    ),
    'finished' => 'batch_codesign_finished',
    'title' => t('Codesigning'),
    'init_message' => t('Codesigning ' . $node->title .'.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error has occured while condesigning the project, please try again.'),
    );
batch_set($batch);
$nid = $node->nid;
batch_process("path/to/endpoint");
}

Comment: Could you use an AJAX overlay instead of a new page to process the batch?  Then when the user hits back they wouldn't go back to the start of the batch, they'd go back to the page before the one in which they uploaded their applet...?
Comment: Can you not do the codesigning and other things beforehand or is the applet being uploaded right then?
Comment: Its a somewhat strange use case where we sometimes have 100s of people uploading projects (which contain applets) at the same time but only some small percentage of those projects will be played right away. If we do the codesining with every upload it can cause performance issues and sometimes interfere with uploads because the codesinging takes much longer then the upload. The codesigning is a long process because the applets come from a legacy applicaiton which does not generate the applet in the correct format. We need to jump though many hoops to get the correct manfiest and such.
Comment: can you not disable their back button on that page via inserting inline js? I know disabling the back button is bad web-fu, but can be ok in some extreme cases, especially if you include a note.
Comment: This is a very worthwhile question, as this even occurs for admins doing updates and such if they accidentally use the back button.
Comment: @DrCord Oh I didn't know that was possible and I'm sure that wouldn't work on all browser, but I think I would prefer to find a solution that didn't involve hacking the back button ;)
Comment: @Darvanen that sounds like a great idea but I wonder how this could be done? Doesn't batch_process automatically run in a new window? Is there someway to configure this?
Comment: What about onpopstate javascript method?  It basically allows you to add your own customization during a back/forward process.  not sure if this would break the default functionality.  https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
Comment: @Mike2012 I'm afraid the 'how' of that idea is beyond me at the moment.
Comment: Still no answers and the bounty is running out :(
Answer: Here's a possible solution, however you'll need to alter the menu callback for batch and wrap the default page callback.
Create your hook_menu_alter() and change batch to be your own page callback function, and update the file attribute (unset if in your .module)
// Default page for batch operations.
$items['batch'] = array(
  'page callback' => 'system_batch_page',
  'file' => 'system.admin.inc',
);

Basically your callback can call the default system_batch_page() page callback (wrap it). From there you can adjust what happens when someone hits an inactive or stale batch.


linear model, given y, calculate the confidence interval for x

Question: I fit the model y = a + b * x. And 95% CI for estimates of a and b are (a1, a2), (b1, b2), respectively.
If we have a new observation x0, then the estimated response is a_hat + b_hat * x0. And the 95% CI is (a1 + b1 * x0, a2 + b2 * x0)
Case 1, now given y = 0, I want to estimate the responding x.
I guess the confidence interval for x is (a1 / b2, a2 / b1). Am I right?
Case 2, if we fit a model y = a + b * x + c * z + d * x * z , a_hat<0, b_hat,c_hat,d_hat>0,
Given y = 0, how to calculate the confidence interval for x + z?
Comment: For these questions to be answerable you need to supply more information, including (at a minimum) the *probabilistic* terms in each model and the method by which the parameters are being estimated.
Comment: For OLS regression, it is not the case that the 95% CI for $\hat y$ is $(a_l + b_lx_0,\ a_u + b_ux_0)$.
Comment: @whuber: in this context, calibration is inverse prediction. See p145 of Seber&Lee Linear Regression Analysis (2ed)
Comment: Yea. We still need error term. I think this problem is looking for a calibration interval.
Comment: What is a "calibration interval" in this context?
Comment: The 95% confidence interval for the estimated X will be given by the points where the `y=Y`horizontal line intersects the lower and upper confidence bands of the regression line
Answer: You seem to be asking about inverse prediction, also known as calibration. In short, if you have a linear regression model
$$
  Y=\beta_0+\beta_1 x +\epsilon
$$
and you estimate it based on some selected values $x_1, x_2, \dotsc, x_n$. Then, you want to use the estimated model (and estimated parameters $\hat{\beta_0},\hat{\beta_1}$ to find the value of $x$ that will give some choosen value of $Y$, say $y_0$, and a confidence interval for that $x$.
This is discussed in Seber and Lee, page 145, for instance, with many references. There is a dedicated R package on CRAN ,investr. And it has been discussed on this site Error bars, linear regression and "standard deviation" for point
(I will try to come back to post a fuller account)


include sitemap to one xml file

Question: I have some files that create sitemap (such as sitemap-product.php, sitemap-company.php and etc). They are very big file!
I want create an XML file that include these address (sitemap-product.php, sitemap-company.php) then when I include this XML file to Google webmaster, Google check one by one these file.
Can I do that?
Thanks for your help!
Answer: The XML version of the sitemap format looks like that shown below. I would recommend that you generate them using a sitemap generation tool rather than trying to hand code them. Search for sitemap generation tools on Google. I used http://www.xml-sitemaps.com/ to create the below snippet.
<code><?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
      http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
  <loc>http://www.TEST.co.uk/</loc>
  <priority>1.00</priority>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.TEST.co.uk/TEST.htm</loc>
  <priority>0.80</priority>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.TEST.co.uk/TEST.htm</loc>
  <priority>0.80</priority>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.TEST.co.uk/TEST.htm</loc>
  <priority>0.80</priority>
  <changefreq>weekly</changefreq>
</url>
</urlset>
</code>
You should call your XML sitemap 'sitemap.xml' and put it at the root of your web server.
If you add a reference to your sitemap to your robots.txt file then it should be found by the search engines automatically.

include sitemap to one xml file


Open Source alternative for Confluent Kafka Connect MQTT Source and Sink connectors

Question: I want to connect by MQTT broker to Apache Kafka (non enterprise version and no confluent kafka managed service used).
I was using Confluent's Kafka Connect MQTT source and sink but I realized it comes with a trial period of 30 days after which it requires a license.
Are there any other open source / free options to use as a bidirectional bridge between Apache Kafka and mqtt broker.
Comment: This is another open source option for mqtt source and sink connector
https://github.com/johanvandevenne/kafka-connect-mqtt
Answer: You can use Lenses' MQTT Source Connector:

A Connector to read events from MQTT and push them to Kafka. The
  connector subscribes to the specified topics and and streams the
  records to Kafka.

Lenses also offer MQTT Sink Connector for streaming records from Kafka to a target system.

Both connectors require the following:

Apache Kafka 0.11.x of above
Kafka Connect 2.x or above
Mqtt server
Java 1.8
Comment: I could not find the licence info on said page. Which licence is the MQTT connector under, and is it free beer?
Comment: The question was "are there any other open source /free options..."  so he's not looking to replace one commercial license for another.  Lenses is a commercial offering that requires a license.
Comment: @RickO'Shea Lenses has also open source offerings.
Answer: I don't have any detailed code examples available, just my 2 cents:
You have to build your own bridge, i.e. MQTT <-> Kafka (pub/sub <-> producer/consumer).

On the MQTT side IMHO the Eclipse PAHO client looks is pretty nice. Have a look at this howto: https://www.baeldung.com/java-mqtt-client.
On the Kafka a rather simple implementation with a producer and a consumer should be pretty easy. Things get complicated if you want to take the MQTT QoS into account (i.e. At most once (0), At least once (1), Exactly once (2)). At least once you can manage by having the offset commit under control and keeping an eye on the processing state of MQTT<->Kafka messages, for exactly once have a look at Kafka Transactions.


Problema com opencv no linux

Question: Estou fazendo um sistema de monitoramento com Opencv Python via streaming no meu SO Windos 10 roda tudo corretamente por ironia no meu Linux Mate recebo a seguinte mensagem de erro quando tento rodar

Nonmatching transport in server reply

segue meu código:
import cv2

cap = cv2.VideoCapture("rtsp://192.168.25.179:554/onvif1")

while(cap.isOpened()):
    ret, frame = cap.read()
    #print(frame)
    cv2.imshow('frame', frame)
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

Comment: E o seu Linux tem acesso a rede do rtsp? (acesso ao IP e porta que apontou)
Comment: Tem outro processo acessando o rtsp no momento no linux?
Answer: aconteceu comigo . isso tem a ver com variáveis do sistema.
você pode iniciar assim:
import os
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"

cap = cv2.VideoCapture("rtsp://192.168.25.179:554/onvif1", cv2.CAP_FFMPEG)

Aconselho a você instalar o pacote completo do v4l2 no linux geralmente tbm resolve.

Problema com opencv no linux


The two meanings of "convex hull"

Question: Given a finite set of points $P$, we can think of two meanings for the term "convex hull of $P$:"

The set of convex combinations of points from $P$, $\sum \alpha_i p_i$ s.t. $\sum \alpha_i = 1 \wedge \forall \alpha_i \geq 0$.
The points $P' \subseteq P$ which are "active" in the convex hull; that is, the removal of which changes the set of points from (1).

Question: Is there a standard way to refer specifically to (1) or (2)?
Comment: I have never heard of convex hull as in 2, only as in 1. The points in 2 I would call the extreme points of the convex hull of $P$.
Comment: This confusion in terminology is also a peeve of mine.  The word "hull" means an exterior, and there's a perfectly good phrase "convex closure" for (1).  Nonetheless the use of convex hull to mean (1) predominates except when discussion turns to algorithms for finding the extreme points (2) as a "representation" of the convex hull.
Comment: Intrigueing. With interpretation (2) you seem to require the convex hull to be a *hull* in some everyday sense, but you don't require it to be *convex* any more :)
Comment: Indeed, I come from CS, where (2) dominates "convex hull". Funny it's unheard-of in Math :) @hardmath turn your comment into an answer to be accepted. "convex closure" is what I was looking for, which appears to be a known synonym for CH.
Comment: Same here - research background in computer graphics and computational geometry, only ever heard of it in terms of (2)
Answer: I prefer "convex closure" for the collection of all convex combinations (1).  The phrase convex hull is slightly more concise, but the etymology of "hull" carries a meaning of the outer covering (as in the hull of a boat or husk of a seed), so it seems a pity to me not to reserve this for what mathematicians instead like to call the "extremal boundary points".  It's an important enough algorithmic (computational geometry) topic to deserve a shorter name.
Comment: If there is a topology involved, too, mathematicians may speak of the "convex hull" and the "closed convex hull".  Of course they use these terms even if $P$ is infinite. If they saw "convex closure" they may not know which is would mean.

The two meanings of "convex hull"


Positivity constraints in optimization

Question: How do you enforce positivity constraints in non-linear optimization (e.g. a constraint $x > 0$)? I remember there being a good reason for why most models use non-negativity constraints.
Comment: How about the KKT conditions? http://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions
Comment: @matt:They handle non-negative and equality constraints.
Comment: :You could use "Log Barrier methods". I will post an answer with more detail.
Answer: Consider the following:
 $$\begin{array}{rll}
 \min_x& f(x)&\\
 \text{subject to}& g_i(x)\leq0 &\text{for each }i\\
 & h_i(x)=0 &\text{for each }j \\
 \end{array}$$
For $\alpha>0$ we define the log barrier penalty function, $P_\alpha$, to be:
$$ P_\alpha(x)=f(x)-\frac1\alpha\sum_i\log(-g_i(x))+\alpha\sum_jh_j(x)^2 $$
where $x$ must be strictly feasible, i.e. $g_i(x)<0$ for each $i$, in order for the log term to be defined.
We seek to minimise $P_\alpha(x)$. The idea is that the boundary of the feasible region (i.e $g_i(x)=0$) acts a a barrier for $x$ close to $0$.
Comment: Should that be $\log(-g_i(x))$? I think you have an extra left parenthesis.

Positivity constraints in optimization


C# Regex quick help

Question: I'm trying to read a text file, and then break it up by each line thats is split by a "\n".  Then Regex it  and write out the regex.
string contents = File.ReadAllText(filename);
        string[] firefox = filename.Split("\r\n");
        string prefix = prefix = Regex.Match(firefox, @"(\d)").Groups[0].Value;
        File.AppendAllText(workingdirform2 + "configuration.txt", prefix);

string[] firefox = filename.Split("\r\n"); doesnt exactly work.
What I want to do is run a regex foreach line of contents and then write out each line after the regex
So...
filename:
Hero123
Hero243
Hero5959
writes out to:
13
243
5959
Well everybody is suggesting something off the base in which i started.  the ending result will be about a 20 line regex with Ints.  I've got to parse it out line by line.
Answer: File.ReadAllLines
var lines = File.ReadAllLines(originalPath);
File.WriteAllLines(newPath, lines
    .Select(l => Regex.Match(l, @"\d+").Value).ToArray());

Comment: i'm getting all types of cannot converts, can you give me an example.
Comment: There's a fine line between fishing and just standing on the shore like an idiot. --Steven Wright
Answer: There are a number of problems with your code:
The reason the splitting doesn't work, is because you're splitting filename, not contents, which contains the actual file data. I agree with the other poster on using File.ReadAllLines :) It's a little more flexible with the file format compared to using \r\n, amongst other things.
Also, you have string prefix = prefix = ..., the second equals sign is probably intended to be a +. You should using StringBuilder if the data files can become large, or better yet, write to an output stream as you go.
Passing an array to Regex.Match doesn't work either. To apply the regex to all lines, you should do something like:
foreach (string line in firefox)
{
    prefix = prefix + Regex.Match(line, // etc
    // Or rather:
    // stringBuilder.AppendLine(...)
}

Either that, or do it all at once with a multiline regex :)

C# Regex quick help


ServiceProxy for current Service

Question: I am trying to figure out how to generate a ServiceProxy that points to the service that I'm currently executing within. I have a need to convey information about it, so that another service can call back into this specific instance: since it's stateful.
ServiceProxy seems to do resolution by partition keys. However, I don't see how I can obtain a partition key for the currently executing service. I can obtain the partition Guid. But, ServiceProxy cannot be used with that.
Example use case: I have a StatefulService which invokes an external HTTP API. It posts a message to this API, which results in the API calling back into my infrastructure after some period. The HTTP endpoint that I have built needs to resolve the original StatefulService in order to route the response back to it.
Answer: You can get the key range for the partition and send the low key value to the external HTTP API. When that external API needs to resolve the partition for the call back, it can use the low key value as the partition key, which guarantees it will fall in the right partition range:
Int64RangePartitionInformation partitionInfo = this.ServicePartition.PartitionInfo as Int64RangePartitionInformation;
long lowKey = partitionInfo.LowKey;

ServiceProxy for current Service


Excel cannot access to ssas cube

Question: Hello everyone,
I encounter random problems concerning the access to the cube ssas via excel.
when I connect to the cube via SSMS, access via Excel is unlocked and becomes functional.
here is the error message when it is blocked:
Errors in the metadata manager. An error occurred while loading "DatabasePermission" Database permision, from file "\? \ D: \ MSAS13.CEGIBI \ OLAP \ Data \ Bi_AnalysisServices.111.db \ DatabasePermission.2.perm.xml"
is there a solution to this problem?
Thank you for your help.
Answer: I suppose you could try running the DBCC command. But ultimately I expect you will need to delete the Analysis Services database and redeploy from the source code. That error indicates some files in the deployed database are corrupt.
Comment: Interesting to note that DBCC can be run against SSAS as well. Always thought it is for SQL Server alone. Thanks for sharing

Excel cannot access to ssas cube


Como ler a propriedade 'Titulo' da Aba Detalhes de um arquivo FONT TRUE TYPE?

Question: Estou desenvolvendo um pequeno aplicativo que lê um .MDB, da qual existem nomes de fonte.
Então verifico se estas fontes estão instaladas , se não , instalo-as .Mas tenho que saber o nome de Titulo da Fonte que fica dentro da tela de propriedades/Datalhes para saber com exatidão a fonte a ser inserida. Uma vez que tenho nome do arquivo = "x.ttf" e nome na aba detalhes "x.ttf" , ai ok funciona bem , mas quando tenho "x.ttf" = nome do arquivo e "xx.ttf"
na propriedade ai dá tudo errado.
Comment: Será que é isso? http://www.delphipages.com/forum/showthread.php?t=171299 (veja a sugestão do Chris).
Answer: Vale responder para termos o histórico e caso no futuro alguém precise.
A forma mais simples é instalar, verificar e desinstalar, assim tendo acesso ao nome da fonte.
Segue rotina:
<code>Function NomedaFonte(Font: WideString):WideString;
type
  TGetFontResourceInfoW = function(Name: PWideChar; var BufSize: Cardinal;
    Buffer: pointer; InfoType: Cardinal): LongBool; stdcall;
var
  naf, k, y: integer;
  gfri: TGetFontResourceInfoW;
  lf: array of TLogFontW;
  lfsz: Cardinal;
  hfnt: HFONT;
  Nome: WideString;
begin
  gfri := GetProcAddress(GetModuleHandle('gdi32.dll'), 'GetFontResourceInfoW');
  if @gfri = nil then
    raise Exception.Create('GetFontResourceInfoW in gdi32.dll não funciona.');
  if LowerCase(ExtractFileExt(Font)) = '.pfm' then
    Font := Font + '|' + ChangeFileExt(Font, '.pfb');
  naf := AddFontResourceW(PWideChar(Font)); //carrega fonte
  try
    if naf > 0 then
    begin
      SetLength(lf, naf);
      lfsz := naf * SizeOf(TLogFontW);
      if not gfri(PWideChar(Font), lfsz, @lf[0], 2) then
        raise Exception.Create('GetFontResourceInfoW não pode ser chamado.');
      y := 0;
      naf := lfsz div SizeOf(TLogFont);
      for k := 0 to naf - 1 do
      begin
        hfnt := CreateFontIndirectW(lf[k]);
        try
          Nome := lf[k].lfFaceName; //Pega nome da fonte
          Result := Nome;
        finally
          DeleteObject(hfnt);
        end;
      end;
    end;
  finally
    RemoveFontResourceW(PWideChar(Font)); //Descarrega fonte
  end;
end;
</code>
Fonte(em alemão).


Formula for cross-classified (a.k.a., crossed random factors) mixed effects model with interaction between two "second level" variables

Question: I have a crossed-classified (Hox, 2010) mixed effects model—also known as crossed random factors (West, Welch, & Galecki, 2015), but I am struggling with how to write the formula for an interaction.
I have observations ($i$) nested within items ($j$) and respondents ($k$). items and respondents are not nested; they are both the units of analysis at "level two." I measured a characteristic of the item, called $Z_j$, and a characteristic of the person, called $X_k$. Thus, both of these are "level two" predictors, but are crossed—not measured at the same unit of analysis.
The primary hypothesis is: Does the relationship between $X_k$ and the outcome, $y_{i(jk)}$, depend on $Z_j$?
The R code seems harmless:
<code>y ~ x * z + (1 + x | j) + (1 + z | k)
</code>
But I hit a snag when writing down the formula.
The "level one" equation is simple enough, where we let the intercept vary by items $j$ and respondents $k$, which are crossed (hence in parentheses together, showing they are both at the same "level"):
$y_{i(jk)} = \beta_{0(jk)} + \epsilon_{i(jk)}$
And now the main effects come in when they predict the intercept:
$\beta_{0(jk)} = \gamma_{00} + \gamma_{01j}X_k + \gamma_{02k}Z_j + u_{0j} + v_{0k}$
This shows that the relationship between $X$ and $y$ varies by $j$; and it shows that the relationship between $Z$ and $y$ varies by $k$.
Now, my hypothesis is specified as the $y \sim X$ relationship depending on $Z$. I could write this as:
$\gamma_{01j} = \gamma_{010} + \gamma_{011}Z_j + u_{01j}$
When we substitute everything in, we get two main effects, an interaction, and random effects around intercepts at both $j$ and $k$ as well as random slopes for the main effects.
However, if I add this equation:
$\gamma_{02k} = \gamma_{020} + \gamma_{021}X_k + v_{01k}$
Then we get two identical interaction effects, both $\gamma_{011}$ and $\gamma_{021}$. But since interactions are multiplicative terms, then the way that I formulate my hypothesis shouldn't matter. This is where my confusion arises. Can I include both? It appears not, since they model the same thing. If not, are the two equivalent? Thus, my questions are:

Am I specifying this model correctly? (That is, before adding $\gamma_{02k}$)
If so, then does that mean: $\gamma_{01j} = \gamma_{010} + \gamma_{011}Z_j + u_{01j}$ and $\gamma_{02k} = \gamma_{020} + \gamma_{021}X_k + v_{01k}$ are equivalent?

References:
Hox, J. (2010). Multilevel Analysis, 2nd Edition.
West, B., Welch, K., & Galecki, A. (2015). Linear Mixed Models, 2nd Edition.
Comment: Your claim is: $$ (Y\mid \mathcal B =\mathbf b, \mathcal G = \mathbf g) \sim \mathcal{N}(\mathbf{C\beta} + \mathbf{Vb} + \mathbf{Tg}, \sigma) \\ \text{where } \mathbf C = [1, X, Z, X\times Z],\ \mathbf V = [1, X], \\ \quad\mathbf T = [1, Z],\ \mathcal B \sim \mathcal N_2(\mathbf{0, \Sigma_0}),\ \mathcal G \sim \mathcal N_2(\mathbf{0, \Sigma_1}) $$
Comment: @HeteroskedasticJim could you relate this to the vector notation I use above?
Comment: I don't think it'd be any different from the answer you already have below. That's why I left it as a comment.
Answer: You could write the model as follows:
$$\left \{
\begin{array}{l}
y_{ijk} = \beta_0 + \beta_1 X_{ijk} + \beta_2 Z_{ijk} + \beta_3 \{X_{ijk} \times Z_{ijk} \}+ \\ \quad\quad\quad\quad b_{0k} + b_{1k} X_{ijk} + u_{0j} + u_{1j} Z_{ijk} + \varepsilon_{ijk},\\\\
b_k = (b_{0k}, b_{1k}) \sim \mathcal N(0, D), \\
u_j = (u_{0j}, u_{1j}) \sim \mathcal N(0, V), \\
\varepsilon_{ijk} \sim \mathcal N(0, \sigma^2),
\end{array}
\right.$$
where $D$ and $V$ denote the variance-covariance matrices for the two sets of random effects, $b_k$ and $u_j$, respectively.
Comment: Shouldn't the lowercase $b_1$ and $u_1$ terms swap subscripts? How can the relationship between $X_k$ and $y$ vary by $k$? it seems like the relationship would vary by $j$.
Comment: @MarkWhite actually, you can permit the sex effect to be different across persons. See page 16 of this JStatSoft paper using lme4 for a variety of IRT http://www.jstatsoft.org/v39/i12/
Comment: @MarkWhite I assumed you were familiar with IRT since you were modeling item-response data using similar techniques to the one in the paper. I just think of it simply as allowing the effect of sex to be different by person. If you use indicator coding with male (1) female (0), not all females are zero and not all males are whatever the male coefficient is.
Comment: What about the interaction?
Comment: Yes, I'll update it.
Comment: Not necessarily, for example, it could be that you want to include different random effects per sex, and $X_k$ is a dummy variable denoting one of the sex groups. And likelikewise, you may wish to include different random effects for two groups of items, say A & B, and $Z_j$ is the dummy variable for one of the groups. In general, the subscripts should actually be $\{ijk\}$ to give you the freedom to use covariates that vary or not within items, respondents and measurements. I have adapted the notation in the model above for that.
Comment: Apologies if I'm being dense, but: Let's say $X_k$ does represent sex. Then $b_{1k}X_{i(jk)}$ would be telling us that the effect of sex... can differ by person. But a person is only coded with one type of sex?
Comment: @HeteroskedasticJim +1 Very interesting! This does not jibe with how I was conceptually taught mixed models: That specifying random slopes allows the slopes to vary within-person. Since gender is singular within-person, there's no variation for a slope. But it looks like this paper (section 6.2, just below equation 8) is specifying the random slope as a way to specify that heteroscedasticity depends on gender—I haven't seen this before/explained conceptually like this before. (But I also do not know IRT).


The area bounded by the tangential lines to an even-power exponential function

Question: The problem:
Consider a function, $f(x) = x^m$, where $m$ is an even, natural number. Then, consider two tangential lines, grazing the points $(-x,y)$ and $(x,y)$, respectively. My question is, what is the area bounded by those tangential lines and the curve, for any given $m,x$:

The area in-question has been colored yellow in the picture above. In this example, $m = 2$, $x = 1.5$ and $y = 9$.
My current research:
The function for a tangential line is denoted as $t(x)$. The $y$-value of the tangential point between $t(x)$ and $f(x) = x^2$ is denoted as $p_t$.
$$t(x) = -p_t + 2x\sqrt{p_t}$$
$p_t$ is met when $\displaystyle x = \sqrt{p_t}$:
$$-p_t + 2p_t = p_t$$
When I looked at this, I thought I could generalize it to any even $m$. That generalization looks like this:
$$t(x) = -p_t + 2x(\root m\of{p_t})^{m-1}$$
So, when $x = \root m\of{p_t}$, then $t(x) = p_t = x^m$. Problem is, when I tried this with $m = 4$ and $x = 3$, it created a secant line, not a tangent line. Not sure why. It did cross the curve at $(3, 81), 81 = p_t$, but it also crossed it much further below, somewhere in the interval $(7,7.2)$. So, that's where I'm at, trying to figure out a generalized formula for the function of any tangential line to an exponential function of the form $f(x) = x^{2n}$.
And that's simply my current sub-question, within the larger question of what is this area?
Comment: Let $t(x)=a+bx$, $f(x)=x^m$. Then at touching point $(x_t,y_t)$: $t(x_t)=a+bx_t=x_t^m=f(x_t)$, $t'(x_t)=b=mx_t^{m-1}=f'(x_t)$. You can express $a$ and $b$ in terms of $x_t$. Then you can find area as $2\int_0^{x_t} (f(x)-t(x))\, dx$.
Answer: $y = x^m ~$ where $m \in \mathbb{N}$ and $m$ is even.
The curve has symmetry about y-axis so we can find the bound area to the right of y-axis and multiply by $2$.
Slope of the curve is $~y' = mx^{m-1}$
Equation of tangent at point $P ~(p, p^m), ~p \gt 0~$:
$(y - p^m) = m p^{m-1} (x-p)$
$\implies y = mp^{m-1} x - (m-1)p^m$
Height of shell bound between tangent line and the curve is,
$h(x) = x^m - mp^{m-1} x + (m-1)p^m$
So the bound area between the curve and the tangents at points $(p, p^m)$ and $(-p, p^m)$ is given by,
$A = \displaystyle 2 \int_0^p h(x) ~dx = \frac{m (m-1) p^{m+1}}{m+1} $
Comment: While I have not dealt with this generic form $y = x^m$, the area bound between $y = x^2$ and tangents at a given $y$ is a pretty common question. This question is very similar except in this case, it is any even $m$ but given the nature of curves $y = x^m$ where $m$ is even, the solution is similar to $y = x^2$ and yes it turns out to be standard calculus work.
Comment: Thanks :) As I thought of this problem, I had the feeling that it was a pretty standard calculus problem. Is that the case? If not, is this the first time you've heard of this problem, or have you dealt with it before?


Evans PDE Chapter 5 Problem 11: Does $Du=0$ a.e. implie $u=c$ a.e.?

Question: Let $W^{1,p}(U)$ be the Sobolev space. Suppose that $U$ is connected bounded domain in $\mathbb{R}^n$ and $u \in W^{1,p}(U)$ satisfies $Du=0$ a.e. in $U$. How can I prove that $u$ is constant a.e. in $U$?
Answer: For a Dirac-family $(\varphi_\varepsilon)_\varepsilon$ with $\mathrm{supp}\, \varphi_\varepsilon \subseteq \overline{B_\varepsilon(0)}$ you have $D(u*\varphi_\varepsilon) = (Du)*\varphi_\varepsilon = 0$ on all open sets $O \subseteq U$ with $\mathrm{dist}(O,\partial U) > \delta$, with $\delta > \varepsilon$, so $u * \varphi_\varepsilon$ is constant on all connected ones. Also, $u*\varphi_\varepsilon \to u$ in $L^p$ for $p \geq 1$, in particular $u * \varphi_\varepsilon \to u$ almost everywhere for some subsequence. But this means $u$ is constant almost everywhere on all $O$ with $\mathrm{dist}(O,\partial U) > 0$, so it is constant almost everywhere on $U$.
Comment: Where do you use connectedness of $U$?
Comment: The $O$'s should be connected too, so $D(u*\varphi)=0$ there implies $u*\varphi$ constant.
Comment: It is intuitively quite true. Do you have a brief topological argument that why each $O$ is connected also?
Comment: I clarified my answer above. The first equality holds for all $O$, but the function is only constant on connected ones.
Comment: why $u\ast \varphi_{\varepsilon}\to u$ in $L^{\infty}$?
Comment: However, we can avoid the question by choosing $\varepsilon $ as a countable series tends to $0$.


Limits, finding $\alpha$ so my function is continuous

Question: Let $g(x)=\dfrac{f(x)-f(c)}{x-c}+\alpha(x-c)$ if $x\neq c$ and $g(x)=f'(c)$ if $x=c$.
Find $\alpha$ such that $g'(x)$ is continuous.
I started with the definition of $g'(x)=\lim\limits_{x\to c}\dfrac{g(x)-g(c)}{x-c}$, with some steps later I don't know how to proceed.
Comment: what are $g'(x)$ for $x\ne c$, $\lim_{x\to c} g'(x)$, and $g'(c)$?
Comment: It should be $$\alpha = - f''(c) /2$$
Answer: We're given
$$g(x)=\begin{cases}\cfrac{f(x)-f(c)}{x-c}+\alpha(x-c)\;,\,&x\neq c\\{}\\
f'(c)\;,\,&x=c\end{cases}$$
Begin by finding $\;g'(x)\;$:
$$\begin{align*}&x\neq c:\;\; g'(x)\stackrel{\text{diff. of fraction}}=\frac{(x-c)f'(x)-(f(x)-f(c))}{(x-c)^2}+\alpha\\{}\\
&x=c:\;\;g'(c)=f''(c)\end{align*}$$
Assuming $\;f',f''\;$ is continuous at  $\;x=c\;$  (it is not given but I don't think we can do without this), we have no problem with continuity $\;g'\;$ except perhaps at $\;x=c\;$ , so it must be that
$$f''(c)=g''(c)=\lim_{x\to c}g'(x)=\lim_{x\to c}\frac{(x-c)f'(x)-(f(x)-f(c))}{(x-c)^2}+\alpha\stackrel{\text{l'H 1st. summand}}=$$
$$=\lim_{x\to c}\frac{f'(x)+(x-c)f''(x)-f'(x)}{2(x-c)}+\alpha=\frac{f''(c)}2+\alpha$$
Thus, it must be that
$$f''(c)=\frac{f''(c)}2+\alpha\implies\alpha=\frac12f''(c)$$
A slightly different way: we in fact have that
$$x\neq c\implies g'(x)=\frac{f'(x)-f'(c)}{x-c}+\frac{f'(c)}{x-c}-\frac{f(x)-f(c)}{(x-c)^2}+\alpha$$
$$g'(c)=\lim_{x\to c}\frac{g(x)-g(c)}{x-c}=\lim_{x\to c}\frac{f(x)-f(c)+\alpha(x-c)^2-(x-c)f'(c)}{(x-c)^2}\stackrel{l'H}=$$
$$=\lim_{x\to c}\frac{f'(x)+2\alpha(x-c)-f'(c)}{2(x-c)}\stackrel{l'H}=\lim_{x\to c}\frac{f''(x)+2\alpha}{2}=\frac12f''(c)+\alpha$$


Linear combination of vectors in $\mathbb{R}^n$

Question: I'm supposed to say whether the following statement is true or false, with justification.

If w is a linear combination of u and v in $\mathbb{R}^n$, then u is a linear combination of v and w.

In my textbook it says this is false, but I don't see how to reason that out.
In my mind, $w = c(u) + d(v)$, where c and d are constants. So we should be able to flip that around and say $u=\frac{1}{c}[w-d(v)]$.
What is the correct way to justify this problem?
EDIT: Okay, now I see the issue. Division by zero.
Answer: Hint: The problem comes when $c=0$ and $u,v$ are linearly independent.


Finite abelian groups and subgroups.

Question: Let $G$ be a finite abelian group of order $n=p_1^{a_1}\cdot \cdot \cdot p_k^{a_k}$ and $H$ a subgroup of $G$ of order $m=p_1^{b_1}\cdot \cdot \cdot p_k^{b_k}$.
By Theorem 5 on page 161 of Dummit and Foote's Abstract Algebra, we can write $$G \cong A_1 \times \cdot \cdot \cdot \times A_k$$ where $|A_i|=p_i^{a_i}.$
Question: Is it possible to write $$H \cong B_1\times \cdot \cdot \cdot \times B_k$$ where $|B_i|=p_i^{b_i}$ and $B_i \leq A_i$ for each $i$?
Answer: Not always. Counter example:
$$G=\Bbb Z_2\times \Bbb Z_2\;,\;\;\;H=\langle\;(1,1)\;\rangle$$
Comment: I see your point now, @Gage. Thanks. Yet the OP said nothing so I pressume he meant the most general case.
Comment: How I am reading the OP's notation I don't think this is a counter example. $\vert G \vert = 2^2$ so we would just write $G \cong A_1$ where $\vert A_1 \vert = 4$ (and obviously $A_1$ is the Klein four group) and then $\vert H \vert = 2$ so $H \cong B_1$ with $\vert B_1 \vert = 2$ so $B_1 \leq A_1$.
Comment: Assuming that we are thinking of the primes in the list as being different for different indices
Comment: @Gage I really don't understand what you meant to convey. I gave an example of a group $\;G\;$ , which indeed is Klein's viergruppe, and a subgroup of it which is **not** the direct product of two subgroups of the factors. Of course $\;B_1\le A_1\;$ , with your notation (which I don't understand why you had to change), but your question was whether any subgroup of a direct product is a direct product of subgroups of the factors, and the above shows this is not always the case. I also don't understand why would we assume the primes in the list are different.
Comment: It isn't my question, I was just saying that how I read the OP's notation that these groups that they say you can break an abelian group up in don't have to be cyclic, just $p$-groups so for example if the group $G = \mathbb{Z}_{2} \times \mathbb{Z}_{2} \times \mathbb{Z}_{3} \times \mathbb{Z}_{3}$ how I read the question as breaking it up is into $A_1 \cong \mathbb{Z}_2 \times \mathbb{Z}_2$ and $A_2 \cong \mathbb{Z}_3 \times \mathbb{Z}_3$ whereas you see it as breaking it up into the 4 cyclic groups. Obviously this is something to clarify with the user asking the question.
Comment: Sorry if that wasn't clear before
Comment: My apologies for not being clear. Thank you both for your help. In fact, the $A_i$ are the Sylow $p_i$-subgroups of $G$ and the $B_i$ are the Sylow $p_i$-subgroups of $H$. So, yes, the primes are different.

Finite abelian groups and subgroups.


Recursion in Snowflake

Question: Long time listener, first time caller.
Im trying to learn recursion in Snowflake SQL with a classic Organizational Chart. The output Im trying for would be the total salary for each manager of employees, including both direct and indirect employees of that manager.
create table Employee(
    employeeid int primary key,
    managerid int,
    title string
);

INSERT INTO EMPLOYEE VALUES(1,NULL,'CEO');
INSERT INTO EMPLOYEE VALUES(2,1,'SVP 1');
INSERT INTO EMPLOYEE VALUES(3,1,'SVP 2');
INSERT INTO EMPLOYEE VALUES(4,2,'DIR 1');
INSERT INTO EMPLOYEE VALUES(5,2,'DIR 2');
INSERT INTO EMPLOYEE VALUES(6,2,'DIR 3');
INSERT INTO EMPLOYEE VALUES(7,3,'MGR 1');
INSERT INTO EMPLOYEE VALUES(8,3,'MGR 2');
INSERT INTO EMPLOYEE VALUES(9,3,'MGR 3');
INSERT INTO EMPLOYEE VALUES(10,9,'ASST');

create TABLE EMPLOYEE_SALARY(
    EMPLOYEE_ID INT PRIMARY KEY,
    SALARY INT
);

INSERT INTO EMPLOYEE_SALARY VALUES(1,100);
INSERT INTO EMPLOYEE_SALARY VALUES(2,90);
INSERT INTO EMPLOYEE_SALARY VALUES(3,90);
INSERT INTO EMPLOYEE_SALARY VALUES(4,80);
INSERT INTO EMPLOYEE_SALARY VALUES(5,80);
INSERT INTO EMPLOYEE_SALARY VALUES(6,80);
INSERT INTO EMPLOYEE_SALARY VALUES(7,70);
INSERT INTO EMPLOYEE_SALARY VALUES(8,70);
INSERT INTO EMPLOYEE_SALARY VALUES(9,90);
INSERT INTO EMPLOYEE_SALARY VALUES(10,60);

select
        managerid,
        sum(salary) as salary
from
        (
        select         emp.managerid,
                       emp.employeeid,
                       sal.salary
        from           employee emp
        inner join     employee_salary sal on emp.employeeid = sal.employee_id
        )
group by 1
start with     managerid is Null
connect by     managerid = prior employeeid

The error Im getting is "SQL compilation error: error line 3 at position 12 invalid identifier 'SALARY'".
Thanks in advance for any direction you can offer.
Answer: I would approach this with a recursive common table expression. Snowflake supports that standard syntax, and I find it easier to follow that the connect by clause:
with cte as (
    select managerid, employeeid from employee
    union all
    select c.managerid, e.employeeid
    from cte c
    inner join employee e on e.managerid = c.employeeid
)
select c.managerid, sum(s.salary) total_salaries
from cte c
inner join employee_salary s on s.employeeid = c.employeeid
group by c.managerid

Answer:
I'd recommend the CTE approach from GMB however if you want your SQL to work here's one approach :
select
    managerid,
    sum(salary) salary_summed
from
(
    select
        *
    from
        (
            select
                emp.managerid,
                emp.employeeid,
                sal.salary
            from
                employee emp
                inner join employee_salary sal on emp.employeeid = sal.employee_id
        ) start with managerid is Null connect by managerid = prior employeeid
)
group by managerid

Recursion in Snowflake


Why my ActiveMQ is shutting down my Tomcat?

Question: I have a dummy webapp in a Tomcat container that uses ActiveMQ.
The problem I'm having is that out of nowhere the ActiveMQ shuts down and forces my Tomcat to shutdown as well.
This is the log from catalina.log:
    INFO 2015-01-21 17:35:04,072 - ActiveMQ Message Broker (localhost, ID:app-46388-1421875096431-0:1) is shutting down - org.apache.activemq.broker.BrokerService.stop(BrokerService.java:560) - ActiveMQ ShutdownHook
    DEBUG 2015-01-21 17:35:04,072 - Caught exception, must be shutting down: java.lang.IllegalStateException: Shutdown in progress - org.apache.activemq.broker.BrokerService.removeShutdownHook(BrokerService.java:1950) - ActiveMQ ShutdownHook
    Jan 21, 2015 5:35:04 PM org.apache.coyote.http11.Http11Protocol pause
    INFO: Pausing Coyote HTTP/1.1 on http-127.0.0.1-8080
    Jan 21, 2015 5:35:04 PM org.apache.coyote.http11.Http11Protocol pause
    INFO: Pausing Coyote HTTP/1.1 on http-188.8.131.52-8080
    DEBUG 2015-01-21 17:35:04,075 - Shutting down VM connectors for broker: localhost - org.apache.activemq.transport.vm.VMTransportFactory.stopped(VMTransportFactory.java:227) - ActiveMQ ShutdownHook
    DEBUG 2015-01-21 17:35:04,076 - Stopping connection: vm://localhost#0 - org.apache.activemq.broker.TransportConnection.doStop(TransportConnection.java:964) - ActiveMQ Task
    DEBUG 2015-01-21 17:35:04,077 - Stopped transport: vm://localhost#0 - org.apache.activemq.broker.TransportConnection.doStop(TransportConnection.java:980) - ActiveMQ Task
    DEBUG 2015-01-21 17:35:04,077 - Cleaning up connection resources: vm://localhost#0 - org.apache.activemq.broker.TransportConnection.doStop(TransportConnection.java:1013) - ActiveMQ Task
    DEBUG 2015-01-21 17:35:04,077 - remove connection id: ID:app-46388-1421875096431-2:1 - org.apache.activemq.broker.TransportConnection.processRemoveConnection(TransportConnection.java:713) - ActiveMQ Task
    DEBUG 2015-01-21 17:35:04,077 - localhost removing consumer: ID:app-46388-1421875096431-2:1:1:1 for destination: queue://mydomain.mail.sender - org.apache.activemq.broker.region.AbstractRegion.removeConsumer(AbstractRegion.java:322) - ActiveMQ Task
    DEBUG 2015-01-21 17:35:04,077 - remove sub: QueueSubscription: consumer=ID:app-46388-1421875096431-2:1:1:1, destinations=1, dispatched=0, delivered=0, pending=0, lastDeliveredSeqId: 0, dequeues: 0, dispatched: 0, inflight: 0 - org.apache.activemq.broker.region.Queue.removeSubscription(Queue.java:430) - ActiveMQ Task
    DEBUG 2015-01-21 17:35:04,079 - localhost removing consumer: ID:app-46388-1421875096431-2:1:-1:1 for destination: topic://ActiveMQ.Advisory.TempQueue,topic://ActiveMQ.Advisory.TempTopic - org.apache.activemq.broker.region.AbstractRegion.removeConsumer(AbstractRegion.java:322) - ActiveMQ Task
    DEBUG 2015-01-21 17:35:04,079 - Connection Stopped: vm://localhost#0 - org.apache.activemq.broker.TransportConnection.doStop(TransportConnection.java:1023) - ActiveMQ Task
    INFO 2015-01-21 17:35:04,079 - Connector vm://localhost Stopped - org.apache.activemq.broker.TransportConnector.stop(TransportConnector.java:288) - ActiveMQ ShutdownHook
    INFO 2015-01-21 17:35:04,079 - ActiveMQ Message Broker (localhost, ID:app-46388-1421875096431-0:1) is shutting down - org.apache.activemq.broker.BrokerService.stop(BrokerService.java:560) - ActiveMQ ShutdownHook
    DEBUG 2015-01-21 17:35:04,079 - Caught exception, must be shutting down: java.lang.IllegalStateException: Shutdown in progress - org.apache.activemq.broker.BrokerService.removeShutdownHook(BrokerService.java:1950) - ActiveMQ ShutdownHook
    INFO 2015-01-21 17:35:04,081 - PListStore:activemq-data/localhost/tmp_storage stopped - org.apache.activemq.store.kahadb.plist.PListStore.doStop(PListStore.java:307) - ActiveMQ ShutdownHook
    INFO 2015-01-21 17:35:04,081 - Stopping async queue tasks - org.apache.activemq.store.kahadb.KahaDBStore.doStop(KahaDBStore.java:206) - ActiveMQ ShutdownHook
    INFO 2015-01-21 17:35:04,081 - Stopping async topic tasks - org.apache.activemq.store.kahadb.KahaDBStore.doStop(KahaDBStore.java:220) - ActiveMQ ShutdownHook
    INFO 2015-01-21 17:35:04,082 - Stopped KahaDB - org.apache.activemq.store.kahadb.KahaDBStore.doStop(KahaDBStore.java:246) - ActiveMQ ShutdownHook
    DEBUG 2015-01-21 17:35:04,082 - Checkpoint started. - org.apache.activemq.store.kahadb.MessageDatabase.checkpointUpdate(MessageDatabase.java:1131) - ActiveMQ ShutdownHook
    DEBUG 2015-01-21 17:35:04,090 - Checkpoint done. - org.apache.activemq.store.kahadb.MessageDatabase.checkpointUpdate(MessageDatabase.java:1244) - ActiveMQ ShutdownHook
    INFO 2015-01-21 17:35:04,480 - ActiveMQ JMS Message Broker (localhost, ID:app-46388-1421875096431-0:1) stopped - org.apache.activemq.broker.BrokerService.stop(BrokerService.java:628) - ActiveMQ ShutdownHook
    INFO 2015-01-21 17:35:04,481 - ActiveMQ JMS Message Broker (localhost, ID:app-46388-1421875096431-0:1) stopped - org.apache.activemq.broker.BrokerService.stop(BrokerService.java:628) - ActiveMQ ShutdownHook
    Jan 21, 2015 5:35:05 PM org.apache.catalina.core.StandardService stop
    INFO: Stopping service Catalina

DEBUG 2015-01-21 17:35:05,345 - Shutting down JMS listener container - org.springframework.jms.listener.AbstractJmsListeningContainer.shutdown(AbstractJmsListeningContainer.java:190) - Thread-20
 DEBUG 2015-01-21 17:35:05,345 - Closing JMS MessageConsumers - org.springframework.jms.listener.SimpleMessageListenerContainer.doShutdown(SimpleMessageListenerContainer.java:303) - Thread-20
 DEBUG 2015-01-21 17:35:05,350 - remove: ID:app-46388-1421875096431-2:1:1:1, lastDeliveredSequenceId:0 - org.apache.activemq.ActiveMQMessageConsumer.doClose(ActiveMQMessageConsumer.java:661) - Thread-20
 DEBUG 2015-01-21 17:35:05,351 - Closing JMS Sessions - org.springframework.jms.listener.SimpleMessageListenerContainer.doShutdown(SimpleMessageListenerContainer.java:308) - Thread-20
 DEBUG 2015-01-21 17:35:05,351 - Failed to send remove command: javax.jms.JMSException: Peer (vm://localhost#1) disposed. - org.apache.activemq.AdvisoryConsumer.dispose(AdvisoryConsumer.java:58) - Thread-20
javax.jms.JMSException: Peer (vm://localhost#1) disposed.
    at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:62)
    at org.apache.activemq.ActiveMQConnection.doAsyncSendPacket(ActiveMQConnection.java:1259)
    at org.apache.activemq.ActiveMQConnection.asyncSendPacket(ActiveMQConnection.java:1251)
    at org.apache.activemq.AdvisoryConsumer.dispose(AdvisoryConsumer.java:56)
    at org.apache.activemq.ActiveMQConnection.close(ActiveMQConnection.java:615)
    at org.springframework.jms.connection.ConnectionFactoryUtils.releaseConnection(ConnectionFactoryUtils.java:81)
    at org.springframework.jms.listener.AbstractJmsListeningContainer.shutdown(AbstractJmsListeningContainer.java:219)
    at org.springframework.jms.listener.AbstractJmsListeningContainer.destroy(AbstractJmsListeningContainer.java:149)
    at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:151)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:487)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:462)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:430)
    at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:853)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:831)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:794)
    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:361)
    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:70)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:3882)
    at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4523)
    at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:924)
    at org.apache.catalina.startup.HostConfig.undeployApps(HostConfig.java:1191)
    at org.apache.catalina.startup.HostConfig.stop(HostConfig.java:1162)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:313)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1086)
    at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1098)
    at org.apache.catalina.core.StandardEngine.stop(StandardEngine.java:448)
    at org.apache.catalina.core.StandardService.stop(StandardService.java:584)
    at org.apache.catalina.core.StandardServer.stop(StandardServer.java:744)
    at org.apache.catalina.startup.Catalina.stop(Catalina.java:628)
    at org.apache.catalina.startup.Catalina$CatalinaShutdownHook.run(Catalina.java:671)
Caused by: org.apache.activemq.transport.TransportDisposedIOException: Peer (vm://localhost#1) disposed.
    at org.apache.activemq.transport.vm.VMTransport.oneway(VMTransport.java:90)
    at org.apache.activemq.transport.MutexTransport.oneway(MutexTransport.java:40)
    at org.apache.activemq.transport.ResponseCorrelator.oneway(ResponseCorrelator.java:60)
    at org.apache.activemq.ActiveMQConnection.doAsyncSendPacket(ActiveMQConnection.java:1257)
    ... 29 more
 DEBUG 2015-01-21 17:35:05,352 - Could not close JMS Connection - org.springframework.jms.connection.ConnectionFactoryUtils.releaseConnection(ConnectionFactoryUtils.java:84) - Thread-20

This is my ActiveMQ configuration (applicationContext.xml):
<amq:redeliveryPolicy id="redeliveryPolicyTwoTimes" maximumRedeliveries="2" redeliveryDelay="2000"/>

<amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost:61616" messagePrioritySupported="true">
    <amq:redeliveryPolicy>
        <ref bean="redeliveryPolicyTwoTimes"/>
    </amq:redeliveryPolicy>
</amq:connectionFactory>

<amq:queue id="jmsDestinationMailSender" physicalName="mydomain.mail.sender"/>

Any help would be very appreciated.
Answer: ActiveMQ registers its own shutdown hook and stops automatically when the process is terminating. Thus it is already stopped before you've called stop() and the exception appears.
If you are stopping it manually via Spring then you should disable the shutdown hook by setting the property useShutdownHook="false"
 useShutdownHook="false"

for refrence , Please go through the link :-
http://activemq.apache.org/broker-uri.html
Sample code:-
<amq:broker useJmx="false" persistent="false" useShutdownHook="false">

...
</amq:broker>

Answer: See this example  from Apache Camel how to embed an ActiveMQ broker inside a WAR application: http://camel.apache.org/activemq-camel-tomcat.html
You do not need to use Camel so you can remove that part from the WAR, but the point is that you need to setup ActiveMQ broker correctly, such as we do in the broker.xml file, which you have not done.


Projection of oblique segment onto another

Question: How can I find the length of segment a, given the length of segment b, and given that the angle between a and b is x?
Alternatively, how can I find the length of segment a, given r and angle y?
OBS: segments r and b are perpendicular.
Answer: (a) You cannot find $a$ with only $b$ and $x$ given. There are infinitely many possible figures can be drawn.

(a) You cannot find $a$ with only $y$ and $r$ given. Again, there are infinitely many possible figures can be drawn.
Answer: It's impossible to express a in terms of x and b or y and r. You need 3 of them.
Comment: Those are what i used? There is also $a= r / \sin(90-x+y) * \sin(y)$
Comment: Thank you, that's what I was looking for.
Answer: For the second problem -- given $y$, $r$, $b$, and $r$ and $b$ perpendicular, find the length of segment $a$ -- there is no solution. In particular, there may be two different lengths $a$ that satisfy the question asked, as in the following diagram, where both $u$ and $v$ are possible solutions:


Combinando e rotacionando dois patches no matplotlib

Question: Estou tentando simular um teste feito com feijões no matplotlib, e para isso estou usando duas elipses combinadas, como na figura:

feijao = Ellipse(xy=(2,2), width=2.5, height = 2, angle = 120)
feijao2 = Ellipse(xy=(2,2.6), width=2.5, height = 2, angle = 75)

fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})

ax.add_artist(feijao)
feijao.set_facecolor('#a38d65')
ax.add_artist(feijao2)
feijao2.set_facecolor('#a38d65')

ax.set_xlim(0,10)
ax.set_ylim(0,10)

plt.show()

Porém eu preciso que o plot contenha mais de um feijão, e que eles variem levemente de angulação. Eu tentei utilizar a própria construção das elipses para isso, mas como cada elipse vai rotacionar em torno do seu próprio eixo, não funciona com todos os feijões.

ang=np.random.rand(10)

eli = [Ellipse(xy=(2+(5*i), 2+(7*j)),
                   width=2.5, height=2,
                   angle = ang[i]*360)
       for i in range(10) for j in range (5)]
eli2 = [Ellipse(xy=(2+(5*i), 2.6+(7*j)),
                   width=2.5, height=2,
                   angle = ang[i]*360-45)
       for i in range(10) for j in range(5)]

fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})

for e in eli:
    ax.add_artist(e)
    e.set_facecolor('#a38d65')
for e in eli2:
    ax.add_artist(e)
    e.set_facecolor('#a38d65')

ax.set_xlim(0, 50)
ax.set_ylim(0, 35)

plt.show()

Procurei na documentação e não encontrei, mas teria alguma forma de "combinar" as duas elipses que formam o feijão, e depois replicar esta formação, rotacionando as figuras?
Comment: Um comentário um pouco tangencial, mas particularmente eu tentaria fazer isso em um programa de edição de figuras como o Inkscape, e não diretamente via Python/matplotlib. Você poderia inclusive exportar a segunda figura como um arquivo SVG, abri-la no Inkscape e ajustar da forma que ficar melhor. Falo isso porque já perdi muito tempo tentando ajustar coisas extremamente específicas nas figuras do matplotlib (eixos, cores, proporções, fontes, ...), apenas pra me dar conta de que é mais simples fazer os "toques finais" editando a figura diretamente com um programa mais adequado.
Answer: Pode fazer-se isso criando uma PatchCollection, copiando isso e aplicando rotacao e translacao a cada copia:
Por exemplo:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.collections import PatchCollection # acrescentei isto
import matplotlib as mpl
import copy # importar o copy para copiar PatchCollection()

ang=np.random.rand(10)

eli = [Ellipse(xy=(2+(5*i), 2+(7*j)),
                   width=2.5, height=2,
                   angle = ang[i]*360,
                   edgecolor="black")
       for i in range(10) for j in range (5)]
eli2 = [Ellipse(xy=(2+(5*i), 2.6+(7*j)),
                   width=2.5, height=2,
                   angle = ang[i]*360-45,
                    edgecolor="black")
       for i in range(10) for j in range(5)]

fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})

e1 = eli[0] #Isto e' apenas criar uma forma qualquer para exemplo
e2 = eli2[0]

p = PatchCollection([e1,e2]) # juntar duas elipses

pcopy = copy.copy(p) # criar uma copia

# aplicar uma transformacao com rotacao e translacao a copia
tr = mpl.transforms.Affine2D().rotate_deg(-45).translate(20,20) + ax.transData
pcopy.set_transform(tr)

ax.add_collection(p)
ax.add_collection(pcopy)

ax.set_xlim(0, 50)
ax.set_ylim(0, 35)

plt.show()

Comment: (falta de acentos por causa de teclado ingles)


Beanshell equivalent for .Net

Question: Is there anything like Beanshell, which exposes CLR classes instead of Java classes, and lets you write scripts in C# or VB.Net (or any .Net language for that matter)
Should come in handy to test one-liner code snippets
Answer: Powershell lets you do this.
See Accessing .NET components from Powershell
Comment: Powershell is indeed good option, though I wish it offered a syntax options of being C#-like and VB-like rather than it's current syntax. Beanshell at least has or can use Java-like syntax.

Beanshell equivalent for .Net