How can nuisance parameters in Fisher matrix can deteriorate the useful constraints?

Question: I have a Fisher matrix $F$ which has the matrix blocks form like this :
$$
F=\begin{bmatrix}
A & B\\
C & D
\end{bmatrix}
$$
The block $A$ is the most important block, in the sense the parameters of this block are the parameters that I want really get. The block $D$ is called the "nuisance block", that is to say, it consists of the nuisance parameters which deteriorate the informations of the block $A$. The blokc $B$ and $C$ are the correlations blocks between "important block" $A$ and "nuisance block" $D$.
Question : How can I prove mathematically that, by inversing the Fisher matrix $F$, I will get worse constraints (I mean larger variances) on the important parameters (corresponding to $A$ covariance matrix), all of this due to the 3 others blocks ?
Track followed :
I know that (1,1) block for inverse of $F$ :
$$
F=\begin{bmatrix}
A & B\\
C & D
\end{bmatrix}
$$
is $(A-BD^{-1}C)^{-1}$ (Schur complement).
From this, if I take the inverse of Fisher matrix $F$, I will get for covariance matrix (the inverse of $F$), the block (1,1) equal to $(A-BD^{-1}C)^{-1}$.
How can we be sure that diagonal of this block $(A-BD^{-1}C)^{-1}$ (which represents the variances of important parameters) will be decreased by the terms "$-BD^{-1}C$" : we should have positive quantities for the diagonal elements of "-$BD^{-1}C$" to make increase the block (1,1) diagonals elements, i.e in order to make worse the constraints, shouldn't we ?
I make the comparison with the values unmarginalised of block A which have the form into initial Fisher matrix F : a_11 = 1/sigma_1^2, a_22 = 1/sigma_2^2, a_33 = 1/sigma_3^2 ... etc. with sigma_i the standard deviation of each important parameters of block A.
I guess it is difficult to prove that nuisance parameters deteriorate the constraints for block (1,1) of covariance matrix but it would be interesting to have a rigorous demonstration.
Comment: When you say "Fisher matrix", I assume you mean *Fisher information matrix*. Assuming that is correct, then you must have $B=C^T$ and $A$ and $D$ must be positive definite. With these clarifications, result is very easy to prove.
Comment: @GordonSmyth . Thanks for your quick answer. Could you explicit please your reasoning in an answer please ? I didn't manage to prove it with your considerations. Regards
Comment: $C^TD^{-1}C$ is non-negative definite. Result follows immediately.
Comment: @GordonSmyth . Do you mean that block $(A-BD^{-1}C)$ will be "smaller" than block $A$ ? , so the diagonal elements of $(A-BD^{-1}C)^{-1}$ will be "higher" than $A^{-1}$ (variance will be larger) . It is difficult for me to understand since I am reasoning on diagonal elements whereas I consider all the 4 blocks $A, C^{T}, D$ and $C$, so there are also covariance terms appearing when inversing initial Fisher matrix information $F$.
Comment: @GordonSmyth . If it doesn't bore you, could you do please a small answer but significant. Regards
Comment: Your statements that `a_11 = 1/sigma_1^2` etc are false. You cannot invert individual elements of $A$ like this to get individual variances. You must work with matrices. If you are not familiar with matrix concepts such as positive definiteness then the proof will not be accessible to you.
Comment: Without a detailled answer, this is sure I won't understand. At some point, we have to explain clearly the things instead of just writting a single sentence that is supposed to be understood by everyone. I need explicit operations, it seems the property "positive definite" is true for a vector $x$ such $x^{T}\,(C^{T}D^{-1}C\,x$ is positive. So must I conclude that for each line  of $y=C^{T}$, I will get $y^{T}\,D^{-1}\,y$ element which will be positive, but where does the increasing of constraints of block $A$ occur ? from $(A-C^{T}D^{-1}C)$ block or $((A-C^{T}D^{-1}C))^{-1}$ ?
Comment: I think that this article by [Wittman and Self (2021)](https://escholarship.org/content/qt81b3k4p7/qt81b3k4p7.pdf?t=qqtx5y) might be helpful. Wittman tends to be really good at explaining things. If nothing else you could probably look him up at UC Davis. If you want to laugh you could read about Wittman's hot dog and hot dog bun universe, by way of explaining the [Fisher Matrix for Beginners](http://wittman.physics.ucdavis.edu/Fisher-matrix-guide.pdf).
Comment: It is a bit difficult to see what you mean by 'all due to the three other blocks'. For a matrix of 2 by 2 the inverse of the block $a$ is $$\frac{d}{ad-bc}$$ Now, if $d$ increases, without $bc$ changing, then the inverse will approach $1/a$. So the $d$ does in some way influence the inverse but is this way what you are looking for?
Comment: yes, this is the way I think about it. If we consider for example bc positive, then the inverse is greater than $1/a$, so the constraints will be worse (larger values) than for the unmarginalised block $1/a$. But I woud like to get a rigorous demonstration in the general case, that is to say with 4 blocks of a matrix. By the way, it is intuitive to say oneself that if we have more parameters to constrain, the constraints will be less good that if we have less parameters : is it understable like this ?
Comment: Do you mean *"are the diagonal elements of $A^{-1}$ always smaller than $(A-C^TD^{-1}C)^{-1}$?"*.
Answer: We know that the inverse of the Fisher information is of the form:
$$F^{-1} = \left[
\begin{array}{cc}
A^{-1}+A^{-1}B(F/A)^{-1}CA^{-1}& ... \\
... & ...
\end{array}\right]$$
where $(F/A) = D - CA^{-1}B$ is the Schur complement of block $D$.
Let's show that diagonal elements of $A^{-1}+A^{-1}B(F/A)^{-1}CA^{-1}$ are bigger than the one of $A^{-1}$, which is equivalent to proving that the diagonal elements of the matrix $R = A^{-1}B(F/A)^{-1}CA^{-1}$ are positive.
Note $p$ the dimension of the upper left block.
We'll just proove that for all $e_i$, vector of the canonical basis of $\mathbb{R}^p$,
$$e_i^T R e_i \geq 0 .$$ Indeed, as $e_i^T R e_i = R_{ii}$, this will prove what we want.
First note that as $F$ is the Fisher information matrix, it is symmetrical and positive definite. So we get that:

$A$ is positive definite,
$B^T = C$,
Schur complements of $F$, $F/A$ and $F/D$, are symmetrical positive definite.

As $F/A$ is symetrical positive definite, its inverse $(F/A)^{-1}$ also is, and therefore there existe a symetrical definite matrix $Q$ such that $(F/A)^{-1} = Q^T Q$.
Using that, we can write $R$ as
$$R = A^{-1} C^T Q^T QCA^{-1} = \left(Q C A^{-1}\right)^T\left(QCA^{-1}\right)$$
Therefore $$e_i^T R e_i = (QCA^{-1}e_i)^T(QCA^{-1}e_i) = \lVert QCA^{-1}e_i\rVert_2 \geq 0. $$
Hence the result.
Hope this is useful.

Additional note : Proof that $F^{-1} = \left[
\begin{array}{cc}
A^{-1}+A^{-1}B(F/A)^{-1}CA^{-1}& ... \\
... & ...
\end{array}\right]$
Write $F$ as $$F = \left[
\begin{array}{cc}
A & B \\
C & D
\end{array}\right] =
\left[
\begin{array}{cc}
I_p & 0 \\
CA^{-1} & I_q
\end{array}\right]
\left[
\begin{array}{cc}
A & 0 \\
0 & D - C A^{-1} B
\end{array}\right]
\left[
\begin{array}{cc}
I_p & A^{-1}B \\
0   & I_q
\end{array}\right]$$
Such that
$$
F^{-1} =
\left[
\begin{array}{cc}
I_p & A^{-1}B \\
0   & I_q
\end{array}\right]^{-1}
\left[
\begin{array}{cc}
A & 0 \\
0 & D - C A^{-1} B
\end{array}\right]^{-1}
\left[
\begin{array}{cc}
I_p & 0 \\
CA^{-1} & I_q
\end{array}\right]^{-1}.
$$
It's easy to check that
$$\left[
\begin{array}{cc}
I_p & 0 \\
CA^{-1} & I_q
\end{array}\right]^{-1}=\left[
\begin{array}{cc}
I_p & 0 \\
-CA^{-1} & I_q
\end{array}\right]$$
and
$$\left[
\begin{array}{cc}
I_p & A^{-1}B \\
0 & I_q
\end{array}\right]^{-1}=\left[
\begin{array}{cc}
I_p & -A^{-1}B \\
0   & I_q
\end{array}\right]$$
and
$$\left[
\begin{array}{cc}
A & 0 \\
0 & D - CA^{-1}B
\end{array}\right]^{-1}=\left[
\begin{array}{cc}
A^{-1} & 0 \\
0   & (D - CA^{-1}B)^{-1}
\end{array}\right].$$
Therefore
$$
F^{-1} =
\left[
\begin{array}{cc}
I_p & -A^{-1}B \\
0   & I_q
\end{array}\right]
\left[
\begin{array}{cc}
A^{-1} & 0 \\
0 & (D - C A^{-1} B)^{-1}
\end{array}\right]
\left[
\begin{array}{cc}
I_p & 0 \\
-CA^{-1} & I_q
\end{array}\right] =
\left[
\begin{array}{cc}
A^{−1} + A^{−1}B (F/A)^{−1}CA^{-1} & −A^{−1}B(F/A)^{−1}\\
−(F/A)^{−1}CA^{−1} & (F/A)^{−1}
\end{array}\right]
$$
where $F/A = D - CA^{-1}B$ .
Comment: Thanks, I am going to get though it. Just a detail, a closed `$`are missing in (F/A)^{-1}.
Comment: Are you sure that your expression is correct when you write : $$F^{-1} = \left[
\begin{array}{cc}
A^{-1}+A^{-1}B(F/A)^{-1}CA^{-1}& ... \\
... & ...
\end{array}\right]$$

Isn't it rather for the first block : $$(A-BD^{-1}C)^{-1}$$ ?
Comment: I found this on the Wikipedia page of Schur's complement https://en.wikipedia.org/wiki/Schur_complement#Properties .
I guess then $(A - BD^{-1}C)^{-1} = A^{-1} + A^{-1} B (F/A)^{-1}C A^{-1}$...
Comment: Thanks. I understand the first expression below but not the development which allows to get the second expression of $M^{-1}$ :
Comment: $$
$$- In general, if $A$ is invertible, then
$$
\begin{aligned}
M &=\left[\begin{array}{ll}
A & B \\
C & D
\end{array}\right]=\left[\begin{array}{cc}
I_{p} & 0 \\
C A^{-1} & I_{q}
\end{array}\right]\left[\begin{array}{cc}
A & 0 \\
0 & D-C A^{-1} B
\end{array}\right]\left[\begin{array}{cc}
I_{p} & A^{-1} B \\
0 & I_{q}
\end{array}\right] \\
M^{-1} &=\left[\begin{array}{cc}
A^{-1}+A^{-1} B(M / A)^{-1} C A^{-1} & -A^{-1} B(M / A)^{-1} \\
& -(M / A)^{-1} C A^{-1} & (M / A)^{-1}
\end{array}\right]
\end{aligned}
$$
Could you help please to do the development to get $M^{-1}$ ?
Comment: @youpilat13
It's hard to write that in comments so I added a note to my answer.
But basically you just take the firs equality you wrote, and compute the inverse of all three matrices (inverses of block diagonal and block triangular matrices are easy to compute) and multiply them in the reverse order.
Comment: Thanks a lot for your patience. Best regards
Comment: I think there is a little error : we have to consider in the decomposition of $F$ the third block as :

$$\left[\begin{array}{cc}
I_{p} & A^{-1} B \\
0 & I_{q}
\end{array}\right]$$

instead of :

$$\left[\begin{array}{cc}
I_{p} & D^{-1} B \\
0 & I_{q}
\end{array}\right]$$
Comment: You're right. It's corrected.


using parameters in group by statment

Question: I just wanna do a simple query with grouping by "Age_Band".
And to set the parameter to help me change the grouping column easily.
But got an error:
"Each GROUP BY expression must contain at least one column that is not an outer reference. "
How did I make mistake on using the parameter? Thanks a lot
DECLARE @group nvarchar(50);
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
SET @SQLString =
    N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
 ,count(Loan_Amount)
 ,SUM(Loan_Amount) as Sum_Loan_Amount
 ,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
 ,Age_Band
 ,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
 ,GETDATE()as today
   FROM [dbo].[Loan]
   group by @groupcol';
SET @ParmDefinition = N'@groupcol nvarchar(50)';
SET @group=N'Age_Band'
exec  sp_executesql  @SQLString, @ParmDefinition,
                  @groupcol = @group;

Answer: You cannot use parameter in the group by clause by you can build query string using parameter. Something like this.
DECLARE @group nvarchar(50) = N'Age_Band'; --set col name
DECLARE @SQLString nvarchar(500);
SET @SQLString =
    N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
 ,count(Loan_Amount)
 ,SUM(Loan_Amount) as Sum_Loan_Amount
 ,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
 ,' + @group + '
 ,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
 ,GETDATE()as today
   FROM [dbo].[Loan]
   group by ' + @group;
exec  sp_executesql  @SQLString;

Comment: Yap, thank you very much. I revised my code and get it successfully run but no query result displayed. How can I get the result out? Thanks
Comment: Add `print @SQLString`. Try output as a query.

using parameters in group by statment


Are the coefficients in `lme4` correct with nested effects?

Question: The coefficients I'm seeing from a merMod model produced by lmer are not what I'd expect.  I made a reproducible example to illustrate.
I assumed that the Days coefficient reported for a nested effect (in this case, subject "308" within "Cohort1") would be the sum of the Days fixed effect plus the random effect coefficient for Days within Cohort and within Subject.
I can produce this coefficient myself by adding exactly this way (18.7) and confirm with predictions (18.7).  But the reported coefficient is different (21.15).
Am I interpreting something wrong?  Appreciate any help!
library(tidyverse)
library(lme4)

# add a categorical variable "Cohort" that Subject can be nested in
df <- sleepstudy %>%
  mutate(Cohort = if_else(
    as.numeric(as.character(Subject)) < 336,
    "Cohort1",
    "Cohort2"
  ))

# fit
sleep_model <- lmer(Reaction ~ Days + (Days | Cohort/Subject), df)
#> boundary (singular) fit: see help('isSingular')

# the report coef
coef(sleep_model)[["Subject:Cohort"]]["308:Cohort1", "Days"]
#> [1] 21.15208

# what I think the coef would be
fixef(sleep_model)["Days"] +
  ranef(sleep_model)[["Cohort"]]["Cohort1", "Days"] +
  ranef(sleep_model)[["Subject:Cohort"]]["308:Cohort1", "Days"]
#>     Days
#> 18.70102

# predict and divide delta y / delta x
predict(
  sleep_model,
  tibble(Cohort = "Cohort1", Subject = "308", Days = c(1, 2))
) %>%
  diff()
#>        2
#> 18.70102

Created on 2023-03-26 with reprex v2.0.2
Answer: coef() gives you the adjusted coefficients (fixed + random effects) for each random-effect term separately; the key thing to know here is that Cohort/Subject is counted as two separate random effect terms by the model. That is, (Days | Cohort/Subject) is internally expanded to (Days | Cohort) + (Days | Cohort:Subject), and dealt with thereafter (for ranef()/coef() purposes) as two separate terms, not as a combined term. So what you are getting when you ask for coef(sleep_model)[["Subject:Cohort"]]["308:Cohort1", "Days"] is indeed just the adjustment for the subject-by-cohort combination, not the combination of the cohort and subject effects.
I realize that may be a nuisance. It would be possible to augment/expand the coef method so that it collapsed these terms together (although a bit of a pain, as the fitted model object doesn't keep track of which RE terms were expanded from nested components in the original formula ...)
I think this should do what you want, provided the grouping variable names/levels within them are not pathologically set up so that grep() gets weird results.
object <- sleep_model
## nested terms to evaluate
nests <- c("Cohort", "Subject:Cohort")
ref <- ranef(object)
maxnest <- ref[nests][[length(nests)]] ## innermost nested RE
## start with FE, shape matching innermost RE
vals <- lapply(fixef(object), rep, nrow(maxnest))
vals <- data.frame(vals, check.names = FALSE)
rownames(vals) <- rownames(maxnest)
##
for (n in nests) {
    for (nm in rownames(ref[[n]])) {
        ## add relevant terms to running total (yikes)
        matches <- grep(nm, rownames(vals))
        vals[matches,] <- sweep(vals[matches,],
                 MARGIN = 2, ## columnwise
                 STATS = unlist(ref[[n]][nm,]), ## cond modes for this group
                 FUN = "+")
    }
}


Ideas on how to create a multi-part form, where the form requires completion/approval by another user

Question: Desired form submission workflow:

User A fills out a form, along with an email address for User B
User A submits the form, which then notifies User B by email of a request to complete and approve the form
User B clicks a link in the notification email and is able to complete (and approve) User A's submission

User B would actually be adding extra data to the form, not just "approving" it.
What are your ideas for ways to accomplish such a multi-part form? Are there any modules (besides webform) that could assist with this type of form logic? Would you base this on webform, or Drupal 7's forms API?
Answer: All you need is D7 forms API if you are comfortable writing PHP. There are several ways you could go about it. One assumes that the e-mail address of User B is the same e-mail they used to create their Drupal account. You'll need to store the result of User A's submission in a database somehow. Depends if you are already storing data from the DB or not. If not you can use variable_set() to store the e-mail address in one of Drupal's core tables and then variable_get() to retrieve it.
The idea is to save whatever user A stores to the DB after filling out the form. In your form definition, at the top check to see if that value is there. If so, you know user A has completed his part, next step is to check the user accessing this form. If their e-mail address matches the e-mail supplied during user A's part then you display user B's part of the form.
Comment: Thanks for your comment. I should probably have clarified that User B is actually an anonymous user, and not a drupal user, but your logic fits what I was thinking.
Comment: You probably don't want to do that with variable_set()/variable_get() it'd really be abusing that system. You should create a database table—or if you just need something temporary—a cache table.


Como acrescentar um caractere numa string, que já está dividida, a cada N caracteres?

Question: Preciso saber como separar, em quebras de linha, uma string a cada N caracteres. No entanto, antes de separar a cada N caracteres, elas já foram separadas a cada vírgula.

Quero que na saída essa separação seja quebra de linha.

Somente a vírgula é bem simples, basta um split(",").join("\n") que já resolve. Mas uma separação dentro de outra separação não consigo. Até penso em algumas soluções mas todas muito grandes, e para meu código preciso de algo simples.
Por exemplo, uma separação a cada 6 caracteres:
Entrada:
teste,testando,outro teste

Saída:
teste
testan
do
outro
teste

Answer: Para fazer a parte que falta pode utilizar uma regex, que seria o mais direto.
A regex seria:
/.{1,6}/g

Qualquer caratere (significado do .) com quantidade 1 a 6, aplicado de forma global (g). Quando usada com match vai lhe dar um array de resultados para cada 6 letras. De forma a ficar como mostrou basta fazer join("\n"), como tem no seu exemplo, que lhe vai dar um \n a cada 6 letras.
Então só a parte da aplicação da regex seria:
.match(/.{1,6}/g).join("\n")

O resto é a logica que já tem. Combinando tudo seria assim:

let texto = "teste,testando,outro teste";
let resultados = texto.split(",").map(t => t.match(/.{1,6}/g).join("\n"));

alert(resultados.join("\n"));

Primeiro divide pela ,, depois transforma cada resultado em conjuntos de 6 letras com a regex seguida de join. No fim mostra tudo junto com join("\n").
Documentação:

join
match
map


Is hook_boot() deprecated?

Question: I created a module in Drupal 7. Two years ago, that was working for me. Right now,  it is not working, as well as drupal_add_js(). It is also giving me an error when I implement hook_boot().
Is hook_boot() deprecated?
Answer: Deprecated? I suppose yes, technically, it was. hook_boot() was completely removed in Drupal 8, so you could take that to mean that it was deprecated in 7, even though it doesn't look like it was formally documented in the usual way (for example by adding @deprecated to the doc block in the system.api.php file).
However it was never, and won't ever be, removed from Drupal 7. Plenty of core and contributed modules are still using it just like they always have done. If your code is suddenly not working, check what else has changed that might be affecting it; hook_boot() hasn't gone anywhere.
Comment: When I use.
function zoomnow_init(){
  drupal_add_css(drupal_get_path('module', 'zoomnow') . '/zoomnow.css');
  drupal_add_js(drupal_get_path('module', 'zoomnow') . '/jquery.zoom.js');
  drupal_add_js(drupal_get_path('module', 'zoomnow') . '/zoomnow.js');

}
Its working for me..
Comment: When I use hook_boot its not initialing my css and js file.but after using hook_init its working form me. not getting.
Comment: Without knowing more about the code and how/where/what it's doing I can't really comment. I can only say that `hook_boot()` still exists, and is still invoked by Drupal during an early stage of its bootstrap. I have dozens of D7 sites running that use `hook_boot()` without issue
Comment: To add to that, deprecated functions would note that they are deprecated in their phpdoc comment.

Is hook_boot() deprecated?


Pagination for multiple query set from different models

Question: I'm trying to get data from multiple models from multiple serializers. and I got the response and data but what is happen it didn't gives me the "count", "next" , and "previous" keys to use it for pagination.
and I created a view as following:
views.py
class PlayerNotificationView(generics.GenericAPIView):
    def get_queryset(self):
        return

    def get(self, request, *args, **kwargs):
        activity_invitation_to_join = ActivityInvite.objects.filter(to_user=self.request.user,
                                                                active=True, status__in=('P', 'k',))
    team_invitation_to_join = TeamInvite.objects.filter(to_user=self.request.user, active=True,
                                                        status__in=('P', 'k',))
    team_player_left_team = TeamInvite.objects.filter(team__admin=self.request.user, active=True, status="L")
    activity_unread = ActivityInvite.objects.filter(to_user=self.request.user, read="False").count()
    team_unread = TeamInvite.objects.filter(to_user=self.request.user, read="False").count()
    total = activity_unread + team_unread
    un_read = [{'activity_unread': activity_unread,
                'team_unread': team_unread,
                'total': total}]

    context = [{

        "request": request,
    }]

    activity_serializer = MyActivityInviteSerializer(activity_invitation_to_join, many=True, context=context)
    team_serializer = MyTeamInviteSerializer(team_invitation_to_join, many=True, context=context)
    team_player_left_serializer = MyTeamInviteSerializer(team_player_left_team, many=True, context=context)

    un_sorted_queryset = activity_serializer.data + team_serializer.data + team_player_left_serializer.data

    from operator import itemgetter
    response = sorted(un_sorted_queryset, key=itemgetter('updated_date'), reverse=True) + un_read

    context = {
        "notifications": response,
    }
    return Response(context)

and it return response like this:
{
    "notifications": [
        {
.
.
.
}]}

and what i need exactly is paginate the result to be like this:
{
    "count": 2,

"next": next,

"previous": previous,

"notifications": [
    {.. }]}

}

So, how can I do this ?
Please any one can help me?
and if there any solution for this point in a different way to get data from multiple models and multiple serializers.
hope this is readable and clear to understand.
many thanks,
update
Solution
this update and solution to help any one faced same issue and he didn't get the answer
I did it like what "schillingt" said in answers as following:
class LimitPagination(MultipleModelLimitOffsetPagination):
    default_limit = 1

class PlayerNotificationView(FlatMultipleModelAPIView):
pagination_class = LimitPagination
add_model_type = True
sorting_fields = ['updated_date']

def get_querylist(self):

    activity_invitation_to_join = ActivityInvite.objects.filter(to_user=self.request.user,
                                                                active=True, status__in=('P', 'k',))
    team_invitation_to_join = TeamInvite.objects.filter(to_user=self.request.user, active=True,
                                                        status__in=('P', 'k',))
    team_player_left_team = TeamInvite.objects.filter(team__admin=self.request.user, active=True, status="L")

    # un_sorted_queryset = activity_serializer.data + team_serializer.data + team_player_left_serializer.data

    querylist = (
        {'queryset': activity_invitation_to_join.distinct(), 'serializer_class': MyActivityInviteSerializer},
        {'queryset': team_invitation_to_join.distinct(), 'serializer_class': MyTeamInviteSerializer},
        {'queryset': team_player_left_team.distinct(), 'serializer_class': MyTeamInviteSerializer},
    )

    return querylist

Answer: You need to instantiate a Pagination class and use that to generate the content. However, I would recommend using django-rest-multiple-models as it's a bit cleaner than what you would have to do. You'll need to override the method that filters down the queryset to limit it to the current user, but that should be relatively easy.
If you do decide to do it on your own, here is DRF's documentation on pagination.
Comment: Thank you for you answer, I did it for models without sorting results from all models together and it works fine , but I need to re-sort the results from all models based on created_date so maybe first dict from first table and the second one from second table and the third result from first table,

I cant get any thing in django rest multiple models talks about this.

can you guide me to do this?

many thanks
Comment: many thanks again ,,
I did it using reset multiple models with pagination and sorting...

many tanks
Comment: If you are looking into using cursor pagination which is more performant for querying larger tables, this library won't be a compatible solution.
Comment: Hey @Amirsalar, I am trying to implement cursor pagination on the nested objects of a Serializer on a ModelViewSet.

Essentially, a 1-to-many relationship between Post and Comments. When i query for posts, i would like to return paginated comments of a post in the serializer. i understand that regular pagination with limit and offset is a lot easier but i have a UI flow that i think only cursor pagination will be able to achieve.


How to make the following screen on iOS, which UI elements i need to use where?

Question: Screen contains 3 dynamic lists. Screen should be scrollable, but i know the total amount of the items in every list before displaying the UI (no need in infinite scroll)
Cats
 Cat1 image + Cat1 label
 ...
 CatN image + CatN label
 Button: ADD NEW CAT >

Dogs
 Textarea or button with description1
 ...
 Textarea or button with descriptionN
(No button to add a new dog)

Promocode
 Textarea or button with promo1
 ...
 Textarea or button with promoN
 (Button "+" ) + editText to input promo

Every 3 sections has unique differences in design.
Should i use 3 different collectionviews on this screen? should i add scrollview as the root? Please advice
Comment: What about a tableview/collection view with 3 sections and custom cells?
Comment: This questions feels like it would better fit in the UX exchange rather than stackoverflow.
Comment: It is about basic components to be used only. I am not allowed to change the UI/UX :(
Comment: i am not an expert in ios, so my main guess right now is
1) maybe i can split it all by 3 cells and use different cell identifiers
2) 3 different collectionviews but the question here will the usual scroll view as a root will be enough
Answer: I already answered in the comment but i'm gonna write down something a bit more complete here.
If you already have all the information you need (which should always be the case) before loading your view, then we're all set.
I suggest a scrollview either of tableview type or collectionview type.
You'd have 3 sections in them?
Since you need different cells (apparently) in each section, you could have 3 different custom cells.
When building your table/collectionview, you would check for the current section
(if tableview.section == 0) //(or 1 or 2)

