Differential Geometry, why orthogonal eigenvectors have minimum and maximum curvature? why not they happen in other vectors without orthogonal?

Question: Hello brothers and masters, I am undergrad student, learning introduction of Differential Geometry (DG).
I am very curious that in the DG, the principal curvature appear in the eigenvectors which is orthogonal to each other (because linear algebra), given that a point of the regular surface.
But I cannot hard to understand with my heart. Because it looks also possible that the principal curvature may happen in the tangent vectors which are not orthogonal to each other.
For example, the counterexample which I am suspecting:

This surface has maximum curvature at $\theta = 0$ and $\theta = \frac{\pi}{2}$, and has minimum curvature at $\theta = \frac{\pi}{4}$ and $\theta = \frac{3\pi}{4}$.
Is there a something wrong with this surface, or what can be a good explanation for this surface?
Please quench this curiosity! Thank you in advance.
the wolfram alpha code of the surface
Comment: Basically, it's because curvature involves quadratic approximations to the surface, which brings the principal axis theorem into play. If I have time, I'll expand that into a proper answer.
Comment: This is a fact in linear algebra. A symmetric matrix is always diagonlizable and if two eigenvalues are different, then their respective eigenvectors are orthogonal.
Answer: Through the power of Wolfram Alpha, one can check that
$$
 \cos(4\arctan(t)) = 3 - \frac{8t^2}{(t^2+1)^2},
$$
so that
$$
 \cos(4\arctan(v/u))+2 = 5 - \frac{8u^2v^2}{(u^2+v^2)^2},
$$
and hence that
$$
 (u^2+v^2)(\cos(4\arctan(v/u))+2) = 5(u^2+v)^2 - \frac{8u^2v^2}{u^2+v^2}.
$$
Thus, your surface is the graph of the function
$$
 f(u,v) = 5(u^2+v^2) - \frac{8u^2v^2}{u^2+v^2}.
$$
I claim that $f$ is not twice differentiable at $(0,0)$, which is what you need to have a well-defined shape operator at $(0,0)$, and hence well-defined principal curvatures at $(0,0)$; in fact, I claim that $f$ isn't even continuously differentiable at $(0,0)$.
Now, for $(u,v) \neq (0,0)$, one can compute
$$
 \partial_1f(u,v) = 10u - \frac{16uv^4}{(u^2+v^2)^2}, \quad \partial_2f(u,v) = 10v - \frac{16u^4v}{(u^2+v^2)^2}.
$$
Let $t \neq 0$, and consider the line $v = tu$. On that line (away from the origin), we find that
$$
 \partial_2f(u,tu) = 10tu - \frac{16t}{(1+t^2)^2},
$$
and hence that the limit of $\partial_2f(u,v)$ as $(u,v) \to (0,0)$ along the line $v = tu$ is
$$
 \lim_{u \to 0} \partial_2f(u,tu) = -\frac{16t}{(1+t^2)^2},
$$
which clearly gives different limits for different values of the slope $t$. Thus, the partial derivative $\partial_2 f$ is discontinuous at $(0,0)$, and hence $f$ can't possibly be twice differentiable at $(0,0)$.
Comment: Thank you for your answer!
Comment: But, you also think that the property of orthogonality is make sense in your heart?


How do you cast a class to its subclass in c++?

Question: I come from a Java background, where classes which extend (inherit from) other classes are often passed around as the super class. I was hoping to do something similar in C++, but I have never worked with C++ inheritance before. I currently have the following:
class Obstacle{
    double get_position(){return position;}
};

class Wall : public Obstacle {
    double get_normal(){return normal;}
};