and load the required cell at that point. Then fill it with relevant information.
To add your button at the end of each section you could have another custom cell that would only load if you're section X and at the last index. That's another inner if
//Inside every section code, you'd check if its the last element of the array.
if (indexPath.row == [yourArray count]-1)

And obviously in your "numberOfRowsInSection" you'd need to add that extra row :
 if (section == 0){
    return [yourArray count]+1;
}else if (section == 1){
  //... repeat for your section1 array
}

So you'd need 3 arrays, one for section 0, one for section 1 and one for section 2. The first one would hold all your cat objects, the second one your dogs, and so on.
Now that will work and maybe look good but I'm not an ios expert either.
Comment: a section is a section, its a property of the collectionview (or tableview)  by itself. I mean that you set the number of sections of the view to 3. NOT the number of items. The number of items (which is 18 for example) has to be set for each section. That's my last bit of code in the answer.
Comment: I would also make a total of 6 customs cells which I would load depending on where we are in the tableview/collectionview.
You'd have 6 cases, section 0 with all items, section 0 last item, section 1 all times, section 1 last item, section 2 all items, section 2 last item.
Comment: When you are saying "3 sections" do you mean
"set collectionview.items to 3?

The rest will be to put all elements for the section in it f.e. top label + (button + text) + "ADD NEW CAT >" and hide label and ADD button in regular cells draw?
Comment: How can i add section in the xcode? That is probably my main problem right now =) in Objective-C i can see numberOfItemsInSection or section in methods which i have to override
Comment: find a classic tableview/collection view tutorial with customs cells and another with sections. Anything on the internet can help you from there, I can't re-type a whole guide here ;)
Look at this for example :
http://www.appcoda.com/ios-programming-index-list-uitableview/

and this https://owenandrewsblog.wordpress.com/2012/01/29/uitableview-sections-tutorial/

You need to try them all and then you'll have learned how to use tableview. From there, you can make your own !


Calculating variance of poisson distributed random variable

Question: I am calculating variance of a Poisson distributed random variable with mean $\lambda$. I am doing it in the following way:
$\mathbb{V}(X) = \mathbb{E}(X^2) - \lambda^2 \\
= \sum_{x\geq 0} \quad x^2\frac{e^{-\lambda} \quad\lambda^x}{x!} - \lambda^2\\
= 0 + \lambda e^{-\lambda} + \sum_{x\geq 2} \quad x^2\frac{e^{-\lambda} \quad\lambda^x}{x!}-\lambda^2\\
= \lambda e^{-\lambda} + e^{-\lambda}\lambda^2\sum_{x\geq 2} \quad \frac{\lambda^{x-2}}{(x-2)!}\\
=\lambda e^{-\lambda} + \lambda^2 -\lambda^2\\
=\lambda e^{-\lambda}$
The answer is wrong. But I cannot understand what am I doing wrong in breaking the summation on line 3.
Edit: shown step 4 to answer a comment
Comment: Often times it's easier to start by finding $E[X(X-1)]$.  Also, please add the self-study tag, and I'll assist further.
Comment: Going from line 3 to line 4, you've assumed $x^2/x! = 1/(x - 2)!$ for $x \geq 2$, which is not true. Also, your $-\lambda^2$ term disappears on line 4 and then reappears on line 5.
Comment: How do you get that sum over $x \geq 2$ to be equal to $\lambda^2$?
Comment: I have added a step.
Comment: @Alex I totally missed that! The $\lambda^2$ is a typo though.
Answer: The Poisson distribution is one of those distributions that involves a factorial denominator.  This this type of distribution, the simplest way to find the raw and central moments is to first find the expected values of the falling factorials:
$$\mathbb{E}((X)_r) = \mathbb{E} \bigg( X(X-1) \cdots (X-r+1) \bigg) = \sum_{x=0}^\infty x(x-1) \cdots (x-r+1) \cdot \frac{\lambda^x}{x!} e^{-\lambda}.$$
Have a go at solving this infinite sum (it is relatively simple) and then you will have a general form for the expected value of the falling factorials of $X$.  These are all polynomials in $X$, so they can be used to find any of the raw moments or central moments by appropriate arithmetic.  In your particular case you want the variance, so you will want to look at the expected values of the falling factorials up to $r=2$.


Array map e funções assíncronas

Question: Estou usando a função getStaticProps do Next.js e Axios para pegar notícias do site Hacker News. Meu objetivo é acessar a API que retorna as principais histórias do dia (a qual retorna um id único dessas histórias) e depois pegar os primeiros cinco ids desse retorno e fazer um novo request pelo Axios para acessar o conteúdo delas. No final passo o conteúdo como props para o componente que vai renderizar as notícias.
O problema é que para pegar as primeiras cinco eu preciso usar map para acessar os resultados de forma assíncrona. O console.log no código retorna vazio justamente por causa do tempo do código. Já pesquisei alguns resultados usando Promise.all porém nenhum que se aplique a esse caso.
Então a pergunta é: Como faço para executar o processo descrito acima usando map assíncrono?
export async function getStaticProps() {
  const res = await axios.get('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
  const allData = await res.data

  let data = []

  allData.slice(0, 5).map(async function(story) {

    try {
      let itemRes = await axios.get(`https://hacker-news.firebaseio.com/v0/item/${story}.json?print=pretty`)
      const itemData = await itemRes.data

      data.push(itemData)

    } catch (e) {

      console.log(e)

    }

  })

  console.log(data)

  return {
    props: { data }
  }
}

Answer: Você está utilizando o map como forma de iterar sobre cada elemento do array. Vejamos seu código:
allData.slice(0, 5).map(async function(story) {
  // ...
  let itemRes = await axios.get('...')
  const itemData = await itemRes.data

  data.push(itemData)
  // ...
})

Note que o callback que você passou ao map não retorna nenhum valor. Portanto, o mapeamento  está sendo feito para undefined.
Você deve retornar o valor que deseja. Se quer montar um novo array diretamente, utilize um for normal (mas nesse caso não é o que você deseja).
Uma vez que você tenha um array de promessas (criado pelo mapeamento que retorna promessas explicitamente ou tem callback sendo função assíncrona), poderá utilizar Promise.all. Veja:
export async function getStaticProps() {
  const res = await axios.get('...');
  const allData = res.data;

  const promises = allData.slice(0, 5).map(async function (story) {
    const itemRes = await axios.get('...');
    return itemRes.data;
  });

  try {
    const data = await Promise.all(promises);

    return {
      props: { data }
    };
  } catch (error) {
    console.error(error);

    return {
      props: { data: null }
    };
  }
}

Note que eu fiz algumas modificações no código: adicionei ponto e vírgula e modifiquei o lugar do try-catch em razão do funcionamento de Promise.all — saiba mais aqui.
Observe também que o await em await res.data não é necessário, uma vez que data não é uma promessa.
Para maior aprofundamento, leia:

Função assíncrona.
Objeto Promise. E o método Promise.all.
Método map.
Comment: Obrigado pela edição e comentários. Porém quando você usou Promise.all() acho que esqueceu de adicionar promises como parâmetro. Adicionei no meu código e funcionou. Se puder verificar isso por favor.
Comment: É isso mesmo, perdão pelo erro! Já está editado. Obrigado. :) cc @Mateusqueiros

Array map e funções assíncronas


How to join two RDDs : value join is not a member of org.apache.spark.rdd.RDD[org.apache.spark.sql.Row]

Question: I'm using Spark 2.1.0 and Scala 2.10.6
When I try to do this :
val x = (avroRow1).join(flattened)

I get the error :
value join is not a member of org.apache.spark.rdd.RDD[org.apache.spark.sql.Row]

Why do I get this message? I have the following import statements :
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.rdd.RDD
import org.apache.spark.rdd.PairRDDFunctions

import org.apache.spark.sql._
import com.databricks.spark.avro._
import org.apache.spark.sql.functions.map
import org.apache.spark.sql.functions._
import org.apache.spark.sql.functions.col

This is my code :
 val avroRow = spark.read.avro(inputString).rdd
  val avroParsed = avroRow
    .map(x => new TRParser(x))
    .map((obj: TRParser) => {
      val tId = obj.source.trim
      var retVal: String = ""
      obj.ids
        .foreach((obj: TRUEntry) => {
          retVal += tId + "," + obj.uId.trim + ":"
        })
        retVal.dropRight(1)
    })

 val flattened = avroParsed
 .flatMap(x => x.split(":"))
 .map(y => ((y),1)).reduceByKey(_+_)  .map { case (a, b) => {
val Array(first, second) = a.split(",")
((first, second), b)
 }}.saveAsTextFile(outputString)

 val avroRow1 = spark.read.avro(inputString1).rdd
  val avroParsed1 = avroRow1
    .map(x => new TLParser(x))
    .map((obj: TLParser) => ((obj.source, obj.uid, obj.chmon))) .map { case (a, b, c) => ((a, b), c) }
    .saveAsTextFile(outputString1)

    val x = (avroParsed1).join(flattened)