Obstacles, in general, can be any shape, but Walls are rectangular and therefore have an easily designed normal, which would not be appropriate for most Obstacles to have. However, another class has an aggregated std::vector<Obstacle*> which contains all Obstacles. When iterating through these Obstacles and doing calculations, I need to do separate calculations for separate types of Obstacles (there's a get_type() function in the superclass as well). When I have a Wall, I'd like to be able to call get_normal(), but if I try static_cast<Wall>(current_obstacle)->get_normal() I get the compilation error: no matching function call to Wall(Obstacle*&). It also gives the same error if I use ((Wall)current_obstacle)->get_normal(). It seems as though I should make a Wall constructor which takes an Obstacle and creates a new Wall object, but these doesn't seem to make sense to me.
In Java, I can cast any class to its subclass using ((Wall)current_obstacle).get_normal(). Is this possible in C++ as well? Do I have to create a constructor? Thanks in advance. Sorry for my lack of understanding.
Comment: This one deals with all the ways you can use to cast an instance: http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used
Answer: static_cast<Wall>(current_obstacle)->get_normal()

Try
static_cast<Wall*>(current_obstacle)->get_normal()

Comment: Oh. Wow. That was simple.
Answer: First, if current_obstacle is of type Obstacle*, then you should be casting it to Wall*. Currently you're trying to convert a pointer into a new object, which doesn't work.
Second, consider using dynamic_cast instead of static_cast. This will check whether the object pointed to is really of type Wall, and if not, will return a null pointer. static_cast does not check, and undefined behaviour (read: Bad Things) will happen if your Obstacle* doesn't really point to a Wall but you cast it and call a Wall member function. (Casting in Java always performs this check for you, as you know.)
Comment: The `dynamic_cast` behavior described only works for polymorphic types (those that have virtual member functions)
Comment: True enough. `Obstacle` should have its destructor declared virtual, given the way it's being used (i.e. polymorphically)
Comment: Can you explain what a virtual destructor does? From my understanding, the `virtual` keyword is used to allow you to redefine a method in a subclass. Why would my destructor be virtual? I am not redefining it in my subclass.
Comment: @Teofrostus Every class has a destructor which cleans up its members, and if you don't provide one the compiler does.


Will change name of an injected service change the behavior of transaction?

Question: I am using Grails 1.3.7, and I have two service, and I call a method of BService in AService as following:
BService {
  static boolean transactional = true

  public void bDoThings() {
    //doThings
    b.save()
  }
}

AService {

  static boolean transactional = true

  BService bProxy

  public void aDoThings() {
    //doSomethings
    bProxy.bDoThings()
    //doSomeOtherThings
    throw new RuntimeException()
  }
}

I think after throwing RuntimeException, aDoThings will be roll back, and b will not be saved. But only aDotThings is roll back, b is still persisted.
But when I change
BService bProxy

to
BService bService

or to
def bService

Everything works fine.So I wonder why this happens, because I think bProxy is just a variable name, it shouldn't affect the behavior of transaction.
Can anyone explain why?
Answer: When you are adding the proxy, you are not instantiating it as a spring service. At that point its just a normal class. To use it as a spring service it has to be injected as an service which you achieve by following the convention. Hope that helps
Answer: It's because grails naming agreement. See Dependency Injection Basics section to understand behaviour in your question.
Comment: OK, I read it, I think I should read the official doc more.
thanks for this information.


Regex syntax with quotes

Question: I'm trying to run a regex string in my code that will pick up everything that is between <li class="f" and

string regex = @"\<li\sclass="f"(\s*?.*?)*?\
";

But the syntax is wrong because of the quotes. I tried replacing them with just '
but it didn't find anything.
The regex string is working by-the-way it's just these quotes that are not. I was trying to look after some replacement like space-->/s and didn't find anything.
Comment: I afraid this is not much related to RegEx, because it's simply a C# problem
Answer: To escape the quotes in a string, double them:
string regex = @"<li\sclass=""f""(.*?)
";

I've also "fixed" your regex a bit, but it's still not a good idea to be using a regex for parsing HTML.
Answer: use shield symbols
@""""; //"
"\""; //"
Answer: You haven't escaped your quotes, but shouldn't be using regular expressions to parse HTML anyway. Use something like the HtmlAgilityPack, and then code along these lines;
static void Main(string[] args)
{
    HtmlDocument doc = new HtmlDocument();
    doc.Load("file.htm");

    var results = doc.DocumentNode
        .SelectNodes("//li[contains(@class, 'f')]")
        .Select(x => x.InnerHtml);

    foreach (string result in results)
    {
        Console.WriteLine(result);
    }
}

Regex syntax with quotes


Is the definition of a nautical mile ultimately incorrect?

Question: From many sources the nautical mile is defined as exactly 1852 meters (with minor variances). Based on history it was calculated around one minute of latitude, which is one sixtieth of a degree of latitude.
Now if we calculate a nautical mile based the equitorial radius $ R_e $ of earth, 6378136.6 meters (was the most accurate value I could find)
$$
M = (R_e2\pi)/360/60
$$
which comes to 1855.32473
Is there something im missing ultimately from how the exact definition has become defined because 1852 Meters would in theory not sensibly match up (run short or run over) if an imaginary line was layed around the equator.
Reversing this calculation to calculate the equatorial radius based on the nautical mile being 1852 meters exact we end up with an equatorial radius of 6366707.0194937075
which is a somewhat large difference.
Granted as earth is such a large body and is not a uniform sphere (more of an Ellipsoid with a flatening factor of $ 1 / 298.257223563 $), the amount of error is unpredicatable, but one would hope there is a reasonably accurate value of 1 nautical mile calculated.
Am I over complicating this?
Comment: @SaucyO'Path The nautical mile is a minute of *latitude* not longitude, so it would be more helpful to know the length of a great circle through the poles rather than the equator.
Comment: I imagine part of the problem might rely - granted, I'm just spitballing - on estimates of the radius and such of the Earth whenever the term was invented. Granted, it's also possible that - like a number of definitions - that the definition has been refined since its introduction, but I wouldn't know. This was merely the first idea that came to mind; would you know of anything along those lines?
Comment: See here https://en.wikipedia.org/wiki/Equator#Exact_length
Comment: 3m is only a $0.1$ percent error. Surely the uncertainty in estimates of earth's equatorial radius and flattening factor is significant enough to accommodate for this?
Comment: that 0.1% error though can go up proportionally would it not if one measures a distance between two gps points (haversine method) using the nautical mile definition?
Comment: The meter was originally defined as one ten millionth of the distance from the equator to the north pole, wasn't it? The pole is at latitude $90$ degrees or $5400$ minutes. Dividing $10^7$ by $5400$ on my calculator, I get about $1851.85$. Now how much have they changed the meter since then?
Comment: According to [Wikipedia](https://en.wikipedia.org/wiki/Earth) the earth's meridional circumference is $40,007,860$ meters. Dividing by $2160$ I get $1852.21574$ meters for the length of one minute of latitude.
Answer: First, a bit of history. In the 16th century the spherical representation of the Earth was generally accepted and began to be used, for navigation and cartographic purposes, with a coordinate system made of latitudes and longitudes. These coordinates are angles (as opposed to linear units), are were reckoned using various instruments that could measure angles of objects in the sky. It was a convenient way for navigators back then to assess their location on the planet, and create better maps of the Earth.
In the 17th century, a British mathematician named Edmund Gunter proposed to use the nautical mile as a convenient unit of distance for navigation, and would correspond to 1/60th of a degree of latitude, or 1 arcminute, because it would be easily relatable to measured angles.
However, one thing that cartographers did not know back then, is that the Earth isn't perfectly spherical. In reality, it more closely resembles an oblate spheroid. As a result, the arcminute of latitude on the Earth's surface isn't equal everywhere. It is slightly longer near the poles, and smaller near the Equator. A navigator moving from 0° 00' to 0° 01'N will obtain a distance of 1,842.9 m, but from 45° 00' to 45° 01'N would obtain 1,852.2 m, and from 89° 59' to 90°N, 1,861.6 m. As a result of this and other possible measurement errors, different countries did not agree on the length of the nautical mile, and several different values were used.
Eventually, as cartographers began to better understand the shape of the Earth, the discrepancy was better explained. Now we know that an arcminute's length on the Earth depends on the location. That new model of the Earth caused the nautical mile to be variable, and since it is highly problematic to have a non-constant length unit, in the end, the nautical mile was agreed internationally to be equal to 1,852 meters, a rounded value in meters close to its length at 45° latitude, also close to 1/5400th of the meridian arc. It is still widely used nowadays, but we know that it only approximately relates to angles.
As a side note, the equatorial radius of the WGS84 ellipsoid, the reference used by GPS systems, is 6,378,137 meters. However, different countries and regions of the world use different ellipsoids that better approximate the local shape of the Earth, and different equatorial radii and flattenings are used. Obtaining a more "accurate" equatorial mean radius and total circumference would be much more involved, because one would need to consider the geoid shape, which deviates by as much as 100 meters from an idealized ellipsoid.
Answer: You are holding 18th century measurements to a 20 century standard.
These are supposed to be based on the circumference around a longitude and not around the equator.
In theory, 1 nautical mile corresponds to one arcminute of latitude.  There are $5,400$ arcminutes from the equator to the north pole.
Also, in theory it is $10,000,000$ meters from the equator to the north pole (along the Paris meridian).
Since they are based on the same definition it should be exactly $1 \text {M} = \frac {10,000}{5400} \text{m}$
As the earth is oblate, 1 arcminute of latitude is not the same at the poles as it is at the equator.  The nautical mile is based on the arcminute at the 45 degree parallel.
Aslo, since in the late 18th century, there was no way to precisely measure the length of the meridian that defined the meter, the French made their best guess based on the technology of the time and created a meter stick that would become the standard meter.  It was never exactly $10,000,000 $ meters from the equator to the north pole.
In the 20th century the mile was established as exactly 1852 meters.


erro SIGSEGV no uso de um ponteiro

Question: Estou com o seguinte problema:
Estou criando um ponteiro e alocando memória nele, passando sua referência para função, mas quando vou lê-lo na função acontece o erro relatado no título.
Função:
void FileLer(char *texto, char *file)
{
    //
    //  Retorno
    //
    int ret = 99;

    //
    //  Handle
    //
    UINT FileHandleLer = 0;

    //
    //  Tamanho do Buffer
    //
    UINT BufferLenLer = 0;

    //
    //  Pega o tamanho do arquivo
    //
    GEDI_FS_FileSizeGet(file, 1, &BufferLenLer);

    if(BufferLenLer > 0)
    {

        GEDI_LCD_DrawString(5,  FONT_HEIGHT*5, FONT_WIDTH*0.7, FONT_HEIGHT*0.7, "File Ok! %d", BufferLenLer);

        GEDI_CLOCK_Delay(1000);

    }
    else
    {

        GEDI_LCD_DrawString(5, FONT_HEIGHT*5, FONT_WIDTH*0.7, FONT_HEIGHT*0.7, "Erro! ");

        GEDI_CLOCK_Delay(1000);

        //
        //  Para a funcao
        //
        return;

    }

    //
    //  Abre um arquivo
    //
    ret = GEDI_FS_FileOpen(file, 3, GEDI_FS_STORAGE_PUBLIC, &FileHandleLer);

    ret = GEDI_FS_FileRead(FileHandleLer, &texto, &BufferLenLer);

    int b = strlen(texto);     <<<<<< -- Linha com o erro

    //
    //  Fecha o socket
    //
    ret = GEDI_FS_FileClose(FileHandleLer);

    //
    //  Zera Variaveis
    //
    ret                 =   0;
    FileHandleLer       =   0;
    BufferLenLer        =   0;
}

Chamada:
char *buffer            =   (char *)malloc(1024*(sizeof(char)));

//
//  Le o arquivo IP
//
FileLer(buffer, "configIP.txt");

Comment: Jovem da uma organizada nesse código ai, pra facilitar a leitura dele.
Comment: No `GEDI_LCD_DrawString(5, FONT_HEIGHT*5, FONT_WIDTH*0.7, FONT_HEIGHT*0.7, "Erro! %d");` - Esse `%d` não vai dar certo pois falta um parâmetro.
Comment: Qual é a finalidade do `int b = strlen(texto);` se a variável `b` não será usada para nada depois e o `strlen` não deveria produzir efeitos colaterais?
Comment: Qual a documentação de `GEDI_FS_FileRead()`?
Comment: Victor Stafusa, já reparei isso, mas ele não esta caindo no else, este não é o problema, mas obrigado
Comment: o estranho que quando faço a mesma função utilizando apenas variáveis locais ela funciona, mas quando tento a mesma passando por parâmetro acontece isso
Comment: Victor Stafusa, só para identificar o problema.
Comment: `&texto` e `texto` são coisas diferentes. O primeiro tem tipo `char **`, o segundo tem tipo `char *`. O primeiro aponta para uma variável local à função `FileLer()`, o segundo aponta para uma string externa.
Comment: Procurei no google por `GEDI_FS_FileSizeGet`, `GEDI_FS_FileOpen`, `GEDI_FS_FileRead`, `GEDI_FS_FileClose`, `GEDI_LCD_DrawString`, `GEDI_CLOCK_Delay` e `GEDI_FS_STORAGE_PUBLIC` - Muitas destas o google nunca ouviu falar. As que ele conhece apontam para uma pergunta que você fez aqui em julho e para sites que copiaram o conteúdo desta sua outra pergunta para republicar. Assim sendo, pergunto: **De onde vem estas funções? Quem foi que as fez? Onde estão publicadas?** Todos os lugares que elas aparecem na internet que eu achei apontam para você, então nos diga quem além de você mesmo as conhece.
Comment: Ah sim, e procurando por `GEDI FS` no google, não veio nenhum resultado relevante. Que bicho é esse?
Comment: pmg, exatamente isso, troquei o &texto por texto e funcionou, obrigado. Quando se trabalha com ponteiros recebidos por parâmetros e um pouco diferente
Comment: Victor Stafusa, Faz parte de uma API de um equipamento que eu uso, só esta presente no manual, eu acho, desculpe
Comment: @LucasFernandes Só por curiosidade, que equipamento é esse? Fico intrigado por existir uma API de algum equipamento que seja tão obscura assim.
Comment: @Victor Stafusa, é uma maquina de POS, sabe? Aquelas de leitura de cartões
Answer: void FileLer(char *texto, char *file)
{
    // ...
    ret = GEDI_FS_FileRead(FileHandleLer, &texto, &BufferLenLer);
    //                                    ^^^^^^
    // ...
}

&texto e texto são coisas diferentes. O primeiro tem tipo char **, o segundo tem tipo char *. O primeiro aponta para uma variável local à função FileLer(), o segundo aponta para uma string externa.

erro SIGSEGV no uso de um ponteiro


In App Purchase functionality is not present in your binary

Question: App store is rejecting my app for below reason but I am able to test with my test device and making purchase for app through sandbox environment . I have submitted this app to app store two time and I got rejection. I need someone to help me over this.
1 - How to test in app purchase through production IPA to know what they is getting wrong.
January 29, 2016 at 3:31 AM
From Apple
Abandoned Batch
We found that while you have submitted In App Purchase products for your app, the In App Purchase functionality is not present in your binary.
If you would like to utilize In App Purchase in your app, you will need to upload a new binary that incorporates the In App Purchase API to enable users to make a purchase.
Your help will be more than appreciation!
[This is my in-app purchases product1
[]2
[]3
Comment: What is your question? Check the tab Capabilities in Xcode and disable In-App Purchase if you are not using it
Comment: Can you put code used here?
Comment: Ok allright @lorenzoliveto app is capable for making in app purchase.
Comment: I am able to purchase item from app but nevertheless app store is rejecting with this same massage friend @AvijitNagare
Comment: Try asking them what is the problem with your implementation of in-app purchase. It seems that they can't find it in the app. I usually make a video showing the functionality to them.
Comment: That is good option @lorenzoliveto but I have written all the steps which can lead them to reach at app purchase functionality, so I want to know if I can see or check that IPA on my device! anything like that
Comment: I think that you can't test the IAP in the production environment. Check out these answers http://stackoverflow.com/questions/13498005/ios-in-app-purchase-test-a-real-purchase-without-submitting-to-apple http://stackoverflow.com/questions/32391041/in-app-purchase-testing-on-production-environment-without-spending-money
Comment: Thanks for you support @lorenzoliveto can you show me some cheklist which will help me to find a problem in it
Comment: Hey @lorenzoliveto I don't know but is it important in-app purchase status approved please reply.
Comment: Hello @AvijitNagare I really running out of time! would you love to help me
Comment: The only think I con point out to you is the official IAP documentation (https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction.html) and the tutorials on Ray Wenderlich's site that are always very helpful
Comment: Can't predict exact issue refer http://www.raywenderlich.com/105365/in-app-purchases-tutorial-getting-started
Answer: Here 2 possible reasons for why the rejected App:

First is might be you are submitting wrong binary. Make sure you are submitting latest binary with in App purchase integrated
Second is if you are submitting right build that might be apple testers not able to find in App purchase option while testing App. In that case you can provide more information to them about how they will get in App purchase option

In Second case try this:

Below apple rejection reason you can see an option where you can appeal to them.
Using that send apple information about where in the app they will get an in App purchase option. Also provide him information by this in App purchase what it will change in the App.

Hope it will work for you.
Comment: Hello @mack I have did that process and they have replied me for same -: In App Purchase functionality is not present in your binary.
Comment: No @mac I am new in it so I don't know what meta data is but under in-app purchases on iTunesConnect my in-app purchase product is in "In Review" state
Comment: I can see that [environment : sandbox] for buy my product and it is purchasing product. we have submitted this binary in which we are testing this test accounts. and I don't recognise why this issue is happening.
Comment: is it necessary to submit binary for review with selected in-app purchase product under "In-App Purchases" option of iTunesconnect.
Comment: now I am figuring it out; So could you tell me that,I need my in-app purchase product under this and this is to be added while submitting my app to app review am I right ?
Comment: first is my in-app purchase product and rest of this are testing and that I don't to be configured in my app.
Comment: Yes exactly that needs to be added
Answer: This is so ridiculous but it will helpful for anyone like me in future
so problem was In-App Purchase and Submitting Binary
Please if you are submitting app binary for in - app purchase first time don't submit your in - app purchase first.
submit your build or binary with In-App Purchase selected under you build screen as shown in screenshot
Comment: I can only see one screenshot. where are the second and third one?
Comment: Please clarify the fix. "Please if you are submitting app binary for in - app purchase first time don't submit your in - app purchase first."
Comment: OMG, I've submitted so many apps and IAPs and managed to forget this, this time. App Store Connect is a minefield of checkboxes and magic.


Understanding Incorrect Permissions for Instagram API

Question: I've written a python script to use the Instagram API to find all the media associated with a given user. This user is one of the users that I follow on Instagram.
When running this line of code...
api.user_recent_media(user_id=user, count=sys.maxint)

...I get the following error:
(400) APINotAllowedError-you cannot view this resource

Why am I getting this error if I'm querying a user that I follow? What am I doing wrong? Thanks!
Comment: Are you properly authorized to use the api for that user id?
Answer: I ended up using the wrong access token (from a different account).
Thanks!
Answer: You need to use an access_token generated for your account.
Basically the Instagram permissions for the Users endpoint works like this:

If the target user is public, you can query that user's info and media with a client_id without the need for any authentication.
If the target user is private, using the client_id will not work and you need to do authentication and use the access_token from an authenticated user that follows that target user.


Image of a category under a functor need not be a category?

Question: I've been trying to understand the following counterexample posted here: https://mathoverflow.net/questions/23478/examples-of-common-false-beliefs-in-mathematics?page=2&tab=votes#tab-top
"You only need two objects 0, 1 and a single non-identity arrow 0->1. Consider the functor from this to Set which takes 0 and 1 to the natural numbers and the arrow to the successor function. "
I don't get why the image of $0\to 1$ in $Set$, which is $0\to 1$ in $\mathbb N$ is not a category...what am I missing? All the axioms seem to check out.
Comment: That is not the image. The image is $\text{succ} : \mathbb{N} \to \mathbb{N}$. It isn't closed under composition.
Comment: Right, in the source category there are no non-trivial compositions. But the image is the single object $\mathbb{N}$ that both objects map to. Thus, there is a composition $succ \circ succ$
Comment: Why isn't it closed under composition? Since there are only two objects, there aren't any nontrivial compositions, right?
Comment: Ooh, I see, I thought it was mapping to two different copies of $\mathbb N$. Thanks!
Comment: And the counterexample here: https://math.stackexchange.com/questions/413138/can-it-happen-that-the-image-of-a-functor-is-not-a-category

is a counterexample because the arrow from $x\to z$, which is the composition of $x\to y$ and $y\to z$, is not in the image?
Comment: Yes, exactly, that's true. (The system didn't allow me to just write "Yes.".)
Answer: Assuming we're working with small categories $\mathcal{C,D}$, the problem with images not being categories requires, for a functor $F$, the map of sets $F: Ob(\mathcal{C}) \to  Ob(\mathcal{D})$ not being injective (though this isn't sufficient to insure a problem). The issue that arises is that there may be objects and morphisms $f:W \to X, g:Y \to Z$ in $\mathcal{C}$, where we have no meaningful idea of composition $f \circ g$, but such that $F(X) = F(Y)$ in $\mathcal{D}$ so that $F(f) \circ F(g)$ now makes sense. But we have no reason a priori to assume there's a map $h: X \to Z$ "lifting" the composition.
The easiest way to construct an example is to consider the finite category $\mathcal{I}$ with objects $0,1$ and a unique morphism $f: 0 \to 1$ (obviously there are also the identities). Suppose we have a functor $F: \mathcal{I} \to \mathcal{C}$, for some other category, and suppose $F(0) = F(1) = X \in Ob(\mathcal{C})$. In order for the image to be a category, $F(f) \circ F(f)$ has to be in the image, but the only morphisms in the image are $F(f)$ and the identity on $X$. So the image of $F$ is only a category if $F(f)$ is idempotent, or if it is its own inverse.
Answer: The source of the problem, as described by JHance,
can be realized as the smallest 'free' example of a functor $F\colon C\to D$
whose image is not a category.
Let $C$ be the category with four (distinct) objects $w$, $x$, $y$, $z$
and the two arrows $w\to x$ and $y\to z$ (besides the identities),
and let $D$ be the category with the objects $0$, $1$, $2$ and the (non-identity) arrows
$0\to 1\to 2$ and $0\to 3$.
(Both $C$ and $D$ are partially ordered sets regarded as categories.)
Let $F$ be the functor $C\to D$ with the object part
$w\mapsto 0$, $x\mapsto 1$, $y\mapsto 1$, $z\mapsto 2$,
which already determines the behavior of $F$ on morphisms,
namely $F(w\to x)=(0\to 1)$ and $F(y\to z)=(1\to 2)$.
The image of $F$ is not a category, because it contains the composable arrows
$0\to 1$ and $1\to 2$, but no arrow $0\to 2$.
Comment: I discovered that the example I gave above is identical to Exercise 2, on page 27, in Peter Freyd, "Abelian Categories: An Introduction to the Theory of Functors", Harper & Row, New York, 1964.


Allowed memory size exhausted + poor performance

Question: I have Requests table in my MySQL database (Yii project), which contains all visits to the main page of my website with
fields: `id`, `partner_id` (relation to `Partners` table), `date`

date with current timestamp.
and id with id of a visitor.
The problem is that there is about 1.5 millions rows in the Requests table and when I try to expose this data somewhere, it shows poor performance or even error from title.
For example, I've got the list of partners and column called "All requests" where I'm viewing all requests with partner_id equal to this partner's id. There could be something like 500 or 1000 requests for every partner, so, I believe, my SQL query is very heavy.
Could you please give some advices about how to make it more flexible?
I still need this data from Requests for commercial calculations, but I can't find out how to avoid this huge amount of data and poor performance.
Comment: So it's not using any keys at all, full table scan.... what indexes do you have on this table? Particularly on the `partner_id` column?
Comment: [Please no!](http://www.commitstrip.com/en/2014/06/03/the-problem-is-not-the-tool-itself/)
Comment: So what indexes do you have on this table, and what queries are you running against it.... and have you done an EXPLAIN for those queries to see how MySQL is executing them and what indexes it might be using?
Comment: selecting 500 results from a table that size does not seem like a particularly heavy task - as above please show your queries
Comment: I've got 20 User models displayed and for each of them - this query: SELECT COUNT(*) FROM $requests_table rt WHERE rt.partner_id = t.id
Comment: @Mark Baker I've just used: EXPLAIN SELECT COUNT(*) FROM 'requests' WHERE partner_id = 1. possible_keys and key are NULL
Comment: Yes, I guess that's it :D added index and 'rows' in EXPLAIN changed from 1680k to 1.4k. Thanks and sorry for newbie questions, I needed to realize it in some way :)
Comment: Remember the CommitStrip cartoon.... it's always useful having a humorous reminder like that for the future.... and the fact that there is a cartoon like that means that enough people make the mistake to know that you're not alone in doing so
Answer: Don't execute request 500 or 1000 on a same time. If you do so then it will gives you error or time out error.
Better to put some logic (kind of forloop or foreach) statement and send request in bunch of 10-20 (but not more than that). If you follow this then it will gives you result properly.
Secondly, I don't know about your front end, but suppose you use DotNet then put a call with "async" "await" keyword in your method which handle this kind of task easily.
If you need some more details on this then please revert.
Comment: Thanks for answer. It's PHP, Yii framework. I guess, my query runs 20 times, 1 for each partner of the list page (there is a list with pagination in frontend).


Hide mobile safari keyboard when form submitted in Ajax application

Question: I have a textfield which fires an event in a web app, but I'd like the keyboard to close when the user presses enter. Using jquery to disable usual submission.
Answer: Create blur event
To open:
<code>$('input#search').focus();
</code>
To close:
<code>$('input#search').blur();
</code>


Is $\Omega^p(M)$ always $H^*(G,-)$-acyclic?

Question: Suppose $M$ is a manifold on which the discrete group $G$ acts freely and properly discontinuously. Is it then true that $\Omega^p(M)$ is an acyclic $G$-module, in the sense that $H^k(G,\Omega^p(M)) = 0$ for $k>0$ ?
Clearly this holds if $G$ is finite, because then $|G|$ is invertible in $\Omega^p(M)$and it annihilates positive-degree cohomology. I would like to know if it's true for more general $G$. I'm ready to assume that $G$ is countable, so as to make it a discrete Lie group.
I'm also wondering about $C^p(X)$, the group of singular cochains of a space $X$ if the group $G$ acts freely on it : is this acyclic  ? If not, under what conditions is it ?
Answer: The answer for $C^p(X)$ is yes, and so it suggests that it is so for $\Omega^p(M)$, though I don't have a proof for that yet.
let $M$ be a $G$-module, we have $\hom_G(M,C^p(X)) = (\hom(M, C^p(X))^G = (\prod_{\hom(|\Delta^p|,X)}(M, \mathbb Z))^G= \hom(C_p(X), \hom(M,Z))^G= \hom_G(C_p(X), \hom(M,\mathbb Z))$.
Now given that $G$ acts freely on $X$, it acts freely on $\hom(|\Delta^p|,X)$ as well, so that $C_p(X)$ is a free $G$-module, and in particular $\hom_G(C_p(X),-)$ is exact.
It follows that $\mathrm{Ext}^i_{\mathbb ZG}(M, C^p(X)) \cong \hom_G(C_p(X), R^i\hom(-,\mathbb Z)(M))$ where $R^i$ denotes the $i$th right derived functor.
Now note that as $C_p(X)$ is a free nonzero (except of $X=\emptyset$, but let's not worry about that here) $G$-module, this $\hom_G$ is zero if and only if $R^i\hom(-,\mathbb Z)(M) = 0$.
But note that this group is completely independent of $X$, it only depends on $G,M$. For acyclicity, we're only interested in $M=\mathbb Z$ so I'll restrict to that situation.
Now to compute $R^i\hom(-,\mathbb Z)(\mathbb Z)$ we want a $G$-projective resolution of $\mathbb Z$. So take a contractible space $EG$ on which $G$ acts freely, so that $C_\bullet(EG)\overset{\epsilon}\to \mathbb Z$ (the augmented singular chain complex of $EG$) is a free resolution of $\mathbb Z$. Then apply $\hom(-,\mathbb Z)$ so we get $C^\bullet(EG)$, and then take its cohomology:  we get $H^*(EG)$. But $EG$ is contractible, so this is $0$ : $R^i\hom(-,\mathbb Z)(\mathbb Z) = 0, i>0$
In particular it follows that $\mathrm{Ext}^i_{\mathbb ZG}(\mathbb Z, C^p(X)) = 0, i>0$, or in other words, $C^p(X)$ is acyclic.


How to duplicate a node into an external database in Drupal 8

Question: What I am trying to do is to save a copy of a node object after it is inserted into another Drupal database.
As it can be seen in the following piece of code, my idea is to change the database after a node is inserted. Make a copy of the node and save it. Then, return to the default database.
However, seems like entity storage manager is set to default database in node save function. Therefore, the node is getting saved inside the default database again.
//... mymodule_node_insert

$node = Node::load($id);
\Drupal\Core\Database\Database::setActiveConnection('external');
$db = \Drupal\Core\Database\Database::getConnection();

// save the node in the shared database
// Create node object with attached file.
$sharedNode = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$sharedNode->save();

\Drupal\Core\Database\Database::setActiveConnection();

How can I make this work? Am I following a correct logic?
Any helps would be appreciated.
Thanks
Answer: This seems similar to Database::setActiveConnection not working as expected?. Perhaps the Node object you've instantiated before switching the connection is still going to hold on to the old db settings as the source to save.
The DatabaseSwitcher class (found in the above posted question, just under the accepted answer by the original poster) may be an effective way for you to switch the container context in a way that will allow your already instantiated Node object to save in your external DB:
//... mymodule_node_insert

$node = Node::load($id);
$db_switcher = new DatabaseSwitcher();
$db_switcher->changeToDifferentDb('external');

// save the node in the shared database
// Create node object with attached file.
$sharedNode = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$sharedNode->save();

$db_switcher->changeToDefaultDb();

Hope this works for you!
Comment: Thanks, great idea! I was really optimistic about this answer. Although, it does not work for nodes. After investing a bit time, I have found the reason. Nodes are getting saved through entity manager. So, just changing the database in the container is not enough. However, your answer showed me the path. Thanks
Comment: Now, the question is how can I change the entity.manager inside the container so this class works also for entities?
Answer: I too just came across this issue. All the examples on the web only show how to deal with SQL queries. Obviously when working with entities one would use Drupal's entity manager. The trick is to new up a new SqlContentEntityStorage instance
This is what I have done and it works
```

namespace Drupal\fintech_sync\Commands;

use Drupal\Core\Database\Database;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
use Drupal\Core\Queue\QueueInterface;
use Drupal\Core\State\State;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drush\Commands\DrushCommands;
use Drupal\Core\Queue\QueueFactory;

/**
 * Provides drush commands for fintech_sync module.
 */
class NewCommand extends DrushCommands {

  use StringTranslationTrait;

  /**
   * The queue.
   *
   * @var \Drupal\Core\Queue\QueueInterface
   */
  private QueueInterface $queue;

  /**
   * The state.
   *
   * @var \Drupal\Core\State\State
   */
  private State $state;

  /**
   * SyncCommand constructor.
   */
  public function __construct(QueueFactory $queue) {
    $this->queue = $queue->get('fintech_sync_worker');
    parent::__construct();
  }

  /**
   * Sync dbs.
   *
   * @command fintech_sync:create-accounts
   */
  public function syncCreateAccounts($customLastRun = FALSE): void {
    $this->createAccounts();
    $this->io()->success(t('Creating accounts on queue.'));
  }

  /**
   * Sync dbs.
   *
   * @command fintech_sync:sync-accounts
   */
  public function syncSyncAccounts(): void {
     foreach (['588', '589'] as $accountId) {
      $this->doRemoteSave('account', $accountId);
    }

    $this->io()->success(t('Sync the accounts it remote databes.'));
  }

  public function doRemoteSave(string $entityType, int $id): void {

    /** @var \Drupal\Core\Entity\EntityStorageInterface */
    $entityManager = \Drupal::entityTypeManager();
    $entity = $entityManager->getStorage($entityType)->load($id);

    // Set the database connection key.
    Database::setActiveConnection('replica');

    $database = Database::getConnection();
    $entity_field_manager = \Drupal::service('entity_field.manager');
    $cache = \Drupal::service('cache.entity');
    $language_manager = \Drupal::service('language_manager');
    $memory_cache = \Drupal::service('entity.memory_cache');
    $entity_type_bundle_info = \Drupal::service('entity_type.bundle.info');

    $new = $entity->createDuplicate();
    $new->set('id', $entity->id());
    $new->set('uuid', $entity->uuid());
    $new->set('created', $entity->get('created')->value);
    $new->set('changed', $entity->get('changed')->value);

    $remoteStorage = new SqlContentEntityStorage(
      $entity->getEntityType(),
      $database,
      $entity_field_manager,
      $cache,
      $language_manager,
      $memory_cache,
      $entity_type_bundle_info,
      $entityManager
  );
    // If setting fields (id and uuid) that have a foreign keys it will fail with;
    // Integrity constraint violation error on a second save; so delete it first.
    $remoteStorage->delete([$entity]);
    $remoteStorage->save($new);
  }

}


How do I go about increasing model complexity?

Question: I performed a simple linear regression on my data, but I want to increase the model complexity, using R.
I was told to use:
lm(y ~ poly(x, degree = n))

to increase the degree of the polynomial to $n$, but this doesn't seem right to me.
For example, I get different estimates and standard errors when I compare:
lm(y ~ x)

and
lm(y ~ poly(x, degree = 1))

Shouldn't they be the same? Sorry if this isn't much information.  Still learning R and statistics.
Comment: Please explain why you would want to make a model more complex.  Ordinarily that is not desirable: it is forced on us when we confront a model with data and find it does not fit well.  The problem then is to *improve* the model--but not for the sake of making it more complex!
Comment: @batmac The comment above should be moved to the main body of the question. To increase the _"model complexity"_ and _"to increase the complexity to a polynomial of degree 16"_ are two different things altogether.
Comment: @whuber Agreed! Conceptually, the purpose of a model is to reduce the complexity of the real world into something comprehensible. Not the other way around! A "more complex" model could be built by simply adding more "x or y variables". However... by "complex" do you mean, say, "larger", "more realistic", or "less understandable" (for its own sake), etc.?
Comment: http://stackoverflow.com/questions/3822535/fitting-polynomial-model-to-data-in-r That looks like it will answer the question that was asked. Whether the OP *should* do this is another question entirely.
Comment: Actually it was for a given problem that I'm trying to solve.  I was asked to increase to complexity to a polynomial of degree 16, then compare the RMSEs with the degrees of the polynomials.  The link @thecity2 pretty much helped me out!  Thanks guys!
Comment: I have heard R can be good for machine learning. But can I use it to train a [Rube Goldberg machine](https://en.wikipedia.org/wiki/Rube_Goldberg_machine)?
Answer:
There are many ways to increase model complexity. Using polynomial expansion is one way. Other ways include: 1. using other basis expansions, such as Fourier basis expansion. 2. using splines. Examples can be found in this post.  What's wrong to fit periodic data with polynomials?
If you want to use 16th order polynomial, you may consider using orthogonal polynomial instead of raw polynomial. Reasons can be found in this post. Why are there large coefficents for higher-order polynomial
If you want to know why lm(y~x) and lm(y~poly(x,1)), you can try to use model.matrix function to see, how the basis expansion changed your data. Here is an example on mtcars data. Note, even the order is 1, it changed your data.
> head(model.matrix(mpg~wt,mtcars))
                  (Intercept)    wt
Mazda RX4                   1 2.620
Mazda RX4 Wag               1 2.875
Datsun 710                  1 2.320
Hornet 4 Drive              1 3.215
Hornet Sportabout           1 3.440
Valiant                     1 3.460
> head(model.matrix(mpg~poly(wt,1),mtcars))
                  (Intercept)   poly(wt, 1)
Mazda RX4                   1 -0.1096309987
Mazda RX4 Wag               1 -0.0628232889
Datsun 710                  1 -0.1646988925
Hornet 4 Drive              1 -0.0004130092
Hornet Sportabout           1  0.0408879112
Valiant                     1  0.0445591041

However, the fitted values does not change, if the order is 1.
    > head(as.vector(lm(mpg~wt,mtcars)$fitted.values))
    [1] 23.28261 21.91977 24.88595 20.10265 18.90014 18.79325

    > head(as.vector(lm(mpg~poly(wt,1),mtcars)$fitted.values))
    [1] 23.28261 21.91977 24.88595 20.10265 18.90014 18.79325


Obtaining a new basis for a lattice with one of the new basis vectors fixed

Question: Suppose that a lattice $L$ in $\mathbb{R}^3$ is given with a basis $B = \mathbf{ \{ v_1, v_2, v_3 \} }$. Is there an algorithm that would help me obtain a new basis $B' = \mathbf{ \{ v_1', v_2', v_3' \} }$ for the same lattice $L$ such that $\mathbf{v_1'}$ is constrained to be along a certain lattice direction (smallest vector along the direction $\mathbf{v_1}'$).
I would also like to mention that this is not a homework problem and I am a researcher in engineering. It is possible that a solution already exists but I am not aware of all the terminology in the field of lattice problems. Any help is appreciated.
Thank you!
Edit: After Simon's answer, I would like to edit the question such that the volume occupied by the parallelepiped formed by the vectors of the basis $\mathbf{B'}$ to be the smallest possible volume in lattice $L$.
For example, one might consider $\mathbb{Z}^3$ with $\mathbf{v_1}=[1,0,0]^T$, $\mathbf{v_2}=[0,1,0]^T$ and $\mathbf{v_3}=[0,0,1]^T$ forming the basis $B$. This has volume 1 and while other bases are possible, one cannot find a basis of volume less than 1. Now the new basis $\mathbf{B'}$ should also have the same volume=1 in $\mathbb{Z}^3$.
Comment: When you say $\mathbf{v}_1'$ is constrained to be along a certain lattice vector, do you mean that it is fixed up to a choice of length? If not, then choosing $(2,0)$ as one vector for $\mathbb{Z}^2\subset\mathbb{R}^3$ means we can not extend this to a basis, as we need the product of the lengths of the basis vectors to be equal to $1$ (the covolume of the lattice).
Comment: No, just the direction is constrained. The length can be picked to be the shortest along that direction. I am assuming that a new basis can be described for any direction as long as it is a part of the lattice. In your example, we will chose $\mathbf{v_1'}$ to be (1,0).
Comment: In that case, you want to find a unimodular matrix with the vector $(a_1,a_2,a_3)^T$ as the first column, such that $\mathbf{v}_1'=a_1\mathbf{v}_1+a_2\mathbf{v}_2+a_3\mathbf{v}_3$. The other columns of the matrix will give you the other basis vectors.
Comment: Dear Daniel, would you mind elaborating what you mean by "find a unimodular matrix". I know that $(a_1, a_2, a_3)^T$ can be easily obtained by $B^{-1}\mathbf{v_1'}$ (basis vectors are assumed to be column vectors here). This forms the first column of the unimodular matrix. How are the other two columns obtained. If it is a routine problem in the algebra community, I would really appreciate it if you could provide me with some resources that I can read up. Thank you again for your help.
Answer: It's worth noting that there are infinitely many possible solutions, even in a particularly basic case: Consider if you have constrained not just $\vec{v_1} = (1,0,0)^T$, but also $\vec{v_2} = (0,1,0)^T$. Then you could pick $\vec{v_3}$ to be any vector of the form $(0,n,1)^T$ for any integer $n$ (or even more generally, any of the form $(m,n,1)^T$). So even if you have constrained the first two, there are infinitely many possibilities for the third.
Comment: Actually, any such basis (no matter the $m, n$) will have volume 1! This is since the volume of the parallelepiped spanned by the basis vectors has volume given by the determinant of the matrix. For $\vec{v_i}$ to be a basis, this must have determinant 1. So any new basis will be from a parallelepiped of volume 1.
Comment: Simon, Thank you for this example and you are absolutely right. I was definitely aware that there would be many answers but I did not quite think of them being infinite. This is a very good example and now I get this feeling that there are infinitely many possible solutions for all cases. At least for the problem that I have in hand, I am interested in the basis with the smallest volume. There might still be multiple solutions but it won't be infinite. I will edit the question accordingly. I wonder how to arrive at the solutions in this case! Thank you.
Comment: That is true, Simon. I should have carefully checked it. Hmm... I guess my question is not well formulated yet. Thank you for your help.


Maxima vector magnitude and cross product

Question: I'm new to maxima. And I have two questions:
1. Question
I have a little problem with computing vector's magnitude. Now I'm using such form as
sqrt(v1.v1)

This code looks very ugly.
2. Question
I thought vector cross product is expressed like a~b. but Maxima says ~ is not an infix operator
Answer: As far as I know, there is no built-in function to calculate a vector's magnitude, but you can easily define your own:
(%i1) norm(x) := sqrt(x . x)$
(%i2) norm([1, 1]);
(%o2)                               sqrt(2)

The cross product operator ~ is only available after loading 'vect':
(%i1) load("vect")$
(%i2) [1, 2, 3] ~ [2, 3, 4];
(%o2)                        [1, 2, 3] ~ [2, 3, 4]
(%i3) express(%);
(%o3)                            [- 1, 2, - 1]

Answer: If you don't mind using lists as vectors a very simple solution would be functions::
cross(u, v) := [u[2] * v[3] - v[2] * u[3], v[1] * u[3] - u[1] * v[3], u[1] * v[2] - v[1] * u[2]]$
dot(u, v) := u[1] * v[1] + u[2] * v[2] + u[3] * v[3]$
norm(u) := sqrt(dot(u, u))$

this is not an ideal nor safe solution but a concise one.
Answer: well, I didn't like the vec library, so I decided to write my own functions. here it goes:
/*this function gets 3 values as elements of a 3D vector and gives a (3,1) column matrix as the representation of the vector */
vec(vec_tempvar_a1,vec_tempvar_b1,vec_tempvar_c1):=block(
matrix([vec_tempvar_a1],[vec_tempvar_b1],[vec_tempvar_c1]))$

/*this function gets a (3,1) column matrix as representation of a 3D vector and delivers a scalar as the magnitude of the vector*/
vecmag(vecmag_tempvar_V1):= block(
sqrt(transpose(vecmag_tempvar_V1).vecmag_tempvar_V1))$

dotprod(dotprod_tempvar_V1,dotprod_tempvar_V2):=block(
transpose(dotprod_tempvar_V1).dotprod_tempvar_V2)$

/*this function calculates the vector/cross product of the vector on the left on the vector on the right*/

crosprod(crosprod_temvar_V1,crosprod_temvar_V2):= block(
matrix([(crosprod_temvar_V1[2,1]*crosprod_temvar_V2[3,1]-crosprod_temvar_V1[3,1]*crosprod_temvar_V2[2,1])],
       [(crosprod_temvar_V1[3,1]*crosprod_temvar_V2[1,1]-crosprod_temvar_V1[1,1]*crosprod_temvar_V2[3,1])],
       [(crosprod_temvar_V1[1,1]*crosprod_temvar_V2[2,1]-crosprod_temvar_V1[2,1]*crosprod_temvar_V2[1,1])])
)$

I have also been working on a maxima library for rigitd body dynamics, specially robotic applications using screw theory in particular. you may find it at github.com/Foadfs/RMaxima.


Disable autofilling missing HTML closing tags in Reveal MD

Question: The following code:
```python
x = '<x>'
```

Evaluates in Reveal MD to:
x = '<x>'</x>

Reveal MD tries to explore HTML tags and in case  of missing closing tags found it closes them automatically. Is there any way to block this feature? This is obviously a bug - I specified after backticks that my intention was to put Python code, not HTML one.
Answer: Replace < and > of the "tag" with html encoding items.
Expression
```python
x = '<x>'
```

evaluates to
x = '<x>'

as expected.


How can I add value to textbox, instead of setting value

Question: I'm trying to create a calculator, getting the values from buttons 1 to 9. Now I'd like to add a value to the textbox instead of setting it, like I want the user to be able to add 1 then 5 to make it a total of 15. How can I achieve this?
.prop sets a value, or .val so that one is out of the list.

CSS part:

    <button id="one">1</button>
    <button id="two">2</button>
    <button id="three">3</button>
    <button id="four">4</button>
    <button id="five">5</button>
    <button id="six">6</button>
    <button id="seven">7</button>
    <button id="eight">8</button>
    <button id="nine">9</button>
    <input type="text" id="entered" disabled="disabled"  />

Answer: Change
jQuery("#entered").prop("value", "1");

to
jQuery("#entered").val(jQuery("#entered").val() + "1");

This will concenate the old stuff with a new entered 1
This is the full code:

    <button id="one">1</button>
    <button id="two">2</button>
    <button id="three">3</button>
    <button id="four">4</button>
    <button id="five">5</button>
    <button id="six">6</button>
    <button id="seven">7</button>
    <button id="eight">8</button>
    <button id="nine">9</button>
    <input type="text" id="entered" disabled="disabled" value="" />

jQuery(document).ready(function () {
    jQuery("#one").click(function () {
        jQuery("#entered").val(jQuery("#entered").val() + "1");
    });

});

If you want to have a function for that:
 $.fn.appendVal = function (newPart) {
   return this.each(function(){ $(this).val( $(this).val() + newPart); });
 };

 $("#abc").appendVal("test");

https://jsfiddle.net/ffp19wze/ here is a working jsFiddle for it
Comment: A second nice way is discribed here:
http://stackoverflow.com/questions/1224133/is-it-possible-to-do-value-in-jquery
Comment: Oh but this one doesn't work properly because when there is not the first value, it returns undefined1...
Comment: Okay thanks, although I've already solved the problem with the link that you've sent to me. Thanks anyways! And If you could edit the answer with codes, I'd like to select you as the best answer.
Comment: I mean not just jsfiddle but this will do I guess, thanks for your answer. Have a good day!
Answer: Change your jQuery to
jQuery(document).ready(function () {
    jQuery("#one").click(function () {
        var cur_val = jQuery("#entered").val();
        cur_val = cur_val+"1";
        jQuery("#entered").val(cur_val);
    });

});


Add new existing field for existing content type

Question: I have a development site (let be site 1) and a site where I check my code (site 2). My goal was to add a new existing field to a paragraphs type (/admin/structure/paragraphs_type), so I did the following:
On site 1:

I re-used an existing field in one of the paragraphs type
I exported the configuration
I deleted uuid and _core.default_config_hash from the configuration files (from those which was relevant for me)
I wrote an update hook which will create the same config file (except order), when my module will be updated on other sites, where it was previously installed my module
I put the exported 3 files to my module's config/optional dir

Than I moved this module to the site 2 where I run the update hooks. But the newly added field wasn't showed up on the paragraphs type's page under the correct paragraphs type. All the configuration's dependencies are right and enabled. Configuration file is same except the order. If I want to add the field on site 2 manually again, after config import I get this error: There was a problem creating field : 'field_config' entity with ID 'paragraph.text_boxes.field_text' already exists.
Note: before I added the new field, I had a configuration export under git, so after I added a new field and exported the configuration I saw exactly which configs was touched.
What am I doing wrong? How can I add a new existing field to a paragraphs (or a content type)? What's missing?
Answer: if I am not wrong, I believe, Site 1 is your local development environment, and site 2 is your production environment.
I wrote an update hook which will create the same config file (except order), when my module will be updated on other sites, where it was previously installed my module
Why would you write an update hook ? You can simply export the configs, and import them on prod.
If this does not suit you, I would suggest you to use Features module for this. It will make sure you get a working module which can be installed even without features module in place on Prod.
Comment: I need update hook because the config files are on the module's dir's config/optional folder (these were exported from the site), so after I update the module (or somebody else from drupal org) they don't have the new field
Comment: In other words, if somebody has my module installed and I push an update with a new field, they don't get it after they update my module. They only get the new field when they reinstall my module, which means they loose all the content. Which is not good at any way.
Answer: Well finally I found a working solution for me, however I don't know why doesn't show up by default after config save.
First I need to connect my existing field (which I want to re-use) to the selected content type/paragraphs type:
\Drupal\field\Entity\FieldConfig::create([
  'entity_type' => 'node',
  'bundle'      => 'page',
  'field_name'  => 'field_text',
])->save();

This code will add a new field which machine name is field_text (needs to be exist in the system) into page content type which is a node.
Than if I edit the configuration (with configFactory) I can set the field name, view and form settings, etc. However you are able to set field settings with FieldConfig. (but not display and form)
Comment: See https://drupal.stackexchange.com/questions/222260/8-add-content-type-field-programmatically


At what points is this piecewise function continuous?

Question:
At which $c \in \mathbb{R}$ is the function $f:\mathbb{R} \rightarrow \mathbb{R}$ defined be
  $$f(x) = \begin{cases}       x & x \in \mathbb{Q}\\
       1-x & x \notin \mathbb{Q}
     \end{cases}$$
continuous

My Solution;
Now between every two rational numbers there exists a sequence of irrationals that converge to the rational number.
So if $c\in \mathbb{Q}$
$$\lim_{x \to c}f(x)=1-c \neq f(c)$$
So it is not continuous on the rationals.
If $c \notin \mathbb{Q}$
$$\lim_{x \to c}f(x)=1-c = f(c)$$
So function is continuous for all $c \notin \mathbb{Q}$.
Is this solution correct?
Any feedback would be appreciated.
Comment: Are you sure? If $c\ne \mathbb{Q}$ you could approximate it with a rational sequence.
Comment: apologies, there is a word missing in the question, im supposed to define at which $c$ the function is continuous
Answer: You say that $\lim_{x\to c} f(x)=1-c$. This is not correct. However, for suitable sequences $\{x_n\}_{n\in\mathbb N}$ with $x_n\to c$ (namely when all $x_n$ are irrational), we have $\lim_{n\to\infty}f(x_n)=1-c$. This is a much weaker statement! So you have to contemplate these problems:
a) For which $c$ does there exist such a "suitable" sequence of irrationals  with $x_n\to c$?
b) For which $c$ is the opposite possible, i..e that there exist a sequence of rationals $x_n$ with $x_n\to c$?
c) Does it matter for all $c$ whether a sqeuence converges to $1-c$ or $c$?
d) Is it enough to consider the types of sequences discussed under a) and b)?
Answer: No.
The first part is correct. If $c \in \mathbb{Q}$ then there's a sequence $c_n \notin \mathbb{Q}$ with $c_n \to c$, and $f$ being continuous at $c$ then requires $$
  \lim_{n\to\infty} f(c_n) = \lim_{n\to\infty} 1 - c_n = 1 - c \overset!= c = f(c) \text{.}
$$
Note that this condition is only necessary, not sufficient, since we only considered a particular sequence.
But the same works the other way around. If $c \notin \mathbb{Q}$, then there's a sequence $c_n \in \mathbb{Q}$ with $c_n \to c$, and just as above we get the necessary condition  $$
  1 - c \overset!= c \text{.}
$$
for $f$ to be continuous at $c$.
So we know that $f$ is discontinuous, except possibly at points where $c = 1-c$, i.e. at $c = \frac{1}{2}$. Since the conditions above where only necessary, not sufficient, we can't immediately conclude that $f$ is continuous at $\frac{1}{2}$. We need to verify that $$
  \lim_{x \to \frac{1}{2}} f(x) = f(\tfrac{1}{2}) = \tfrac{1}{2} \text{.}
$$
But that's easy. Let $|x - \frac{1}{2}| < \epsilon$. Then if $x \in \mathbb{Q}$, $$
  |f(x) - \tfrac{1}{2}| = |x - \tfrac{1}{2}| < \epsilon
$$
and also if $x \notin \mathbb{Q}$, $$
  |f(x) - \tfrac{1}{2}| = |1 - x - \tfrac{1}{2}| = |\tfrac{1}{2} - x| = |x - \tfrac{1}{2}|  < \epsilon \text{.}
$$
So $f$ is indeed continuous at $\frac{1}{2}$.


How to compare the mean of two samples whose data fits exponential distributions

Question: I have two samples of data, a baseline sample, and a treatment sample.
The hypothesis is that the treatment sample has a higher mean than the baseline sample.
Both samples are exponential in shape.  Since the data is rather large, I only have the mean and the number of elements for each sample at the time I will be running the test.
How can I test that hypothesis?  I'm guessing that it is super easy, and I've come across several references to using the F-Test, but I'm not sure how the parameters map.
Comment: Why don't you have the data? If the samples are really large non-parametric tests should work great, but it sounds like you're trying to run a test from the summary statistics. Is that right?
Comment: @Mimshot, the data is streaming, but you are correct that I'm trying to run a test from the summary statistics.  It works quite well with a Z test for normal data
Comment: Under these circumstances, an approximate z-test is maybe the best you can do. However, I would more care about how large the true treatment effect is, not about statistical significance. Remember, that with large enough samples, any tiny true effect will lead to a small p value.
Comment: @january - although, if his sample sizes are large enough, by the CLT they will be very close to normally distributed.  Under the null hypothesis, the variances would be the same (as the means are), so, with a large enough sample size, a t-test should work fine; it won't be as good as you can do with all the data, but still would be OK.   $n_1 = n_2 = 100$, for example, would be pretty good.
Comment: Are the baseline and treatment values from the same patient set or are the two groups independent?
Comment: @MichaelMayer they are independent
Comment: @JonathanDobbie "It works quite well with a Z test for normal data" -- how's that? I thought you only have the mean, and no standard deviation?
Comment: @January for normal data, I keep around a running sum of squares
Comment: @January: For exponentials, standard deviations equal means. But this is also the weakness here (unequal group variances).
Comment: @MichaelMayer yep, but he is actually looking at the difference in means ($H_0: \mu_1 - \mu_2 = 0$), which is not exponentially distributed.
Comment: @January: The difference in means is hopefully not too far from being normal :-)
Answer: You can test equality of the mean parameters against the alternative that the mean parameters are unequal with a likelihood ratio test (LR test). (However, if the mean parameters do differ and the distribution is exponential, this is a scale shift, not a location shift.)
For a one-tailed test (but only asymptotically in the two tailed case), I believe that the LR test comes out to be equivalent to the following (to show that this is in fact the same as the LR test for the one-tailed case one would need to show the LR statistic was monotonic in $\bar x/\bar y$):
Let's say we parameterize the $i$th observation in the first exponential as having pdf $1/\mu_x \exp(-x_i/\mu_x)$ and the $j$th observation in the second sample as having pdf $1/\mu_y \exp(-y_j/\mu_y)$ (over the obvious domains for the observations and parameters).
(To be clear, we're working in the mean-form not the rate-form here; this won't affect the outcome of the calculations.)
Since the distribution of $X_i$ is a special case of the gamma, $\Gamma(1,\mu_x)$, the distribution of the sum of $X$'s, $S_x=\sum_i X_i$ is distributed $\Gamma(n_x,\mu_x)$; similarly that for the sum of the $Y$s, $S_y$ is $\Gamma(n_y,\mu_y)$.
Because of the relationship between gamma distributions and chi-squared distributions, it turns out that $2/\mu_x S_x$ is distributed $\chi^2_{2n_x}$. The ratio of two chi-squares on their degrees of freedom is F. Hence the ratio, $\frac{\mu_y}{\mu_x}\frac{S_x/n_x}{S_y/n_y} \sim F_{2n_x,2n_y}$.
Under the null hypothesis of equality of means, then, $\bar x/\bar y \sim F_{2n_x,2n_y}$, and under the two sided alternative, the values might tend to be either smaller or larger than a value from the null distribution, so you need a two-tailed test.

Simulation to check that we didn't make some simple mistake in the algebra:
Here I simulated 1000 samples of size 30 for $X$ and 20 for $Y$ from an exponential
distribution with the same mean, and computed the above ratio-of-means statistic.
Below is a histogram of the resulting distribution as well as a curve showing the
$F$ distribution we computed under the null:

Example, with discussion of computation of two-tailed p-values:
To illustrate the calculation, here's two small samples from exponential distributions. The X-sample has 14 observations from a population with mean 10, the Y-sample has 17 observations from a population with mean 15:
x: 12.173  3.148 33.873  0.160  3.054 11.579 13.491  7.048 48.836
   16.478  3.323  3.520  7.113  5.358

y:  7.635  1.508 29.987 13.636  8.709 13.132 12.141  5.280 23.447
   18.687 13.055 47.747  0.334  7.745 26.287 34.390  9.596

The sample means are 12.082 and 16.077 respectively. The ratio of means is 0.7515
The area to the left is straightforward, since it's in the lower tail (calc in R):
 > pf(r,28,34)
 [1] 0.2210767

We need the probability for the other tail. If the distribution was
symmetric in the inverse, it would be straightforward to do this.
A common convention with the ratio of variances F-test (which is similarly two
tailed) is simply to double the one-tailed p-value (effectively what is going on as here;
that's also what seems to be done
in R, for example); in this case it gives a p-value of 0.44.
However, if you do it with a formal rejection rule,
by putting an area of $\alpha/2$ in
each tail, you'd get critical values as described here.
The p-value is then the largest $\alpha$ that would lead to rejection, which is equivalent to
adding the one tailed p-value above to the one-tailed p-value in the other tail for the degrees of freedom interchanged. In the above example that gives a p-value of 0.43.
[Neither of these rules are "optimal" in small samples]
Comment: I have made the distinction between the population means and the resulting sample means more clear
Comment: I'm guessing this is just me being thick, but where does 0.7515 come from?
Comment: r = mean(x)/mean(y) = 0.7515 - that is, "The ratio of means"
Comment: Okay, awesome.  I got 0.67, but that is probably just due to a data entry error.
Comment: (+1) But though it's tangential, I don't understand the last paragraph. How is doubling the one-tailed p-value not equivalent to finding the largest $\alpha$, with an area $\frac{\alpha}{2}$ in each tail, that would lead to rejection? Why would you interchange the degrees of freedom at all?
Comment: Because $S_x$ is often used to denote sample standard deviation, it seems worth noting explicitly that $S_x = n\bar X_n$ here. But (+1).
Answer: As an addendum to @Glen_b's answer, the log likelihood ratio is
$$n_x\log \frac{n_x}{\sum x_i} +n_y \log \frac{n_y}{\sum y_j} -(n_x+n_y)\log\frac{n_x+n_y}{\sum x_i +\sum y_j}$$
which you can rearrange to
$$n_x\log\left(\frac{n_x}{n_y} + \frac{1}{r}\right) + n_y\log\left(\frac{n_y}{n_x}+r\right) + n_x\log\frac{n_y}{n_x+n_y} + n_y\log \frac{n_x}{n_x+n_y}$$
where $r=\frac{\bar{x}}{\bar{y}}$. There's a single minimum at $r=1$, so the F-test is indeed the likelihood ratio test against one-sided alternatives to the null hypothesis of identical distributions.
To perform the likelihood-ratio test proper for a two-sided alternative you can still use the F-distribution; you simply need to find the other value of the ratio of sample means $r_\mathrm{ELR}$ for which the likelihood ratio is equal to that of the observed ratio $r_\mathrm{obs}$, & then $\Pr(R>r_\mathrm{ELR})$. For this example $r_\mathrm{ELR}=1.3272$, & $\Pr(R>r_\mathrm{ELR})=0.2142$, giving an overall p-value of $0.4352$, (rather close to that obtained by the chi-square approximation to the distribution of twice the log likelihood ratio, $0.4315$).

But doubling the one-tailed p-value is perhaps the most common way to obtain a two-tailed p-value: it's equivalent to finding the value of the ratio of sample means $r_\mathrm{ETP}$ for which the tail probability $\Pr(R>r_\mathrm{ETP})$ is equal to $\Pr(R<r_\mathrm{obs})$, & then finding $\Pr(R>r_\mathrm{ETP})$. Explained like that, it might seem to be putting the cart before the horse in letting tail probabilities define the extremeness of a test statistic, but it can be justified as being in effect two one-tailed tests (each the LRT) with a multiple comparisons correction—& people are usually interested in claiming either that $\mu_x > \mu_y$ or that $\mu_x < \mu_y$ rather than that either $\mu_x > \mu_y$ or $\mu_x < \mu_y$. It's also less fuss, & even for fairly small sample sizes, gives much the same answer as the two-tailed LRT proper.

R code follows:
x <- c(12.173, 3.148, 33.873, 0.160, 3.054, 11.579, 13.491, 7.048, 48.836,
       16.478, 3.323, 3.520, 7.113, 5.358)

y <- c(7.635, 1.508, 29.987, 13.636, 8.709, 13.132, 12.141, 5.280, 23.447,
       18.687, 13.055, 47.747, 0.334,7.745, 26.287, 34.390, 9.596)

# observed ratio of sample means
r.obs <- mean(x)/mean(y)

# sample sizes
n.x <- length(x)
n.y <- length(y)

# define log likelihood ratio function
calc.llr <- function(r,n.x,n.y){
  n.x * log(n.x/n.y + 1/r) + n.y*log(n.y/n.x + r) + n.x*log(n.y/(n.x+n.y)) + n.y*log(n.x/(n.x+n.y))
}

# observed log likelihood ratio
calc.llr(r.obs,n.x, n.y) -> llr.obs

# p-value in lower tail
pf(r.obs,2*n.x,2*n.y) -> p.lo

# find the other ratio of sample means giving an LLR equal to that observed
uniroot(function(x) calc.llr(x,n.x,n.y)-llr.obs, lower=1.2, upper=1.4, tol=1e-6)$root -> r.hi

#p.value in upper tail
p.hi <- 1-pf(r.hi,2*n.x,2*n.y)

# overall p.value
p.value <- p.lo + p.hi

#approximate p.value
1-pchisq(2*llr.obs, 1)


Struct becomes NULL even after assigning value from another function in a loop

Question: I am having troubles with my code. As you can see below, I have to make a list using linked list technique. My problem is that when I printf the s->item outside the add() function after performing it, the program crashes.
When I print the s->item inside the add() function, it does print the correct data. Why does Statistician s become null again, even if the intialization of it is outside the while loop?
Please don't mind the typedefs, they are given by our instructor and we have to use it as basis so we dont have to change anything with the typedefs and structs.
typedef struct node *nodePtr;
struct node {
    int item;
    nodePtr next;
};
typedef nodePtr Statistician;

Statistician newStatistician(){
      Statistician s = (Statistician)malloc(sizeof(Statistician));
      s = NULL;
      return s;
}

void add(Statistician s, int x){

Statistician newNode = (Statistician)malloc(sizeof(Statistician));

if(s == NULL){ // first node
    printf("first");
    newNode->next = NULL;
    newNode->item = x;
    s = newNode;

main(){
int menuChoice, clearDataChoice, x, outputInt, exitChoice, check;
float  outputFloat;
Statistician s = newStatistician();

while (TRUE){
    printf("\t\t*** STATISTICIAN PROGRAM v1 ***\n\n\n");
        printf("Please enter data to be added : ");
        x = inputNum();
        add(s, x);
        printf("%d", s->item);
//... bunch of other code

   if(exitChoice==TRUE)
        return 0;
    else{
        printf("\n\nPress any key to continue...");
        getch();
        system("cls");
        fflush(stdin);
        continue;
    }
}

EDIT: add and main are 2 different functions
   void add(Statistician s, int x){}
    main(){}

Comment: `malloc` returns a pointer, not an object. `Statistician s = (Statistician)malloc(sizeof(Statistician));` is wrong. See also https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc
Comment: You should include a [mcve] that demonstrates the problem. As it is, you have chunks of functions (`add` is cut off) lying around. Also, `newStatistician` leaks memory, and is always returning a NULL pointer.
Comment: Also, you're only allocating enough memory for a pointer, and not the full node object; you might want to remove the second typedef, as that appears to be causing some confusion.
Comment: You need not cast the result of malloc.
Comment: Friendly advice: never typedef a pointer. You need to know when you're dealing with a pointer. Hiding the pointer with a typedef actually makes the code harder to read. For example, in the `newStatistician` function, `sizeof(Statistician)` is the size of a pointer, not the size of the node structure.
Comment: This code has some missing brackets and stuff, you need not cast the result of malloc, the while loop could also be changed to a do-while.

Ignore what I said in my  second comment.
After you fix up your code a bit (according to what others have said ), try your add() with the dereference &.
add(s&, x)
Comment: @user3386109 what keyword do i use inside the malloc to make it have the size of the node structure?
Comment: @timi95 if i use &s in add() it considers *&s* as a pointed variable of double pointer which *Statistician s* is not
Comment: Among other problems, your `newStatistician` function always returns a null pointer.

A bigger problem: The code in your question will not compile. Please update your question with a [mcve] (follow that link).
Answer: Talk to your instructor and ask him/her to explain the scope of variables to you.
The basic cause of the problem is that Statistician is a node *.  So, you're passing a pointer to a Statistician to add(), but add() receives a private copy of the pointer itself: its variable s.  You're modifying that private copy of s, but that modification doesn't affect the s in main().  So all the changes you make to the private copy in add() are lost when it returns.
The most usual way to solve this, and it's a fairly common pattern in C, is to return the possibly modified private copy of s from add().  So you'd change it's declaration to:
Statistician add(Statistician s, int x)

and then add the following at the very bottom:
return s;

Then when you actually call it in main() change the line to this:
s = add(s, x);

Give that a try and see how it works.
Comment: Bear in mind that `Statistician` is, it seems, already a pointer, due to the dodgy typedeffing.
Comment: @PhilM  Ugh.  I had the prototype of `add()` all wrong.  It's fixed now.  Code like this tends to reinforce my agreement with Herb Sutter's Guru when she said that typedefs that just do pointer adornment are vanity, and lead to trouble.
Comment: Thanks for the quick reply, im gonna talk to my instructor about this. But it I think that I will be told to just follow the structure given
Comment: Why does Statistician s become a private variable if it is a pointer?
Comment: I mean, how does it not change the value of struct node if it is a pointer?
Comment: Because a pointer is just a value, like an `int` is. If you pass an int by value and change it inside the function, that change won't propagate outside the function, since you've only changed a copy. Same for the **value** of a pointer. That's different than changing the value of what the pointer points to.


Overriding highlighted selection in UIPickerView

Question: I have a custom UIPickerView where I use:
-(UIView *)pickerView:(UIPickerView *)pickerView
       viewForRow:(NSInteger)row
     forComponent:(NSInteger)component
      reusingView:(UIView *)view

to populate the picker with UILabels.  Is there a way to disable the behavior of highlighting the selected row when touched?
I think this is a property of the underlying UITableViewCell inherent in the UIPickerView and I can't find a way to change it.
Answer: You need to make sure your custom view has the following properties:

It needs to be sized to the same dimensions that the UIPickerView expects based on your delegate methods -- pickerView:rowHeightForComponent: and pickerView:widthForComponent:. The default height is 44 if you're not specifying a custom height.
The background color must be [UIColor clearColor].
The view must capture all touches.

The one gotcha when using UILabel instances as the custom view is that UILabel defaults userInteractionEnabled to NO (UIView, on the other hand, defaults this property to YES).
Based on these requirements, the example code from Halle can be rewritten as follows. This example also correctly reuses previously created views, which is needed for fast scrolling performance.
- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {

  UILabel *pickerRowLabel = (UILabel *)view;
  if (pickerRowLabel == nil) {
    // Rule 1: width and height match what the picker view expects.
    //         Change as needed.
    CGRect frame = CGRectMake(0.0, 0.0, 320, 44);
    pickerRowLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    // Rule 2: background color is clear. The view is positioned over
    //         the UIPickerView chrome.
    pickerRowLabel.backgroundColor = [UIColor clearColor];
    // Rule 3: view must capture all touches otherwise the cell will highlight,
    //         because the picker view uses a UITableView in its implementation.
    pickerRowLabel.userInteractionEnabled = YES;
  }
  pickerRowLabel.text = [pickerDataArray objectAtIndex:row];

  return pickerRowLabel;
}

Answer: Setting the userInteractionEnabled property of UILabel to YES fixes the highlighting issue, but it also disables the UIPickerView from autoscrolling to select the row that has been touched.
If you want to disable the highlighting behavior, but maintain the UIPickerView's default autoscrolling functionality, call the setShowSelection function in the UITableCell instances contained in the UIPickerView. A way of doing this is to subclass the UILabel class similar to the following:
PickerViewLabel.h -
#import <UIKit/UIKit.h>

@interface PickerViewLabel:UILabel
{
}

@end

PickerViewLabel.m -
#import "PickerViewLabel.h"

@implementation PickerViewLabel

- (void)didMoveToSuperview
{
 if ([[self superview] respondsToSelector:@selector(setShowSelection:)])
 {
  [[self superview] performSelector:@selector(setShowSelection:) withObject:NO];
 }
}

@end

Then, where you had previously been returning an instance of UILabel in pickerView:viewForRow:forComponent:reusingView:, return an instance of PickerViewLabel. As an example, using the code from Doug, you would replace all the cases of 'UILabel' with 'PickerViewLabel'. Just remember to remove the pickerRowLabel.userInteractionEnabled = YES; line.
Comment: Hi Christine, I implemented the same above code but still blue selection comes at both end of selected row. When I try to debug the code, I found that didMoveToSuperview is not called anywhere. Can you help me? Thanks.
Comment: Hey Shailesh, It's hard to say w/o seeing your code, but I have a few ideas as to why it would not be called. 'didMoveToSuperview' is a function of UIView that gets called automatically anytime that a UIView is added or removed from a view. Is your custom view definitely being added to the screen? If you do a quick test and add an instance of your class as a subview of a UIViewController's view, do you see 'didMoveToSuperview' being called then? If not, I would guess that you have a typo somewhere in the function declaration.
Answer: I guess you may want to look at "showsSelectionIndicator" property of UIPickerView
Comment: The showsSelectionIndicator is responsible for displaying the blue bar over the value that will be returned by the picker.  It unfortunately has nothing to do with the underlying UITableViewCell structure.
Answer: I'm not sure if there is an easy way to remove the selection feedback, but you can cover it up if you make the background of the label white and size it to the same dimensions as the blue selection rectangle:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

    UILabel *pickerRowLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 316, 40)];
    pickerRowLabel.backgroundColor = [UIColor whiteColor];
    pickerRowLabel.text = [pickerDataArray objectAtIndex:row];
    [self.view addSubview:pickerRowLabel];

    return pickerRowLabel;

}

With a width of 316 the label covers all but a sliver of blue on each side, and at 320 it completely covers the selection feedback but it also starts to cover a bit of the outer wheel gradients, which may or may not bother you.


Effect of basis functions on the dimension of a linear regression model

Question: In Scikit-learn I can use polynomial features to create polynomial linear regression models. Scikit-learn transforms my original data as follows. If I had a datapoint [2], it would return [2,4,8] with 3 basis functions $(x, x^2, x^3).$ This means that it is increasing the dimensionality of the model, indeed because these monomials form a basis for the vector space of cubics. So the resulting model is a linear combination of monomials.
My question therefore is how do basis functions relate to the dimensionality of the model? Precisely which vector space do they form a basis for? How do we construct the linear regression model taking into account that vector space?
Answer: The model space
As always in a linear model, with a $n\times k$ model matrix $X$ for $n$ observations and $k$ features, the space is the set of all possible vectors $X\beta$ where $\beta$ is the collection of $k$ coefficients (the "parameters").
Geometrically, the parameter $\beta\in\mathbb{R}^k$ is a vector and $X$ represents a linear transformation from $\mathbb{R}^k$ to $\mathbb{R}^n.$  The model space is the image of $X.$  It's a linear subspace of $\mathbb{R}^n,$ the so-called "column space" of $X.$  Linear algebra tells us the dimension of this space equals the dimension of the domain $(k)$ minus the dimension of the kernel (the "null space" of $X$), whence the dimension cannot exceed $k$ and equals $k$ precisely when the only vector $\beta$ for which $X\beta=0$ is the zero vector itself.
The dimension of the space
Can more be said?  Yes, but it's a little delicate. Let's focus on the columns generated by monomials.  Suppose they correspond to $x^{e_1}, x^{e_2},$ and so on, through $x^{e_p},$ where all the exponents $e_j$ are distinct positive integers.  We may order the exponents so that $1\le e_1 \lt e_2 \lt \cdots \lt e_p,$ whence $e_p \ge p.$
Notice that when a value of $x$ is the same for two observations, these monomials generate identical rows, which therefore are linearly dependent: the extra rows do not change the dimension of the space of the model.  Thus, we only need to consider the distinct values of $x$ in the dataset.  Let there be $m\le n$ of these and let $X_0$ designate the model matrix for the $m$ distinct observations.
(Geometrically, the equality of some of the original values $x$ means the data reside in some $m$-dimensional subspace $V^m$ of $\mathbb{R}^n.$  Limiting to a set of unique rows of $X$ induces a linear isomorphism $\iota: V^m\to\mathbb{R}^m.$ $X_0$ thereby represents a linear transformation $X_0:\mathbb{R}^p \to \mathbb{R}^m$ given by applying $X$ and following that by $\iota.$  You did ask "precisely what vector space" was involved!)
To compute the dimension of the model space, let's do it indirectly by finding some null vectors.  That is, we seek $p$-vectors $\beta$ for which $X_0\beta=0.$  Writing these distinct values of $x$ as $x_1,x_2, \ldots, x_m,$ we have
$$X_0 = \left(x_i^{e_j}\right) = \pmatrix{x_1^{e_1} & x_1^{e_2} & \cdots & x_1^{e_p}\\
x_2^{e_1} & x_2^{e_2} & \cdots & x_2^{e_p}\\
\vdots & \vdots & \ddots & \vdots\\
x_m^{e_1} & x_m^{e_2} & \cdots & x_m^{e_p}}.$$
The equation $X_0\beta = 0$ represents the system of simultaneous equations
$$\beta_1 x_i^{e_1} + \beta_2 x_i^{e^2} + \cdots + \beta_p x_i^{e^p} = 0,$$
$i = 1, 2, \ldots, m.$  In other words,

All the $x_i$ are roots of the polynomial $\beta_1 T^{e_1} + \beta_2 T^{e_2} + \cdots + \beta_p T^{e_p}.$

Because the $x_i$ are distinct, this polynomial has at least $m$ roots.  The Fundamental Theorem of Algebra, which asserts any polynomial of degree $p$ (with real or complex coefficients) has at most $p$ distinct roots (real or complex), implies $e_p \ge m.$  Consequently,

The kernel of the model matrix is $\{0\}$ whenever $e_p\lt m:$ that is, whenever the maximum power of your monomials is less than the number of distinct values of $x,$ the dimension of the space generated by those monomials equals the number of monomials.  There is no redundancy.

An important corollary is that when the powers are $e_j = 1,2,\ldots, p,$ then so long as you use fewer monomials $(p)$ than distinct values of $x$ $(m),$ the dimension of the model space will equal the number of monomials.
As a simple common example, suppose $x$ is a binary indicator, thereby limited to two values, and that both values appear in the data.  This result shows that when you are including an intercept in the model (essentially $x^0=1$) along with $x$ itself, it's pointless to introduce any more monomials.
Constructing a model matrix
It's usually not a good idea to work with the matrices $X$ and $X_0$ whose columns are monomials, because they often create numerical instabilities.  Part of the problem is that high powers grow very quickly.  If you have, say, distinct values of $x$ from $1$ through $10$ and you choose to include a monomial of degree $e_j=16$ or higher, $1^{e_j}$ is indistinguishable from $0$ in comparison to $10^{e_j}$ when you are using double-precision floating point arithmetic, as illustrated in Python 3.0 here:

Standardizing the columns helps a little, but not much, because the monomials tend to be nearly collinear anyway.  See Why are there large coefficents for higher-order polynomial for some discussion.
The standard solution is to compute orthogonal polynomials.  These are linear combinations of the monomials $T^{e_j}$ that, when applied to the values $x_i,$ give vectors that are orthogonal to each other.  (They form a different basis for the model space, but the model space is unchanged.)  The orthogonality is the opposite of nearly collinear: these new columns don't interfere with each other in the underlying calculations.  For much more about this, including some statistical subtleties, please read Raw or orthogonal polynomial regression?.
An often overlooked point is that despite being called "orthogonal polynomials," which sounds kind of universal, the orthogonal polynomials depend on the specific distinct values $x_i.$  Some of the links I provide (above and below) mention good ways to compute the orthogonal polynomials for a dataset.
We have many good discussions and examples of the use of orthogonal polynomials in regression models: please see the results of this site search for some of the better answers.
Finally, if you would like to see explicit examples of model matrices involving orthogonal polynomials, I included some in a post on multivariate orthogonal polynomials.


Save ObservableCollection to textfile when closing MainWindow

Question: I'm realtivley new to C# and WPF and have gotten the task to program an Alarm. Now I have the problem, that I have to save the set times to a textfile when closing the mainwindow.
The times are stored in an ObservableCollection of the type Reminder, a class i wrote myself and stores the time and name of the alarm as string.
public override string ToString()
    {
        return ReminderName + " " + ReminderTime.ToString("HH:mm");
    }

My saving function looks like this:
...
public RelayCommand<object> SaveAllTimes { get; set; }
...
public MainWindowModel()
{
...
SaveAllTimes = new RelayCommand<object>(SaveReminders, CanSaveReminders);
...
}

private void SaveReminders(object sender)
    {

        StreamWriter writer = new StreamWriter("time.txt");
            foreach (Reminder time in Reminders)
            {
                writer.WriteLine(time.ToString());
            }
    }

Now how can I bind the view to this function, that it's executed when the user closes it?
My view looks like this:
<Window x:Class="Wecker1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Wecker1"
    Height="350"
    Width="310" >

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="3*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>

    <ListBox Name="Liste" ItemsSource="{Binding Reminders}" Margin="10" Grid.Row="0">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding}" IsChecked="{Binding Active}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <Button Command="{Binding SaveTime}" Content="Add Reminder" Margin="10" Grid.Column="1"/>
        <Button Margin="10" Content="Stop" Command="{Binding DeleteTime}"
            CommandParameter="{Binding ElementName=Liste,Path=SelectedItem}" />
    </Grid>

</Grid>
</Window>

Answer: Somewhere in your code, you are creating your View and ViewModel. From my point of view (and this part surely is opinion-based) you should implement your On-Exit code there, because your saving of data is at the end of the process, not the end of the view. When your MainWindow was run, you can call a viewmodel method to save all it's relevant data.
If you do want to have it upon closing the view instead of ending the program, you can go two paths: the dark side, by writing a code-behind OnClose handler for the window. Don't tell anyone I said so. That's not WPF style. Or the correct path by implementing a Close-Behavior for your window. That's too broad for a single post, you should look up WPF, View and Behavior, you will find lots of tutorials for different behaviors.
Answer: You can use interactivity to bind Closing event to your Command like below
<Window xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">

</Window>

Answer: here is my approach using pure MVVM, not dependent to any other provider
xaml
<Window x:Class="CSharpWPF.ViewModel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:l="clr-namespace:CSharpWPF"
        l:MyEventHandler.ClosingCommand="{Binding SaveAllTimes}">
</Window>

MyEventHandler class
namespace CSharpWPF
{
    public class MyEventHandler
    {
        public static ICommand GetClosingCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(ClosingCommandProperty);
        }

        public static void SetClosingCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(ClosingCommandProperty, value);
        }

        // Using a DependencyProperty as the backing store for ClosingCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ClosingCommandProperty =
            DependencyProperty.RegisterAttached("ClosingCommand", typeof(ICommand), typeof(MyEventHandler), new PropertyMetadata(OnClosingCommandChanged));

        private static void OnClosingCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Window window = d as Window;
            window.Closing += (s, ee) => GetClosingCommand(d).Execute(ee);
        }
    }
}

so the whole idea is to route the events to binded commands via Attached Properties, you may create more handlers as you need


code gives "java.lang.StringIndexOutOfBoundsException: String index out of range: 14"

Question: the following code gives me "java.lang.StringIndexOutOfBoundsException: String index out of range: 14"
Please guide me on what is wrong with my code.
public class max_temp {

    public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        public String y;
        public String a;
        public Double t;

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {

            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                y = word.toString();
                a = y.substring(7,14);
                t = Double.parseDouble((y.substring(35,41).trim()));

                word.set(a);

               // 27516201501012.424-156.6171.32-18.3-21.8-20.0-1   9.90.00.00C-19.2-24.5-21.983.973.777.
               context.write(word, one);
           }
       }
   }

   public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
       private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }
}

Comment: Possible duplicate of [Java substring : string index out of range](http://stackoverflow.com/questions/953527/java-substring-string-index-out-of-range)
Comment: The 15th character in your string does not exist. Your string is shorter than that.
Comment: does every word has 21 characters or more?
Comment: Did my answer help you? If yes, please mark it as a solution by clicking on the gray tick below the answer score.
Answer: It would be easier if you attached the stacktrace. Anyway, the problem is, that you're calling the substring(7,14) of the String which has length smaller then 15. Java doesn't know what to do and therefore throws an exception.
The problem is with your app logic. If you use substring(7,14) you have to be sure that the String is long enough or use try-catch block.
try {
    String s = s.substring(7,14);
} catch (StringIndexOutOfBoundsException e) {
    //somehow process the situation in which the string is too short.
}


elementary numbers- set with n numbers contains subset that the sum of whose elements is a multiple of n

Question: how can I prove a set with n numbers contains subset that the sum of whose elements is a multiple of n
I'm not sure if I can use EGZ theory here
Answer: If we allow the emptyset, then the statement is trivial since everything divides zero.  We instead prove the stronger statement for a nonempty subset.
Let the set be $\{a_1,a_2,\dots,a_n\}$
Consider the set of numbers $\{b_1,b_2,\dots,b_n\}$ where $b_i := a_1+a_2+\dots+a_i$
Applying the pigeon-hole principle, let our set $\{b_1,\dots,b_n\}$ be our set of pigeons and the equivalence classes modulo $n$ be our holes.
One of two things will occur:  either there exist $b_i,b_j$ with $i<j$ such that $b_i\equiv b_j\pmod{n}$, or every equivalence class has exactly one entry $b_i$ in it, in particular the equivalence class of $0$.
In the first case, notice that $b_j-b_i = (a_1+a_2+\dots+a_j) - (a_1+a_2+\dots+a_i) = a_{i+1}+a_{i+2}+\dots+a_j$
That $b_j\equiv b_i\pmod{n}$ implies $b_j-b_i$ is a multiple of $n$, and therefore the subset $\{a_{i+1},a_{i+2},\dots,a_j\}$ has the sum a multiple of $n$.
In the second case, you have some $i$ for which $b_i\equiv 0\pmod{n}$ which implies $a_1+a_2+\dots+a_i$ is a multiple of $n$.