UPDATE
This is my sample output for avroRow1 :
((p872301075,fb_100004351878884),37500)
((p162506011,fb_100006956538970),-200000)

This is my sample output for flattened :
((p872301075,fb_100004351878884),2)
(p162506011,fb_100006956538970),1)

This is the output I'm trying to get :
((p872301075,fb_100004351878884),37500,2)
(p162506011,fb_100006956538970),-200000,1)

Answer: join() operation is only available on PairedRDD.In your case it is not paired RDD. The reason being , you need a common key to join two RDDs but with generic RDD it is not possible. Try convert your  avroRow1 & flattened into (key,value) and then perform join.

A Resilient Distributed Dataset (RDD), the basic abstraction in Spark.
  Represents an immutable, partitioned collection of elements that can
  be operated on in parallel. This class contains the basic operations
  available on all RDDs, such as map, filter, and persist. In addition,
  org.apache.spark.rdd.PairRDDFunctions contains operations available
  only on RDDs of key-value pairs, such as groupByKey and join;
Answer: val avroRow1 = spark.read.avro(inputString1).rdd

Here you are converting a DF to rdd. You should convert avroRow1 to  (key,value) pair. Then apply join operation.
Answer: .saveAsTextFile(outputString) can cause problems because this changes the return type of the variables. Rather than saving as individual files before joining, the RDDs can persist() and the final output can be saved by .saveAsTextFile in this manner :-
 val flattened = avroParsed
 .flatMap(x => x.split(":"))
 .map(y => ((y),1)).reduceByKey(_+_)  .map { case (a, b) => {
val Array(first, second) = a.split(",")
((first, second), b)
}}

 val avroRow1 = spark.read.avro(inputString1).rdd
  val avroParsed1 = avroRow1
    .map(x => new TLParser(x))
    .map((obj: TLParser) => ((obj.source, obj.uid, obj.chmon))) .map { case (a, b, c) => ((a, b), c) }

val res = avroParsed1.join(flattened).saveAsTextFile(outputString1);


links between switches for iSCSI

Question: We inherited a SAN/vmWare/iSCSI setup with both Dell and HP equipment purchased for it, but not fully setup, and we need to get some additional switches to make it all work. But we're getting different feedback from the vendors on what's needed for the inter-links between the switches.
This is a diagram of what we believe we want to end up with -
http://www.gthomson.us/san-vmware-project2.jpg
ESXi 5.0 environment, running about 60 Windows VMs - will be adding more once further along.
For the most part, the left 2/3rds of the diagram is setup - HP servers for ESXi and HP P4000 Lefthand SAN. But currently there is just a single HP Procurve 2810g switch dedicated to 1gb iSCSI. We want to make that redundant on higher end switches.
We also have a Dell Equallogic PS6010E SAN and a couple Dell R900 servers. The Equallogic is 10gb iSCSI, and no switches were purchased to put it to use.
We'd like to have two realms
- one realm with 1gb iSCSI redundant switches, with the HP Lefthand SAN and HP servers
- one realm with 10gb iSCSI redundant switces, with the Dell Equallogic and Dell servers
And use one vCenter setup to manage and migrate systems between the two (1gb and 10gb) realms if/when it makes sense to.
When we migrate from one to the other, we want to migrate both the host and storage (i.e. would not be wanting the host on the 1gb side, and the storage on the 10gb side, or vice-versa.)
One vendor tells us none of the switches need interlinks for this all to work.
The other vendor tells us all the switches need to be interlinked for this to work.
From what I understand so far (and I'm very new to all of this, hence the diagram to help me understand what's happening and what's needed), on the 10gb side of things, the switches would need to be inter-linked because the Equallogic requires it.
On the 1gb side (left side of the diagram) do the two 1gb switches need to be interlinked for the HP Lefthand SAN side of things, or some other reason? My gut feeling tells me this inter-link isn't needed because the Lefthand SAN makes sure all data is written to at least two different physical devices, so the 'link redundancy' is actually handled in that way, rather than inter-links at the switch level.
Does there need to be inter-links between the 1gb side and the 10gb side at the switches, and if so, why? And how do those inter-links get done - each 1gb to each 10gb using the uplink ports on the 1gb going to regular ports on the 10gb?
My understanding was that vmotion, for both host migrations and storage migrations, would happen across the vmotion NICs, rather than across the iSCSI links. And if that's the case, why would the links directly between the 1gb and 10gb switches be needed for anything?
We don't have any goals of automatic failover from 1gb to 10gb side or vice-versa.
Comment: And I fear that #2 will be the bastard. I'm sure it can't be done - you can't vMotion between hosts if they don't have access to the same shared storage. Thus, there will need to be a link, and all hosts will need to have access to all storage : or else all of your migrations will have to be offline (not vMotion or svMotion.)
Comment: You actually have 2 questions here and they should probably be seperated: 1) Does LeftHand recommend/require inter-switch links, and 2) What are the networking requirements for vMotion between 2 ESXi clusters that don't share iSCSI storage?
Answer: The HP LeftHand implementation guides specifies links between the switches.
I have found that during high load, the links between the switches requires about 1 link per 2 nodes. Since you have 6 nodes, that would be 3 links for you. However, I tend to +1 when possible (to guard against port failure, allow for recabling without reduced performance, etc.) so 4 would be my final suggestion for you.
Comment: +1 My thoughts exactly (though I might add another link or two for "really safe", *4 ought to be enough for anybody*)
Answer: vMotion migrates the active state of the virtual machines, it does not migrate the virtual machine disks or configuration files (unless you're using storage vMotion to migrate the VM storage to another datastore). As such, the source and destination hosts need access to the virtual machine disks and configuration files, which is why shared storage is required to migrate a powered on virtual machine to another host.
What I see as a possible workaround would be to connect one host from each realm to the other realm's shared storage (rather than connecting each realm's switching infrastructure). This would then allow you to migrate virtual machines from one realm to the other using these two hosts as "placeholders". When migrating a VM you would migrate the VM first to the placeholder host and then perform a second migration to migrate the VM storage from the source realm datastore to the target realm datastore, both of which the placeholder hosts have access to. From there you can migrate the VM to any host in the target realm. Since each placeholder host has a connection to each realm's shared storage this should be do-able without powering down any of the VM's.
NOTE: I don't have an infrastructure like yours to test with so I'm merely visualizing how it might be done and I think this method might work.
Comment: Probably work - since he says they have no goal of "automatic failover" between realms, he probably isn't hoping for DRS between them.

links between switches for iSCSI


Ratio of two infinite cardinal numbers

Question: Suppose $G$ is the group of all functions between $[0,1]\to\mathbb{Z}$. Let $H$ be the subgroup defined as $H=\{f\in G: f(0)=0\}$. Then, what can be said about the cardinality of $H$ and its index in $G$?
I think the cardinality of $H=G=2^{c^2}$, where $c$ is the cardinality of the natural numbers. Hence, I think the index is countable. Am I right? Any hints ? Thanks beforehand.
Comment: How can you compose two functions $f : [0,1] \rightarrow \mathbb Z$ and $g : [0,1] \rightarrow \mathbb Z$ ? Your group doesn't seem well defined
Comment: I guess the group operation that would make the most sense is addition, do you agree?
Comment: @vidyarthi, $\mathfrak c$ is universally recognised as denoting [the cardinality of the _real_ numbers](https://en.wikipedia.org/wiki/Continuum_(set_theory)).
Comment: The standard symbol for the cardinality of the natural numbers is $\aleph_0$ (`\aleph_0`). But whatever you call it, squaring it leaves it unchanged. So $2^{\aleph_0^2}=2^{\aleph_0}$ (which equals $\mathfrak c$).
Comment: The group operation is likely $fg(x):=f(x)+g(x)$, or similar, as in a group ring.
Comment: $c$ is the cardinality of the natural numbers? Do you really mean that?
Comment: @TonyK why, you mean it is wrong?
Comment: @DodoDuQuercy  This is a question I saw in an exam. The question said the group of all maps and did not mention the group operation. What could be the group operation?
Comment: @TonyK but I wrote $c$ not  $\mathfrak{c}$!
Answer: Hint. Prove that $G/H\simeq\mathbb{Z}$ by exhibiting a surjective group morphism $G\to \mathbb{Z}$ with kernel $H$ (there is an obvious one).
Then deduce that $G/H$ has cardinality $\aleph_0$ ($c$, with your weird notation).
Comment: does this proof work:: we take cosets of $H $ in $G$. Now the cosets are exactly equal to $\mathbb{Z}$ depending on the value of $f(0)$. Hence the index is countable
Comment: I think a required morphism is $F(f)=f(0)$, right?
Comment: You are right :-)

Ratio of two infinite cardinal numbers


Passing user id argument to filter

Question: I have a view that lists the (ubercart) orders of a user. I created a view for that with a filter applied: "User: current". This works perfectly this way, I use this view in my profile page template like this:
$view = views_get_view('user_orders_custom');
$result = $view->execute_display('default', array($account->uid));

My problem is that when admin is inspecting the profile page of a user, this lists the orders of the admin, not the user being watched. Of course the passed $account->uid is not used by the applied views filter User:current.
I don't know how to make my view filter on the passed uid. I tried creating a relationship, arguments but the filter thing is not clear to me.
Comment: the question is still open, any help appreciated.. :-)
Answer: May be what you need is contextual filters, the user can go to view-name/% where % is a contextual filter for the uid
Comment: Not exactly, but thanks for the tip. I forgot to mention that I am using Drupal 6 where this module is not available afaik.
Comment: @jabal: oh, I am a bit of drupal 7 only. But I think [pathauto](http://drupal.org/project/pathauto) might help.
Answer: The solution is: removing filter User:current and adding argument (Order user) Ubercart order: User ID.

Passing user id argument to filter


Proving a set is positively invariant for a system

Question: I have the following system and set S:
$$x' = - y + x - x^3 - xy^2\\y' = y + x - y^3 - x^2y
\\\ S = \{(x, y) \in R^2 : x^2 + y^2 \leqslant \sqrt2 \}$$
I need to prove that for this system, the set S is positively invariant.
My first thought was to find a Lyapunov function.
However, all candidates I tried to use was't suitable to deduce anything.
I would be thankful for any help!
Answer: Your set $S$ is the closed, circular disc in $\mathbb R^2$ centered on the origin and with radius equal to $\sqrt[4]{2}$. The boundary of $S$ is the circle centered on the origin of radius $\sqrt[4]{2}$.
So, fixing a point $(x,y)$ on that circle, what you need to prove is that the vector $\langle x',y' \rangle$ is pointing inside the circle.
At the point $(x,y)$, the vector $\langle x,y \rangle$ is an outward normal of the circle. Therefore, $\langle x',y' \rangle$ points inside the circle if and only if the dot product with the outward normal is negative:
$$\langle x',y' \rangle \cdot \langle x,y \rangle < 0
$$
Substituting and simplifying:
\begin{align*}
(-y + x - x^3 - x y^2) x + (y + x - y^3 + x^2 y) y &= x^2 + y^2 - x^4 - 2 x^2 y^2 + y^4 \\
 &= \sqrt[4]{2} - (\sqrt[4]{2})^2 \\
 &< 0
\end{align*}
which finishes the proof.
One can express this in terms of Lyaponov functions, if one wants: $x^2 + y^2$ is a Lyaponov function, because $\langle x,y \rangle$ is equal to ($\frac{1}{2}$ times) the gradient of $x^2 + y^2$. Geometrically, the Lyaponov condition is just saying that the vector $\langle x',y'\rangle$ points inward along each circle $x^2 + y^2 = r^2$, which is exactly what my computations prove.


Power tower(infinite tetration)

Question: How to find the domain and range of
$Y=x^{x^{x^{x^{x^{...}}}}}=x^Y$
I know how to differentiate the function.
I don't know how to proceed further.
We should prove that domain:$[1/(e^e),e^{(1/e)}]$ and range:$[1/e,e]$
Answer: As you said:
$$y=x^y$$
and so:
$$\ln(y)=y\ln(x)$$
$$\ln(x)=\frac{\ln(y)}{y}\tag{1}$$
now if we take:
$$L_1=\lim_{y\to\infty}\frac{\ln(y)}{y}=\lim_{y\to\infty}\frac{1}{y}=0$$
If you mean for a given domain that is the range, we can work backwards from $(1)$ to get the domain from the range. Differentiating we get:
$$\frac1x=\left(\frac{1}{y^2}-\frac{\ln(y)}{y^2}\right)\frac{dy}{dx}$$
$$\frac{dy}{dx}=\frac{y^2}{x(1-\ln y)}$$
so our minimum/maximum will occur when $y=0$, but to work out $x$ you must evaluate:
$$x=\exp\left(\lim_{y\to0}\frac{\ln(y)}{y}\right)$$

Power tower(infinite tetration)


Does closed immersion induce surjection of global section

Question: Let $X$ be a projective scheme and $Y \subset X$ be a projective subscheme. Assume $X, Y$ are connected. Denote by $i:Y \hookrightarrow X$ the closed immersion. Is it always true that the induced morphism $H^0(\mathcal{O}_X) \to H^0(i_*\mathcal{O}_Y)$ surjective?
Comment: I suggest learning a very little  bit of algebraic geometry before asking this kind of question -- and please use mathstackexchange.
Answer: No. Let $X = P^1$ and $Y$ be a double point (locally given by the ideal $(x^2)$). Then $H^0(X,O_X) = k$ while $H^0(i_*O_Y) = k^2$.
Answer: If you are looking at varieties over an alg. closed field, the answer will be yes, since both $H^0$'s will just equal $k$.  But in general the answer is no.  Sasha gives a non-reduced example.  A reduced example is given by considering $Y  = V(X_0^2 + X_1^2) \hookrightarrow \mathbb P^1$, over $\mathbb Q$ (or any field that doesn't contain $\sqrt{-1}$).
Answer: Suppose $\mathcal{I}$ is the ideal sheaf of $\mathcal{O}_X$ that defines $Y$.That is, $i_*\mathcal{O}_Y=\mathcal{O}_X/\mathcal{I}$. Then we have a short exact sequence of sheaves
$$0\rightarrow\mathcal{I}\rightarrow\mathcal{O}_X\rightarrow i_*\mathcal{O}_Y\rightarrow0.$$
This gives us a long exact sequence of cohomology
$$0\rightarrow H^0(X,\mathcal{I})\rightarrow H^0(X,\mathcal{O}_X)\rightarrow H^0(X,i_*\mathcal{O}_Y)\rightarrow H^1(X,\mathcal{I})\rightarrow H^1(X,\mathcal{O}_X)\rightarrow\ldots.$$
Clearly, what you want is equivalent to the map $H^1(X,\mathcal{I})\rightarrow H^1(X,\mathcal{O}_X)$ being injective (thanks MB!), which is not necessarily true under the conditions you specified.
Comment: $H^1(X,I)=0$ is sufficient, but not necessary. An equivalent condition is that $H^1(X,I) \to H^1(X,\mathcal{O}_X)$ is injective.
Comment: Good point! I edited it.


sending string in sockets C?

Question: I am trying to send this string:
Server code:
char bash[256] = "grep 'usernama' data/*.txt | awk -F':' '{print $1}' | uniq";
char result[1000] = system(bash);
send(connected, result,strlen(result), 0);
fflush(stdout);

Error message:
error: array must be initialized with a brace-enclosed initializer

Issit possiible to send the grep result to the client in that way?
Comment: You seem to be missing a lot of code.
Comment: @ignacio: Can guide me to the codes?
Answer: system(3) returns you status of fork(2), but not stdout of forked program. Standard solution is using pipes:
char bash_cmd[256] = "grep 'usernama' data/*.txt | awk -F':' '{print $1}' | uniq":
char buffer[1000];
FILE *pipe;
int len;

pipe = popen(bash_cmd, "r");
if (pipe == NULL) {
    perror("pipe");
    exit(1);
}

fgets(buffer, sizeof(buffer), pipe);
len = strlen(bash_cmd);
bash_cmd[len-1] = '\0';

pclose(pipe);

Answer: system doesn't capture the output from the command it runs, so it isn't possible to do what you want that way.
If you look at the system man page you can see it returns int, the exit status of the command you run.
In order to capture the output of a process, you need to:

Find a library that does it for you.
Code up your own fork/exec with pipes implementation.
Redirect the output to a temporary file, then read that in. (From @unwind)

3 would be slightly simpler than 2, but would introduce security and reliability problems that wouldn't be present in 1 or 2.
Comment: So there is no direct and simple way to do it?
Comment: @origame: No simple way from C. Probably easier to either do it all from bash, or switch to a more high-level language such as python.
Answer: The easiest way to do this, if you're willing to call system() and run a shell, is probably to redirect the output to a file, then open the file, read its contents, and send that.
This of course opens up a bunch of problems (mainly race conditions and error handling), but it can perhaps be a bit simpler than just diving in and learning about fork() and exec().

sending string in sockets C?


Quotient spaces in linear algebra

Question: I'm having a bit of difficulty understanding what a quotient space is to a vector space $V$. I will present the part I'm finding trouble with below.
Let $V$ be a vector space and let $U$ be a sub space of $V$. We define an equivalence relation by setting $v\approx w$ if $v-w\in U$, the way I understand this is it means squishing the size of the sub-set $U$ to zero? The set of equivalence classes of this relation is denoted $V/U$, it is itself a vector space. The map from $V$ to $V/U$ is the projection $\pi$, such that $\pi:V\rightarrow V/U$.
$v$ is a class representative of $[v]$ the equivalence class. Lastly the dim$(V/U)=$dim$V-$dim$U$.
It is this last section I'm having trouble with. What is $[v]$, it is seemingly called the same thing as $V/U$ namely a equivalence class. So here are my questions;
1) what does it mean that $v$ and $w$ are linked by an equivalence relation?
2) what is the difference between $[v]$ and $V/U$?
Comment: are you assuming that $V$ is finite dimensional? to define quotient, you don't need this assumption. but for the dimension (the way you wrote) finiteness is required.
Answer: (1) An equivalence relation is a relation $\sim$ which satisfies the following conditions:
$$x \sim x \qquad \mbox{ for all } x \tag{reflexive}$$
$$x \sim y \iff y \sim x \tag{symmetric}$$
$$x \sim y \mbox{ and } y \sim z \implies x \sim z \tag{transitive}$$
If you replace $\sim$ with $=$, these three properties hold, so we might informally say that an equivalence relation is a relation which is 'like' equality.
In your case, $x \sim y \iff x-y \in U$, so saying $v$ and $w$ are linked by the equivalence relation $\sim$ means (geometrically) that if we consider the hyperplane $U+v$ of all vectors which have the form $u+v$ for $u \in U$, then $w$ is in this hyperplane.
(2) The equivalence class $[v]$ is the set of all vectors $w$ such that $v \sim w$.  In fact, $V/U$ is not an equivalence class: it is the vector space of all equivalence classes $[v]$, where $v \in V$.  To see why $V/U$ is a vector space define addition and scalar multiplication by
$$[v] + [w] = [v+w]$$
$$k[v] = [kv]$$
It is not entirely obvious that these operations are well defined: if $v' \in [v]$ (that is, if $v' \sim v$) and $w' \in [w]$, then $[v'] = [v]$ and $[w'] = [w]$, so we would need to show that $[v'+w'] = [v+w]$ and that $[kv'] = [kv]$ (that is, that the value of $[v] + [w]$ and $k[v]$ does not depend on the representative we choose for $[v]$ and $[w]$).  However, we can prove that if $v \sim v'$ and $w' \sim w$, then
$$kv' \sim kv$$
and
$$v'+w' \in v + w$$
(I'll leave the details to you.  Just work using the definition of $\sim$).  From this, we have that $[v'+w'] = [v+w]$ and $[kv'] = [kv]$ by transitivity.
Answer: On $V$ define the relation $v_1 \sim v_2$ if $v_1 - v_2 \in U.$ Then it is an equivalence relation on $V.$ An equivalence class (under this equivalence relation) is denoted by $[v]$ for some $v \in V.$ By definition, $[v] = \{w \in V |  v-w \in U \}.$ The set of all equivalence classes is denoted by $V/U.$ Then $V/U$ has a natural vector space structure induced from the vector space structure of $V$ itself.
$V/U = \{[v] | v \in V \}$ where we have the assumption (by construction) that $[v_1] = [v_2] \Leftrightarrow v_1 \sim v_2 \Leftrightarrow v _1 - v_2 \in U.$ The map $\pi : V \rightarrow V/U$ is defined by $v \mapsto [v].$ This is a linear transformation.
Answer: 1) Not a term, I have heard of, but in this case I think it simply means: $v \approx w$ or equivalently $v-w\in U$.
You can view an equivalence relation as a kind of "weak equality", since it behaves like equality, it is reflexive, transitive and symmetric, but $v \approx w$ follows from $v = w$, but not the other way around. Of course: $v \approx w \Leftrightarrow [v]=[w]$.
2) $[v]\in V/U$.  The set $[v]$ contains all $w\in V$ with $w\approx v$. The set $V/U$ contains all equivalence classes, that is sets of the form $[v]$ for every $v\in V$.
Specifially:
$$[v] = \{ w\in V : w\approx v\}$$
for all $v\in V$ and:
$$V/U = \{ S \subseteq V : \exists v\in V : S=[v]\} = \{[v] : v\in V \}$$

Quotient spaces in linear algebra


Obter dados de uma coluna no banco para uma váriavel

Question: Em uma parte do meu código tenho o tratamento de uma exceção que usa essa mensagem.
 //Grava log com sucesso da importação
fundo.registerLog(Resources.MensagemSucessoImportacao);

A mensagem fica dentro de um arquivo Resource, porém ela é concatenada.
Arquivo {0} importado com sucesso.

O {0} é onde ficará minha coluna da tabela do banco.
Minha classe não tem uma variável que pegue essa coluna.
Detalhe: Essa coluna vem de uma procedure:
 Database db = DatabaseFactory.CreateDatabase();
 DbCommand cmd = db.GetStoredProcCommand("PR_LOG");

 //Adds other parameters
 db.AddInParameter(cmd, "P_DESCRICAO_LOG", DbType.String, logDescription);

A estrutura acima fica em uma outra classe do projeto, dentro de um metódo.
Como faço pra pegar essa coluna, jogar numa variável e colocar essa variável após Resources.MensagemSucessoImportacao?
Answer: Se eu entendi, falta apenas usar String.Format():
fundo.registerLog(String.Format(Resources.MensagemSucessoImportacao, logDescription));

Comment: logDescription não existe no contexto de onde está a mensagem, como eu disse acima essa parte está em outra classe do projeto.
Comment: Não funcionou :(
Comment: @ThamiresCunha Qual seria o nome da variável que existe neste contexto, então? Pode por favor atualizar sua pergunta?
Comment: Como tbm citado acima, nesse contexto não tem uma variável que pegue essa coluna, eu teria que criar.. minha dúvida é como pegar essa possivel variavel que eu vou criar e conectar com essa coluna..
Comment: @ThamiresCunha Sem mais detalhes fica impossível responder.
Comment: Morrison Acho que não me expressei bem.. Gostaria de pegar o nome do arquivo e concatenar com a mensagem. Não tem colunas na tabela do banco que guardem o nome do arquivo.
Comment: gostaria que a mensagem ficasse ex.: Arquivo TESTE.txt importado com sucesso


Proofs of $\cos(x+y) = \cos x\cos y - \sin x \sin y$

Question: Define $\sin x $ and $\cos x$ via their infinite series:
$$
\sin x = \sum_n (-1)^{n}\frac{x^{2n+1}}{(2n+1)!}, \qquad
\cos x = \sum_n (-1)^n \frac{x^{2n}}{(2n)!}.
$$
Is there a short, clever proof that $\cos(x+y) = \cos x \cos y - \sin x \sin y$ for all real $x,y$?  I can prove it using product series, or by showing that both sides (with $y$ fixed) are solutions of $f''(x) = -f(x)$, $f(0) = \cos y$, $f'(0) = - \sin y$. Does anyone know other (preferably slick!) proofs?
Comment: I happen to have answered a [very similar question](http://math.stackexchange.com/questions/349143/how-do-we-find-specific-values-of-sin-and-cos-given-the-series-definition) today. You will find there in particular a proof of the two Addition Laws, rather condensed, using the series definition.
Comment: There's probably a proof involving complex numbers.
Comment: Not exactly what you want, but still, you might be interested in the [geometric proof](http://www.jimloy.com/geometry/trig.htm).
Comment: Allow me to clarify.  I'm wondering if there is a proof using real analytic methods (e.g. power series).  I'm not assuming anything about $\sin$ and $\cos$ other than what can be derived from their definitions as series.
Comment: [ProofWiki](http://www.proofwiki.org/wiki/Cosine_of_Sum/Geometric_Proof) features a geometric proof. As a PW herald, I'd like to invite any users to add their proofs (as far as they're different from the present quadruple) to it as well!
Comment: @AndréNicolas:  Beautiful!  Exactly what I wanted to see.  I'm not sure the proofs get simpler than that.
Comment: The diagram in [this answer](http://math.stackexchange.com/a/1103/409) links the series definition with the unit circle definition, and then [this diagram](http://math.stackexchange.com/a/1342/409) illustrates the identity.
Answer: One way is to use the fact that
$$\cos(\theta) = \dfrac{e^{i \theta}+e^{-i \theta}}2$$
$$\cos(x+y) = \dfrac{e^{i(x+y)}+e^{-i(x+y)}}2 = \left(\dfrac{e^{ix}+e^{-ix}}2 \right) \left(\dfrac{e^{iy}+e^{-iy}}2\right) - \left(\dfrac{e^{ix}-e^{-ix}}{2i} \right) \left(\dfrac{e^{iy}-e^{-iy}}{2i}\right)$$
Comment: Can $e^{\imath x}$ be defined without series? The proofs that $e^{\imath(x+y)} = e^{\imath x}e^{\imath y}$ seem to involve product series or uniqueness of ODE, which I'm seeing if I can avoid.
Comment: I don't believe it can. Are you looking for, say, an elementary geometry proof?
Comment: look at Mertens' theorem  http://en.wikipedia.org/wiki/Cauchy_product and you need only case when both series are absolutely convergent, which should be easier to prove. If I can remember right you will need that absolutely convergent series can be summed in any order.
Comment: @tom: I know the product series proof as stated in the question.  I'm looking for novel proofs.
Answer: New answer to an old question.  This one, maybe the slickiest of them all, is due to Erhard Schmidt.
Define
$$f(t)=\cos(x+y-t)\cos(t)-\sin(x+y-t)\sin(t).$$
  Verify $f'(t)=0$, hence $f$ is constant.  Now the desired angle sum identity follows from $f(0)=f(y)$
Answer: This was addressed in the question already. I leave it so that the method is fully explained.
LEMMA Let $f$ be a function with second derivative everywhere such that $f''+f=0$ and $f'(0)=0$; $f(0)=0$. Then $f$ is identically zero everywhere.
P We have that $$f''+f=0$$ Then $$f'f''+ff'=0$$ or $$(f')^2+f^2=C$$
But the initial conditions force $f'^2+f^2=0$ everywhere, which means $f\equiv 0$. $\blacktriangle$.
PROP Let $f$ be a function with second derivative everywhere such that $f''+f=0$, and $f'(0)=a$, $f(0)=b$. Then $$f=a\sin+b\cos $$
P Let $g=f-a\sin+b\cos$. Then $g''+g=0$ and $g'(0)=0$, $g(0)=0$. The lemma implies $g\equiv 0$, so that $f=a\sin+b\cos$. $\blacktriangle$.

Differentiate with respect to one variable and use the uniqueness of the solution of a second degree ODE with initial conditions.
That is, your cosine on the left vetifies $$f''+f=0$$ and $f'(0)=–\sin y$, $f''(0)=\cos y$. Then it must coincide with the unique solution $$f'(0) \sin+f(0)\cos$$
Comment: This solution was addressed in the question.
Comment: @UmbertoP. I just realized.
Answer: I always had a hard time to memorize that formula.
But actually, that's not really needed, because there it is an easy way to reconstruct it from the from the laws of exponentiation applied to complex exponentiation:
$$e^{i(x + y)} = e^{ix} \cdot e^{iy}.$$
Using the complex multiplication rule $\operatorname{Re}(ab) = \operatorname{Re}(a)\operatorname{Re}(b) - \operatorname{Im}(a)\operatorname{Im}(b)$, taking the real part gives
$$\operatorname{Re}(e^{i(x + y)}) = \operatorname{Re}(e^{ix})\operatorname{Re}(e^{iy}) - \operatorname{Im}(e^{ix})\operatorname{Im}(e^{iy}).$$
So by $\cos(x) = \operatorname{Re}(e^{ix})$ and $\sin(x) = \operatorname{Im}(e^{ix})$
$$\cos(x + y) = \cos(x)\cos(y) - \sin(x)\sin(y).$$
Answer: The way I learned it as a kid was geometric, and probably looked like the proof seen here  on Wikipedia.
The segment $OP$ has length $1$. We have the $\sin(\alpha + \beta) = PB = PR + RB = \cos(\alpha) \sin(\beta) + \sin(\alpha) \cos(\beta)$.
Then, to prove the cosine identity we can use that $\cos(\alpha + \beta) = \sin(\alpha + \beta + \pi/2)$ and use the sine identity.
Answer: Let $\vec{u},\vec{v}\in\mathbb{R}^2$ unitary vectors such that
$$
\vec{u}=\big(\cos(x),\sin(x)\big)\quad \mbox{ and } \quad \vec{v}=\big(\cos(-y),\sin(-y)\big)
$$
Here $x$ and $-y$ are the smallest angle formed between the x-axis and the vectors $\vec{u}$ and $\vec{v}$ respectively. Then
\begin{align}
\cos\big( x+y\big) = & \cos\big( x-(-y)\big)\\
= & \frac{\vec{u}\bullet\vec{v}}{\|\vec{u}\|\cdot \|\vec{v}\|} \\
= & \vec{u}\bullet\vec{v}\\
= & \cos(x)\cdot\cos(-y)+\sin(x)\cdot\sin(-y)\\
= & \cos(x)\cdot\cos(y)-\sin(x)\cdot\sin(y)\\
\end{align}
Answer: For variety, here is a different proof. Unfortunately it might be considered circular since it relies on differentiation of trig functions. But maybe you know their derivatives without using this identity, if say $\sin$ and $\cos$ have been defined by their Taylor series.
Apply $\frac{d^2}{dx^2}$ to each side (viewing $y$ as some constant), and you see that each side a solution to  $\frac{d^2}{dx^2}f(x)=-f(x)$
Both sides are in agreement at $x=-y$. Also the first derivatives of each side are in agreement at $x=-y$. Therefore they are the same expression.
Comment: That solution was mentioned in the question.
Answer: $$\begin{array} {rcl}
\cos(x + y) + i \sin(x + y)& = & e^{i(x + y)} \\
&=& e^{ix}e^{iy} \\
&=& (\cos(x) + i\sin(x))(\cos(y) + i\sin(y)) \\
&=& (\cos(x)\cos(y) - \sin(x)\sin(y)) + i(\sin(x)\cos(y) + \sin(y)\cos(x)) \\
\end{array}$$
Equating real and imaginary parts you get
$$\cos(x + y) = \cos(x)\cos(y) - \sin(x)\sin(y)$$
$$\sin(x + y) = \sin(x)\cos(y) + \sin(y)\cos(x)$$
Comment: Thanks for the answer - this question is nearly 6 years old. At the time I was interested in proving the trig angle-sum formulas using nothing but the series definition of sine and cosine. The issue is that the identity $\cos x + i \sin x = e^{ix}$ is outside the scope of the question, and the justification of the further identity $e^{w+z} = e^w e^z$ is requires tools that essentially prove what was being asked in the first place.
Answer: Suppose we know that $\sin(x+y) = \sin x \cos y + \cos x \sin y$, then we can do this to get a proof:
$\cos (x + y) \\ =  \sin (x + y + \frac{\pi}{2}) \\ = \sin x \cos (y + \frac{\pi}{2}) + \cos x \sin (y + \frac{\pi}{2}) \\ = \sin x (-\sin y) + \cos x \cos y \\ = \cos x \cos y - \sin x \sin y$
By the way, both have a geometric proof.


Append directive to body

Question: I have a popup directive, and I would like to compile and append it to body. Is there a simpler way then recompiling and appending directive to body.
 link: function (scope, element) {
     $('body').append($compile('html')(scope.new()))
  }

I don't want to compile the directive twice, first time automatically, and the second time manually. If there is a property or setting, that will automatically append the directive to body, that would be great.
Comment: Did you find a solution?
Answer: Why don't you put your custom directive in the right place within you page's html, and then use transclude to swap that with anything you put in the directive's template?
Comment: OK, whatever suits you best. Also, is this `$('body').append` jQuery? I don't think it's a good practice to use it like that with AngularJS. Good luck anyway, these were just my observations.
Comment: I am using angular.element.

Append directive to body


Relation between curvature of a curve and the curve formed after action of a orthogonal matrix on the curve

Question: Problem: Let $\gamma: [a,b] \to \mathbb{R}^2$ be a regular smooth curve and $A$ be a $2 \times 2$ orthogonal matrix. Let $\gamma_A: [a, b] \to \mathbb{R}^2$ be a regular smooth curve defined by $\gamma_A(t) := A(\gamma(t))$. Find the relation between the curvature $\kappa_{\gamma}(t)$ and $\kappa_{\gamma_A}(t)$ for $t \in [a, b]$.
My approach: Consider $\gamma_t = (x(t), y(t))$, then $\gamma_A (t) = (Ax(t), Ay(t))$. After applying the standard formula for curvature for plane curves for both $\gamma_t$ and $\gamma_A (t)$, we get:
$$
k_{\gamma}(t) = \frac{x'y'' - x''y'}{(x'^2 + y'^2)^{3/2}}
$$
and
$$
k_{\gamma_A}(t) = \frac{Ax'Ay'' - Ax''Ay'}{(A^2x'^2 + A^2y'^2)^{3/2}} = A^{-1}\left(\frac{x'y'' - x''y'}{(x'^2 + y'^2)^{3/2}}\right).
$$
Since $A$ is an orthogonal matrix, its inverse exists. Therefore, $k_{\gamma}(t) =  A^{-1}\cdot k_{\gamma_A}(t)$.
Is this correct?
Comment: What is $Ax(t)$?
Comment: The matrix A multiplied by a scalar since $t \in [a, b]$ which is a real number?
Comment: That's what you are doing wrong. You have to multiply $A$ to the vector $(x, y)'$ not individually by scalars.
Comment: Your formula makes no sense. Think about Frenet, not coordinate computations. The answer is that the signed curvature of $\gamma_A$ is $\det A$ times the signed curvature of $\gamma$ (at corresponding points).
Comment: How can I write $(\gamma_{A} (t))'$ in order to compute the tangent for applying Frenet?
Comment: I am not able to proceed @TonyPizza
Comment: @R_Squared remind me later after few hours. I will write an answer with explaination.
Answer: The first thing you are doing wrong is writing
$\gamma_A (t) = (Ax(t), Ay(t))$
$Ax(t)$ and $Ay(t)$ are matrices, right? So $(Ax(t), Ay(t))$ is actually a tuple of matrices not a tuple of points, so how does it represent a point in $\mathbb R^2$? If you know matrix multiplication then you would know that multiplying $m×n$ matrix to $n×k$ matrix gives you $m×k$ matrix. In your case you have to multiply $2×2$ matrix $A$ to a $2×1$ matrix which represents a point in $\mathbb R^2$ to get another $2×1$ matrix which is again a point in $\mathbb R^2$. So $A$ is transforming points in  $\mathbb R^2$ to points in  $\mathbb R^2$. Specifically, the point
$\gamma(t) = \begin{bmatrix} x(t)\\ y(t) \end{bmatrix}$
gets mapped to the point
$\gamma_A(t) = A\begin{bmatrix} x(t)\\ y(t) \end{bmatrix}$
In particular if $A = \begin{bmatrix}a & b\\ c & d\end{bmatrix} $ then
$\gamma_A(t) = \begin{bmatrix}a & b\\ c & d\end{bmatrix}\begin{bmatrix} x(t)\\ y(t) \end{bmatrix} = \begin{bmatrix} ax(t) + by(t) \\ cx(t) + dy(t)\end{bmatrix}$
So the point $(x(t), y(t))$ gets mapped to the point $(ax(t) + by(t), cx(t) + dy(t))$ and in effect the curve $\gamma(t)$ gets mapped to the curve $\gamma_A(t)$. Let's write
$\gamma_A(t) =  A\begin{bmatrix} x(t)\\ y(t) \end{bmatrix} =  \begin{bmatrix} X(t)\\ Y(t) \end{bmatrix} $
Hence the curvature of our new curve is
$\dfrac{X'Y'' - X''Y'}{(X'^2 + Y'^2)^{3/2}}$
To calculate this note that
(1)  $ X'Y'' - X''Y' = \det \begin{bmatrix} X' & X''\\ Y' & Y'' \end{bmatrix} $
(2) $\begin{bmatrix} X' \\ Y'\end{bmatrix} = A\begin{bmatrix} x'\\ y' \end{bmatrix}$
(3) $\begin{bmatrix} X'' \\ Y''\end{bmatrix} = A\begin{bmatrix} x''\\ y'' \end{bmatrix}$
(4) Combining (2) and (3) you get
$\begin{bmatrix} X' & X'' \\ Y' & Y''\end{bmatrix} = A\begin{bmatrix} x' & x'' \\ y' & y'' \end{bmatrix}$
Thus
$ \det \begin{bmatrix} X' & X''\\ Y' & Y'' \end{bmatrix} = \det \Bigg(A\begin{bmatrix} x' & x'' \\ y' & y'' \end{bmatrix}\Bigg) = \det A \cdot \det  \begin{bmatrix} x' & x'' \\ y' & y'' \end{bmatrix} $
(5) $X'^2 + Y'^2 = \begin{bmatrix} X' & Y' \end{bmatrix}\begin{bmatrix} X' \\ Y' \end{bmatrix} = \begin{bmatrix} x' & y' \end{bmatrix}A'A\begin{bmatrix} x' \\ y' \end{bmatrix}  $
Now just use properties of orthogonal matrices. First of all for orthogonal matrices we have $A^{-1} = A'$ so that $A'A = I$ in (5) which gives $X'^2 + Y'^2  = x'^2 + y'^2$. This along with (4) will give you $k_{\gamma_A}(t) = \det A \cdot k_{\gamma}(t)$. Further, for orthogonal matrices $\det A = ±1$ so the curvature either remains same or changes only upto a sign depending on whether $\det A = 1$ or $\det A = -1$.
Most of these of calculations wouldn'td be needed if you know how orthogonal transformations work. Basically they don't change the distance between points. So if $(x, y)$ goes to $(X, Y)$ the distance $|X - Y|$ still equals $|x - y|$. So the curves $\gamma(t)$ and $\gamma_A(t)$ will look exactly the same. The only possible difference will be their orientation. For example if you take mirror image of all points across $X$ axis then the curve will get mapped to its mirror image which will look same as original curve except for the orientation. The curvature of new curve will be negative of the original curve's curvature. Also you can see that mapping to mirror images across any line through origin doesn't change the distance between two points. So this transformation is orthogonal. Yes, not only orthogonal transformations preserve distance but any distance preserving linear transformation is orthogonal. I hope that explains. If you have doubt about how the formulas in (1) - (5) appeared then simply do the calculations and you will see they are true. If you want to know more about orthogonal matrices/transformations then you will find many things right here on mathstackexchange.
Answer: A regular curve can always be parametrized by arclength $s$.  Then the curvature of $\gamma(s)$ is by definition the norm (length) of $\gamma''(s)$.  Since an orthogonal matrix preserves the norm of vectors, it follows that the curve and its image under $A$ have the same curvature at the corresponding points.


Which is better way of injecting service to controller with __construct or $instance = parent::create($container)

Question: I'm always using this way of injecting service to controller:
<?php
namespace Drupal\TestModule\Controller;

    use Drupal\Core\Controller\ControllerBase;
    use Symfony\Component\DependencyInjection\ContainerInterface;

    class TestModuleController extends ControllerBase {

      protected $testModule;

        public function __construct(TestModule $testModule) {
        $this->testModule = $testModule;
      }

      public static function create(ContainerInterface $container) {
        return new static(
          $container->get('testModule.service')
        );
      }

      public function testModule() {
        return [
          '#type' => 'markup',
          '#markup' => $this->testModule->getTestModule(),
        ];
      }
    }

But with drupal console I generate Controller with service (drupal gcon command) and get different code:
<?php
    namespace Drupal\TestModule\Controller;

    use Drupal\Core\Controller\ControllerBase;
    use Symfony\Component\DependencyInjection\ContainerInterface;

    class TestModuleController extends ControllerBase {

      protected $testModule;

      public static function create(ContainerInterface $container) {
        $instance = parent::create($container);
        $instance->testModule = $container->get('testModule.service');
        return $instance;
      }

      public function testModule() {
        return [
          '#type' => 'markup',
          '#markup' => $this->testModule->getTestModule(),
        ];
      }
    }

Is this second way better than first and which should I use?
Answer: TL;DR: The second way is better.
The constructor method __construct() is considered internal, you can not (savely) overwrite it. E.g. the number or type of mandatory function parameters might change. Therefore the first version's code might break even within a minor update of Drupal core. Only the second version is guaranteed to work at least until the next major version release.
For more information I'd suggest reading this Change record from the Webform module.
Comment: Ah yeah, the CR is nice. I had this issue bookmarked: https://www.drupal.org/project/webform/issues/3067546
Comment: Here also an interesting read on this [Safely extending Drupal 8 plugin classes without fear of constructor changes](https://www.previousnext.com.au/blog/safely-extending-drupal-8-plugin-classes-without-fear-of-constructor-changes)


how to use "php include function" if the file from sumbit form?

Question: I understand the include function in php where the directory has been determined, like this:
include (dirname (__FILE__). '/file.php');

my question: can I use this function if the file from submit form?
my source code:
upload.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
</form>

process.php
<?php
include (dirname (__FILE__). '??????????');
?>

Bad english, sorry
Comment: You actually want to run a user uploaded file??? Dont do that
Comment: ok if you want this, where you store the file
Answer: If you really want to do this, you can do:
include $_FILES['file']['tmp_name'];

Uploaded files are not put in the same directory as the script, so you don't need dirname(__FILE). The tmp_name field contains the full pathname to the uploaded file.
Answer: One does not simply run a file uploaded by a user.
That being said, the details of the uploaded files are stored in the $_FILES array. The temporary name (and path) of the uploaded file is $_FILES['file']['tmp_name'].
You could either include this file directly:
include $_FILES['file']['tmp_name'];

Or, you could store this file first, using move_uploaded_file and then include that file:
$destination = "path/to/file.php";
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
include $destination;

Good luck!


how to find the nearest neighbor of a sparse vector

Question: I have about 500 vectors, each vector is a 1500-dimension vector, and almost every vector is very sparse-- I mean only about 30-70 dimension of the vector is not 0。
Now, the problem is that here is a given vetor, also 1500 dimension, and I need to compare it to the 500 vectors to find which of the 500 is the nearest one.(In euclidean distance).
There is no doubt that brute-force method is a solution, but I need to calculate the distance for 500 times, which takes a long time.
Yesterday I read an article "Object retrieval with large vocabularies and fast spatial matching", it says using inverted index will help:

But after my test, it made almost no sense, imagine a 1500-vector in which 50 of the dimension are not zero, when it comes to another one, they may always have the same dimension that are not zero. In other words, this algorithm can only rule out a little vectors, I still need to compare with many vectors left.
Thank you for your nice that you have read to here, my questions are:

Will this algorithm make sense?

Is there any other way to do what I want to do? Such as flann or Kd-TREE? But I want the exact accurate nearest neighbor, an approximate one is not enough.
Answer: An inverted index is really useful when you consider using a cosine distance, as you have to compute the dot product of say x and y which is simply:
$$
<x,y> = \sum_{i=0}^N x_i.y_i
$$
so you indeed only need to compare the document x to the one that have non-zero coordinates only when x_i != 0. I think your article was talking about that.
Unfortunately there's no such "easy trick" for euclidean distance that uses $$\|x-y\|^2 = <x-y,x-y> $$
instead. There are a lot of things to imagine if you need only an ANN but if you truly want the nearest one it can get ugly. Most of the ANN will give you the closest though - simplest is LSH for partitionning e.g., or LSH-forest.
Note also that KD-trees work great for small dimensions, but get close to linear as the dimension of the space increases, so you'll still get a brute force complexity. I should double-check but I remember a paper proving that partitionning tend to get linear as the dimension increases.
Comment: thank you for you answer!   you mean that in my condition I still have to use brute-force if I insist in getting an accurate nearest neighbor. I think maybe I should try PCA to do dimension reduction instead
Comment: Indeed, I cannot think of any exact method that would not use brute comparison, though some approximate really have impressive results (LSH-forest e.g.). PCA wouldn't really solve your problem because you would lose information reducing dimension, so even if you can find a good algorithm to get the closest point in the reduced space, it would still be an approximation of the closest one in the original space...


Definir MIME-type de um arquivo no Android

Question: Estou precisando descobrir dinamicamente qual o MIME-type de um arquivo. Inicialmente, preciso apenas identificar vídeos, mas pretendo usar isso para identificar páginas HTML, fotos, PDF etc.
Answer:
Informações extraídas e mineradas a partir desta resposta no SO internacional

Se você não tiver acesso direto ao arquivo (como, por exemplo, estar disponível via FTP ou via HTTP), você pode tentar resgatar o MIME-type pela extensão do arquivo. A classe android.webkit.MimeTypeMap tem exatamente o que se precisa para isso. Veja o método getMimeTypeFromExtension.
 public String getMimeType(Uri uri) {
    String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
}

Caso esteja com acesso local, pode-se tentar também usar o ContentResolver.getType.
public String getMimeType(Uri uri) {
    ContentResolver cr = getContentResolver();
    return cr.getType(uri);
}

Na documentação do getType não há menção de como ele faz a descoberta. Talvez seja pela extensão, talvez pelos números mágicos do arquivo, o que é uma detecção muito mais confiável do que pela simples extensão.
Como descobrir se o acesso é direto? Bem, podemos ver em qual scheme o conteúdo se encontra. Se for SCHEME_CONTENT, SCHEME_ANDROID_RESOURCE ou SCHEME_FILE, então é seguro considerar como local:
public boolean contentSchemeLocal(Uri uri) {
    String scheme = uri.getScheme();

    return scheme.equals(ContentResolver.SCHEME_FILE) ||
        scheme.equals(ContentResolver.SCHEME_ANDROID_RESOURCE) ||
        scheme.equals(ContentResolver.SCHEME_CONTENT);
}

public String getMimeType(Uri uri) {
    if (contentSchemaLocal(uri)) {
        ContentResolver cr = getContentResolver();
        return cr.getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
    }
}


How to use fetch multiple api using using getStaticProps in next js

Question: I have a [slug].js page where I'm using getStaticPath and getStaticProps to fetch the data and create static page{
export async function getStaticProps({ params }) {
    const { posts } = await hygraph.request(
        `
      query BlogPostPage($slug: String!){
        posts(where:{slug: $slug}){
            id
            slug
            title
            tags
        }
      }
    `,
        {
            slug: params.slug,
        }
    );

    return {
        props: {
            posts,
        },
    };
}
export async function getStaticPaths() {
    const { posts } = await hygraph.request(`
      {
        posts {
          slug
        }
      }
    `);

    return {
        paths: posts.map(({ slug }) => ({
            params: { slug },
        })),
        fallback: false,
    };
}

const Post = ({ posts }) => {
    return (
        <>

                <BlogPost posts={posts} />

                        <SuggesCard />

        </>
    )
}

There are two react components: BlogPost and SuggesCard, I am sending fetched posts content to BlogPost but now I want to fetch all the other post titles related to this fetched posts tag. so for this should i make another api call using getStaticPaths/getStaticProps or should I use a different approach?
Comment: Your question is a bit hard to follow. What happens for you to want to make another query? Does the user select something? Do you really need 2 queries or will a single one suffice?
Comment: i am making a blog website where i want to get tags of current open blog slug and then dipslay all the blog post related to this slug tags
Answer: There are many ways of solving this problem so expect some opinionated answers.
From what I understand of your question, you want to build a page that contains an individual post (identified by its slug) along with all other posts that have the same tag as the individual post.
Having the client make two queries feels slow and clumsy to me. The server should have everything it needs in the original slug.
I suggest creating a new query as follows:
postsWithRelatedPosts(where:{slug: String!}):[Post]

Then on the server return all the posts you are looking for. The server would first find the individual post, get its tags, then find all the related posts (excluding the original), concatenate and deduplicate the results, and return all the posts. If you don't want to create another type you could just use the convention that the post you found by slug is the first element in the return array. If that seems too clunky just go ahead and create a new type:
Type PostWithRelatedPost {
  post: Post
  relatedPosts: [Post]
}

and return that instead. This is more flexible since you can use a different set of fields for the related posts (perhaps you just want the date and title) than for the main post.


Rescale predictions of regression model fitted on scaled predictors

Question: Let's say I fit a model to data that has been standardized to z-score form:
#load data
data(cars)

#standardize variables so that they have mean 0 and st. dev 1
st.cars <- scale(cars)
st.cars <- as.data.frame(st.cars)

mod <- lm(speed ~ dist,data=st.cars)

I would like to make predictions using this model:
predict(mod,st.cars), however, I would like to get the predictions on the original scale of the dependent variable in the dataset.
Is there a way to re-scale the predictions to the original scale?
Answer: The scale function stores the scale and center values it uses to scale the data in an attribute. These can be used to convert predictions on the scaled data back to the original data scale.
# Scale cars data:
scars <- scale(cars)
# Save scaled attibutes:
scaleList <- list(scale = attr(scars, "scaled:scale"),
    center = attr(scars, "scaled:center"))
# scars is a matrix, make it a data frame like cars for modeling:
scars <- as.data.frame(scars)
smod <- lm(speed ~ dist, data = scars)
# Predictions on scaled data:
sp <- predict(smod, scars)
# Fit the same model to the original cars data:
omod <- lm(speed ~ dist, data = cars)
op <- predict(omod, cars)
# Convert scaled prediction to original data scale:
usp <- sp * scaleList$scale["speed"] + scaleList$center["speed"]
# Compare predictions:
all.equal(op, usp)

If you want to use the model to predict new data with the smod model object, you will need to scale the newdata values using the appropriate values from the scaleList object (do not call the scale function on the newdata directly).
Comment: R should include some automatic and way to reverse standardization on the output. Something working for different models (logistic, linear...) and for other statistics (Coefficients, Intercept...).
Answer: I have built on skaluzny's answer, if you want a more intuitive way to do this, without saving the scale attributes, but rather using knowledge of what the scale() function does by default (you really only need the last couple lines of this answer).
The scale function centers (subtracts mean value), and then scales (divides by standard deviation of data):
sdist <- scale(cars$dist)
head(sdist)

           [,1]
[1,] -1.5902596
[2,] -1.2798136
[3,] -1.5126481
[4,] -0.8141446
[5,] -1.0469791
[6,] -1.2798136

sdist2<-(cars$dist-mean(cars$dist))/sd(cars$dist)
head(sdist2)

[1] -1.5902596 -1.2798136 -1.5126481 -0.8141446 -1.0469791 -1.2798136
# Note this only is oriented the other way because scale() function outputs a matrix:

sdist2<-as.matrix(sdist2)
head(sdist2)
# The output now looks identical

           [,1]
[1,] -1.5902596
[2,] -1.2798136
[3,] -1.5126481
[4,] -0.8141446
[5,] -1.0469791
[6,] -1.2798136

So instead of storing things as a list, we can actually use the mean and standard deviation of the original data.
# Scale cars data:
scars <- scale(cars)

# Save scaled attibutes:
scaleList <- list(scale = attr(scars, "scaled:scale"),
                  center = attr(scars, "scaled:center"))

scaleList
$`scale`
    speed      dist
 5.287644 25.769377

$center
speed  dist
15.40 42.98

> sapply(cars,mean) # note that these values are the same as the `center` values above
speed  dist
15.40 42.98

> sapply(cars,sd)  # note that these values are the same as the `scale` values above
    speed      dist
 5.287644 25.769377

So now we can check if the predicted values would all be the same if we just use mean() and sd() rather than scale attributes:
# scars is a matrix, make it a data frame like cars for modeling:
scars <- as.data.frame(scars)
smod <- lm(speed ~ dist, data = scars)

# Predictions on scaled data:
sp <- predict(smod, scars)

# Fit the same model to the original cars data:
omod <- lm(speed ~ dist, data = cars)
op <- predict(omod, cars)

# Now the original answer was to use these stored attributes to modify the predictions:
usp1 <- sp * scaleList$scale["speed"] + scaleList$center["speed"]

# We can also simply use the standard deviation and mean from the original dataset:
usp2 <- sp * sd(cars$speed) + mean(cars$speed)

identical(usp1,usp2)
[1] TRUE

all.equal(op, usp1, usp2)
[1] TRUE

This might be faster / more efficient if you do it this way since there is no need to create extra dataframes / objects:
Mod <- lm(scale(speed) ~ scale(dist), data = cars) # add scale() function directly to model

Unscaled_Pred <- predict(Mod, cars) * sd(cars$speed) + mean(cars$speed)

all.equal(op, Unscaled_Pred)
[1] TRUE                      # predictions are the same as the model that was never scaled


Element-wise binary value concatenation of two matrices

Question: Element by element, I want to concatenate binary values from different matrices to one matrix.
For example,
|1 0 0|  |0 1 0|   |10 01 00|
|0 1 1|  |1 1 0| = |01 11 10|
|1 0 1|  |0 0 1|   |10 00 11|

How can this be done?
Comment: As far as I know, Matlab doesn't have the ability enter numbers in  numeric matrices using binary values. Matlab's logical matrix type only stores one bit binary, i.e. true and false. Your output matrix will either need to be numeric in which case it will be displayed in decimal or strings in which case you won't be able to use more math operations.
Comment: might help you: http://stackoverflow.com/questions/13347749/merge-two-binary-vectors
Answer: I would store the output matrix as a decimal matrix and convert to binary strings when accessing elements.
To concatenate the elements, treat each input matrix as a binary digit
A1 = [1 0 0; 0 1 1; 1 0 1];
A2 = [0 1 0; 1 1 0; 0 0 1];
output = A1 * 2^1 + A2 * 2^0;
output_str = arrayfun(@dec2bin, output, 'UniformOutput', false);

output will be a double matrix
[2,  1,  0;
 1,  3,  2;
 2,  0,  3]

output_str will be a cell array of strings
['10', '1',  '0';
 '1',  '11', '10';
 '10', '0',  '11']

Comment: @Michael Glad to be of help!
Comment: Also, if you don't mind you might have to add `'uni',0` to the end of `arrayfun` to avoid the error.
Answer: Here is one alternative without bin2dec or dec2bin conversion
out = arrayfun(@(x,y) strcat(num2str(x),num2str(y)),A1,A2,'Uni',0);

Input:
A1 = [1 0 0; 0 1 1; 1 0 1];
A2 = [0 1 0; 1 1 0; 0 0 1];

output:
>> out

out =

'10'    '01'    '00'
'01'    '11'    '10'
'10'    '00'    '11'

If you want it as numeric instead of string, you might do this:
outp = cellfun(@(x) str2double(x), out);

output:
>> outp

outp =

10     1     0
 1    11    10
10     0    11


Edge, Hover, and Click

Question: This is supposed to be a fly out menu that opens up when a user hovers.
This works perfectly fine within Chrome, I've tried this multiple ways (Using CSS :hover, (mousenter) and (mouseleave) the issue is - when using Edge, when hovering over my flyout menu and then clicking an item within the select box - the mouseout / mouseleave then gets triggered. (Or stop hover gets triggered) until the mouse is moved again.
This is very frustrating as obviously the mouse is still hovering the div and the div element should remained opened. Any ideas?
HTML:

    <select [(ngModel)]="selectedAccountNumber" size="20" multiple="false">
       <option *ngFor="let account of accounts" >
          {{account}}
        </option>
    </select>

CSS:
.flyoutmenu {
  z-index: 1000;
  display: block;
  position: absolute;
  left: 0px;
  top:0px;
  bottom:0px;
  margin-top:100px;
  margin-bottom:100px;
  width:40px;
  overflow: hidden;
  background-color: white;
  border: 5px solid gray;
  border-left: none;
  transition: 0.5s ease-in-out;

  select {
    width: 100%;
    min-height: 100%;
  }
}

// .flyoutmenu:hover {
//   width:300px!important;
//   transition: 0.5s ease-in-out;
// }

.flyoutmenuhover {
  width:300px;
  transition: 0.5s ease-in-out;
}

Partial TS:
public accounts = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6'];
public selectedAccountNumber = '';
public hoveringFlyOutMenu = false;

Comment: I've noticed, when adding `` to the div, and clicking on that element - the menu behaves correctly and stays open. So this appears to be some kind of edge compatibility bug with `` and the hover event on parent items.
Answer: I'm pretty sure this is some sort of bug with good ol' edge and there may be a workaround to get this to work correctly, but what I did in this case was removed the <select> and replaced it with an ngFor <button> then I stylized the button to look the same as the options would have.

Edge, Hover, and Click


Proving uniform convergence of $f_n(z)=\frac{4n\sqrt{nz}}{3+4n^2z}$

Question:
Study the convergence and uniform convergence of the functions $$f_n(z)=\frac{4n\sqrt{nz}}{3+4n^2z},\:z\in[\delta,+\infty],\delta>0$$.

$$\lim_{n\to\infty}\frac{4n\sqrt{nz}}{3+4n^2z}=\lim_{n\to\infty}\frac{4z^{\frac{1}{2}}}{\frac{3}{n^{\frac{1}{2}}}+4n^{\frac{1}{2}}z}=0$$
So the function converges pointwise to $0$.
For uniform convergence I did the following:
$|\frac{4n\sqrt{nz}}{3+4n^2z}-0|\leqslant\frac{4n\sqrt{nz}}{4n^2z}=\frac{1}{n^{\frac{1}{2}}z^{\frac{1}{2}}}=\frac{1}{n^{\frac{1}{2}}\delta^{\frac{1}{2}}}\to 0$ as $n\to\infty$
Questions:
Is this proof right? If not why? Which are the alternatives?
Thanks in advance!
Comment: Looks  ok to me. $\epsilon$ given, there is a $n_0$ (in terms of $\epsilon, \delta$) s.t. for $n \ge n_0 $: $|f_n(z)| < \epsilon.$
Comment: There seems to be a typo in the pointwise convergence part. Otherwise , the proof is fine.
Answer: Your proof seems correct to me. The general idea of uniform convergence is to show that you can find some expression independent of the choice of $z$ that converges to the required limit "at least as fast" as the sequence of functions. By using the boundary of the domain of the functions (the left boundary - $\delta$), you have found a sequence independent of $z$ that converges to $0$ - and so you have uniform convergence on the entire domain.