Field sharing between translations of a node?

Question: Assume I have a content type which I want to be translated to 5 languages! And assume that my content type has 10 fields, with 7 of them being some numbers and 3 of them are text.
There is absolutely no need for these 7 fields to be translated to each language. But when I translate each content I should spend a lot of time on filling same values for each language.
Answer: How about storing the 7 fields in a 1st content type and the 3 remaining fields in a 2nd content type. And then use the References module to connect them to each other? That way you'd only have to "translate" the content type with the 3 fields.
A variation of this could be using entities, whereas you'd then use the Entity Reference module instead. And probably also the Entity Translation module, for which quite some Community Documentation is available to get you started.
Drupal 7's new multilingual systems compilation contains an interesting set of posts about multilanguage websites ...
PS: You may also want to look at Node translation vs. Entity (field) translation for a lot of extra info/details about both variations of translations.
Comment: first thanks for your answer . I already had this idea in mind ! but I thought maybe it's a little hard for end user for data entry ! but I'm sure this works ! another idea which I'm thinking about is using entity translation module . but I haven't work with this module before !


Printf nao imprime dentro do while

Question: o objetivo do código é imprimir os valores, de listas ligadas.
  Exemplo de como é a lista:
   L->[3]->[4]->[5]->X,
deviria imprimir 3, 4, 5. No entanto nâo o faz.
typedef struct lligada {
    int valor;
    struct lligada *prox;
} *LInt;

LInt insereL (LInt l, int x){
    LInt new;
    new = malloc(sizeof(struct lligada));
    new->valor = x;
    new->prox = l;
    //printf("%d\n", new -> valor);
    return new;
}

void imprimeL (LInt l){
    while (l != NULL){
        printf("%d\n", l -> valor);
        l = l -> prox;
    }
}

int main(){
    LInt new;
    insereL(new, 5);
    insereL(new, 4);
    insereL(new, 3);
    imprimeL(new);
    //freeL(new);
    //puts("Hello World!");
    return EXIT_SUCCESS;
}

Comment: "deviria imprimir 10, 20, 30" - Como assim ? No seu código, você adicionou os valores 5, 4 e 3
Comment: Isac, esses valores era suposto ser só um exemplo, mas ja editei para perceber melhor.
Answer: As outras respostas já indicam qual o maior problema que tem, que é não utilizar o que é retornado na função insereL de forma a ligar a lista, no entanto, existe ainda outro problema que é utilizar o ponteiro LInt sem ser inicializado:
LInt new;
insereL(new, 5); //utilizar new sem estar inicializado

O que lhe vai potencialmente dar um segmentation fault na parte da impressão, pois a lista não vai acabar em NULL como seria suposto.
Para corrigir esses dois problemas precisa de alterar o main:
int main(){
    //iniciar com NULL que serve para o fim da lista, e que joga com a parte da impressão
    //quando faz while (l != NULL){
    LInt new = NULL;

    new = insereL(new, 5); //guarda resultado de novo em new, que é a nova cabeça da lista
    new = insereL(new, 4); //guarda neste tambem
    new = insereL(new, 3); //e neste
    imprimeL(new);

    return EXIT_SUCCESS;
}

Veja no Ideone como já funciona com essas altearções
Haveriam certamente outras recomendações a fazer, mas vou me resumir apenas a uma, mudar o nome da variável new, pelos seguintes motivos:

Todas as outras variáveis que tem estão escritas em português, logo esta deve estar também, dando assim mais coerência ao código. Um nome razoável seria novo, ou novo_no.
new é uma palavra reservada em c++, isso é visível pela cor especial que vê aqui dada à palavra. Isto significa que o seu código não só não é portável para C++ como dificulta a leitura a quem perceba c++.
Answer: O seu código não modifica a variável  Lint que recebe como primeiro parâmetro, você cria um elemento novo e retorna mas isso não é armazenado e por isso quando imprime a lista está vazia.
Answer: A função insereL não conecta os objetos criados, ou seja, quando na hora de imprimir você "anda" entre os objetos
l = l -> prox;

não está apontando para os objetos instanciados na função insereL.

Printf nao imprime dentro do while


How to execute purge command on Kusto SDK

Question: I'm trying to run purge command for testing purposes using Kusto C# SDK
I'm executing .show purges as I understand if I can execute this command then I also can execute other purge command
I've use the connection string with the ingest prefix (as in this answer https://github.com/Azure/azure-kusto-python/issues/165), yet I'm unable to use purge command
public AdxConnection()
{
    // https://ingest-mycluster.myregion.kusto.windows.net
    var connStringBuilder = new KustoConnectionStringBuilder(_connectionString)
        .WithAadApplicationKeyAuthentication(_clientId, _clientSecret, _tenantId);

    _adminProvider = KustoClientFactory.CreateCslAdminProvider(connStringBuilder);
}

public async Task Purge()
{
    var purgeCommand = CslCommandGenerator.GenerateShowPurgeCommand(_database);
    await _adminProvider.ExecuteControlCommandAsync(_database, purgeCommand);
}

Here is the response from Kusto
Syntax error: Query could not be parsed: {
    "error": {
        "code": "BadRequest_SyntaxError",
        "message": "Request is invalid and cannot be executed.",
        "@type": "Kusto.Data.Exceptions.SyntaxException",
        "@message": "Syntax error: Query could not be parsed: . Query: '.show database environment1 purge operations'",
        "@context": {
            "timestamp": "2020-02-21T11:04:52.4907001Z",
            "serviceAlias": "INGEST-DATAMTE",
            "machineName": "KDataMana000000",
            "processName": "Kusto.WinSvc.DM.Svc",
            "processId": 9420,
            "threadId": 4368,
            "appDomainName": "Kusto.WinSvc.DM.Svc.exe",
            "clientRequestId": "KD2RunCommand;7ee3cb62-5c82-4a6d-9885-bc56a2339a15",
            "activityId": "4058bf27-af5c-4bab-8d6f-c7c41473c89a",
            "subActivityId": "3689c292-91a6-4595-8e60-663a4a59a370",
            "activityType": "P.WCF.Service.ExecuteControlCommandInternal..IAdminClientServiceCommunicationContract",
            "parentActivityId": "1a9d19bf-15fe-4c43-a154-9e47e3fa7a26",
            "activityStack": "(Activity stack: CRID=KD2RunCommand;7ee3cb62-5c82-4a6d-9885-bc56a2339a15 ARID=4058bf27-af5c-4bab-8d6f-c7c41473c89a > DN.Admin.Client.ExecuteControlCommand/1a9d19bf-15fe-4c43-a154-9e47e3fa7a26 > P.WCF.Service.ExecuteControlCommandInternal..IAdminClientServiceCommunicationContract/3689c292-91a6-4595-8e60-663a4a59a370)"
        },
        "@permanent": true
    }
}. Query: '.show database environment1 purge operations'

*Edit:
Replacing GenerateShowPurgeCommand with GenerateDmPurgesShowCommand solve the problem. However, when running GenerateDmPurgeTableRecordsFirstPhase I've encounter another error
InternalServiceError (520-UnknownError): {
    "error": {
        "code": "Internal service error",
        "message": "Request aborted due to an internal service error.",
        "@type": "Kusto.Common.Svc.Exceptions.AdminCommandInvalidOperationException",
        "@message": "An admin command cannot be executed due to an invalid state: State='Operation PurgeTableRecords requires feature flag EnabledForPurge set on Engine'",
        "@context": {
            "timestamp": "2020-02-24T01:58:01.5764072Z",
            "serviceAlias": "INGEST-DATAMTE",
            "machineName": "KDataMana000000",
            "processName": "Kusto.WinSvc.DM.Svc",
            "processId": 5760,
            "threadId": 6100,
            "appDomainName": "Kusto.WinSvc.DM.Svc.exe",
            "clientRequestId": "KD2RunCommand;64439168-29e4-420e-b04a-07dccf11c5a4",
            "activityId": "855d59ba-3de2-44b4-9cac-62fbe5f7a5a3",
            "subActivityId": "5872fb41-7483-49bd-922c-1ae6104771fc",
            "activityType": "DM.MonitoredCommand",
            "parentActivityId": "c31fbc9a-8ae5-4cbf-9070-db5e39b8d5fa",
            "activityStack": "(Activity stack: CRID=KD2RunCommand;64439168-29e4-420e-b04a-07dccf11c5a4 ARID=855d59ba-3de2-44b4-9cac-62fbe5f7a5a3 > DN.Admin.Client.ExecuteControlCommand/bf23f2c3-d82b-4cf0-9f2b-0bfd32d55bc5 > P.WCF.Service.ExecuteControlCommandInternal..IAdminClientServiceCommunicationContract/c31fbc9a-8ae5-4cbf-9070-db5e39b8d5fa > DM.MonitoredCommand/5872fb41-7483-49bd-922c-1ae6104771fc)"
        },
        "@permanent": false
    }
}

Do I need to contact Kusto team to set EnabledForPurge to true, or I can do that using a command myself? This is not something I find in the docs.
Answer: The operation .show database environment1 purge operations is a command that should be executed on the "engine" cluster, meaning DATAMTE (and not ingest-DATAMTE) in your case.
In your case, you may find the following command on the "DM" (INGEST-DATAME) more useful: https://learn.microsoft.com/en-us/azure/kusto/concepts/data-purge#track-purge-operation-status
This command shows purge operation status by specifying the operation Id within the requested time period
Update answer for updated question: you need to contact Kusto to whitelist your cluster for purge.
Comment: Thanks @Ravid D, using DM command does help, but it didn't solve my problem entirely. I've updated my question, could you help me solve it?
Comment: Updated the response.


Mascarar CNPJ no firebird

Question: Estou precisando mascarar meu campo CPF / CNPJ direto no firebird, tentei o comando abaixo mas apresenta erro, será que alguém pode me ajudar?
UPDATE EMPRESA
SET EMP_CPF_CNPJ =
SUBSTRING(EMP_CPF_CNPJ from 1 for 2) + '.'
+ SUBSTRING(EMP_CPF_CNPJ from 3 for 3) + '.'
+ SUBSTRING(EMP_CPF_CNPJ from 6 for 3) + '/'
+ SUBSTRING(EMP_CPF_CNPJ from 9 for 4) + '-'
+ SUBSTRING(EMP_CPF_CNPJ from 13 for 2)

Comment: E porque você faria isto? O CNPJ é formado apenas por números, estes símbolos são usados para facilitar a leitura por humanos na apresentação, nada mais.
Comment: Precisei mudar no sistema para deixar a máscara fixa, só que os dados já cadastrados não aparecem no campos a mesmo que eles estejam mascarados
Comment: Acredito que a melhor tratativa nesse caso seja, após recuperar os dados do banco, aplicar a máscara através da sua aplicação, antes de promover a exibição dos dados.
Answer: No Firebird o símbolo de concatenação de Strings é o || e não o +, esse foi o erro.
UPDATE EMPRESA SET
  EMP_CPF_CNPJ = SUBSTRING(EMP_CPF_CNPJ from 1 for 2) || '.' ||
                 SUBSTRING(EMP_CPF_CNPJ from 3 for 3) || '.' ||
                 SUBSTRING(EMP_CPF_CNPJ from 6 for 3) || '/' ||
                 SUBSTRING(EMP_CPF_CNPJ from 9 for 4) || '-' ||
                 SUBSTRING(EMP_CPF_CNPJ from 13 for 2)

Mascarar CNPJ no firebird


Completely regular-Topology

Question: Prove that every metric space is a Tychonoff space.
Can somebody please help me to show this space satisfies the completely regular axiom and the $T_1$ axiom.
Comment: More generally, you can prove that a topological space is completely regular iff it admits a uniform structure compatible with its topology; here, the metric gives such a uniform structure.
Answer: According to Wikipedia, "$X$ is a Tychonoff space, ... if it is both completely regular and Hausdorff."
Every metric space is Hausdorff (but perhaps you might want to show that).
And, again according to Wikipedia, "$X$ is a completely regular space if given any closed set $F$ and any point $x$ that does not belong to $F$, then there is a continuous function $f$ from $X$ to the real line $\mathbb R$ such that $f(x)$ is $0$ and, for every $y$ in $F$, $f(y)$ is $1$."
Let $F \subset X$ be closed. Let $x_0 \in F^c $. Since $F^c$ is open there is $\varepsilon > 0$ such that $B(x_0, \varepsilon) \subset F^c$. Define $$ f(x) = \begin{cases} \frac{d(x,x_0)}{\varepsilon} & x \in B(x_0, \varepsilon) \\ 1 & x \in B(x_0, \varepsilon)^c \end{cases}$$
Then $f(x_0) = 0$ and $f\mid_F = 1$. Now show that $f$ is continuous.
Comment: @ccc Let's use that $d(.,.)$ is continuous in both arguments and that $1$ is also continuous. Then all we need to show is continuity at points $x$ such that $d(x,x_0) = \varepsilon$. Let $x$ be such a point. Then $x$ is in the closure of $B(x_0, \varepsilon)$ hence there is a sequence $x_n$ in $B(x_0, \varepsilon)$ converging to it, $x_n \to x$. Now since $d(.,.)$ is continuous, $d(x_0, x_n) \to d(x_0, x) = \varepsilon$.
Comment: @ Matt,can you please help me to show this function is continuous?
Comment: @Rudy There exist metric spaces and balls such that closure of an open ball is a proper subset of a closed ball. E.g. $\mathbb R^2 \backslash (-1,1) \times (-1,1)$ with the ball $B((1,0), 2)$. Its closure does not contain $(-1,0)$ but $B[(1,0), 2]$ does. So we don't know that $x$ is in the closure of $B(x_0, \epsilon)$. But actually it doesn't spoil your argument. If $x$ is a limit point, your argument is valid. If $x$ is not then in does not contains in $B(x_0, \epsilon)$ and has a neighborhood without points of $B(x_0, \epsilon)$. So the restriction of $f$ to that neighborhood is constant.
Answer: $T_1$: By the triangle inequality $\delta_p \colon X \to [0,\infty), x \mapsto d(p,x)$ is continuous and it is zero iff $x = p$. Therefore $\{p\} = \delta_p^{-1}\{0\}$ is closed.
$T_{3\frac{1}{2}}$: Let $A$ be closed and set $\delta_{A}(x) = \inf_{a \in A} d(x,a)$. Again the triangle inequality shows that $\delta_A$ is continuous. Moreover, $\delta_A(x) = 0$ iff $x \in A$, so if $p \notin A$ the function $\frac{\delta_A}{\delta_{A}(p)}$ is zero on $A$ and $1$ on $p$.
Comment: If you see this, please try to register your account. It was just pointed out to me that your account has fragmented into 6 or 7. Registering would help prevent that. I've merged the fragments into this one.
Answer: Every metric space is normal Hausdorff, hence for any two disjoint nonempty closed sets $A$ and $B$, there is a function that sends $A$ to $0$ and $B$ to $1$. This is true if $A$ is a singleton, so the space is Tychonoff.

Completely regular-Topology


Statistical comparison of two means with a range not starting at 0

Question: I don't know the exact term for this, so googling didn't work. I will explain exactly what I need below.
I want to compare two sets of values such as blood sugar or blood pressure, where the values never start at 0. Please consider the example below:
Update
I compared the duration of motor block after spinal anesthesia. The results are not distributed normally:
Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
75.0   140.0   160.0   157.2   175.8   280.0
90.0   166.2   190.0   193.3   210.0   295.0
And Wilcoxon rank sum test with continuity correction resulted in W = 622.5, p-value = 1.475e-05.
So, is there any special concerns for comparing these groups aside from applying t-test or Mann-Whitney-U, regarding the fact that legal range does not start at 0?
@Peter Flom
Well, after reading your last comment, I tried it on R and saw that the two p values are the same:

tension1<-c(160,180,170,150,145,176,198,200)
deviation1<-c(20,40,30,10,5,36,58,60)
tension2<-tension1+12;deviation2<-deviation1+12
ks.test(tension1,tension2)

Two-sample Kolmogorov-Smirnov test
data:  dev1 and dev2
D = 0.375, p-value = 0.6601
alternative hypothesis: two-sided

t.test(tension1,tension2)

Welch Two Sample t-test
data:  tension1 and tension2
t = -1.1792, df = 14, p-value = 0.258

t.test(deviation1,deviation2)

Welch Two Sample t-test
data:  deviation1 and deviation2
t = -1.1792, df = 14, p-value = 0.258
Comment: No, not that the *means* are similar, but that the *variances* are. Although, when means are very far apart, variances are likely to differ; but the you can use e.g. Satterthwaite to fix that.
Comment: I think for a t-test, the fact that the range starts at 0 or another value is not really important. What is important, however is that the mean of the two sequences are "similar" (how much is too much is somewhat open to interpretation) and that the data is normally distributed. For the Mann-Whitney U, because it is non parametric, you can use it on not normally distributed data.
Answer: As far as I know, there is no test of difference in location (e.g. median, mean etc) that depends on either distribution having 0 as part of it. Certainly not t-test or Wilcoxon signed ranks or Mood's median test or bootstrapping.
Comment: Can we say that it is better to compare the deviations from baseline in such cases to negate the effect of distance to 0? As an example, say the blood pressures deviated by 30% in one group, and only 15% in the other, instead of comparing the mean of measured blood pressure levels.
Comment: It is not necessary to do this.  There is no "effect of distance to 0" to negate. Blood pressure is not, as far as I know, measured in "deviation" but in some unit of pressure. You can compare the central tendencies in whatever units you've got.
Answer: The t-test is apt here. There is no dependency on the range involving zero. So long as $t = \frac{\delta \mu}{s}$ is within range (decided by the chosen p-value) for the given number of degrees of freedom you cannot reject the null hypothesis that the means are equal
Comment: I see the point. However, since you answered so specifically about parametric comparison, and my data is non parametric, does the case  "There is no dependency on the range involving zero" apply to non parametric data, too?


Set builder notation alternatives even number

Question: I'm trying to understand set builder notation, I was wondering what the difference (if any) is between:
$$
A = \lbrace k \; \vert \; \exists n \colon ( n \in \mathbb{N} \; \wedge k = 2n ) \rbrace
$$
and:
$$
B = \lbrace n \; \vert \; ( n,p \in \mathbb{N} \; \wedge n = 2p ) \rbrace
$$
Both these set should contain all the positive even numbers. I also assume that both notations are correct.
Comment: The first is correct. The second makes no sense to me (where are the quantors?).
Comment: The second notation is not correct because $p$ is not quantified. The formula $n,p\in\mathbb{N} \wedge n=2p$ is neither true nor false for any $n \in \mathbb{N}$.
Answer: $A$ is indeed the set of even integers.
$B$ is a bit bizarre. It is not the set of all even integers. $p$ is not bound, so If it didn't say "$p\in \Bbb N$" then we could give the definition the benefit of the doubt, and regard $p$ as a parameter. Assuming that $p$ is an integer, $B = \{2p\}$. In fact, even as written, we might still regard $p$ as a parameter, and then:
$$
B = \begin{cases}
\{2p\}&\text{if $p\in \Bbb N$,}\\
\emptyset&\text{if $p\notin \Bbb N$.}\\
\end{cases}
$$
But this is very contrived: too little benefit, too much doubt. If someone wanted to define such a set $B$, in practice they wouldn't write it this way.
Comment: I think I am beginning to understand it, in $A$ the part $\exists n \colon$ binds $n$ making the whole term a predicate. In $B$ the term is not a predicate and as such cannot be used to create a set. Is this interpretation correct? (I apologize if I am imprecise, I'm a computer guy trying to learn set theory)
Comment: No, that's not quite right. In the definition of $A$, the predicate following $\mid$ has one free variable, $k$, so it "is" or specifies a 1-ary predicate $P(k)$. In turn, the set-builder binds this variable $k$, and $A$ consists of all $k$ such that $P(k)$. In the definition of $B$, the formula following $\mid$ has two free variables, $n$ and $p$, and specifies a binary predicate $R(n,p)$. The set builder binds only $n$, and $B$ consists of all $n$ such that $R(n,p)$, *whatever $p$ is*.
Comment: The older name for "set-builder notation" is "set comprehension". Do you know Python? "comprehensions" in Python (list comprehensions, dict comprehensions, generator expressions, ...) are inspired by set comprehensions in set theory.
Comment: Again, though, nobody would write that definition of $B$. Although it's syntactically legal, it's weird for reasons indicated, almost certainly a mistake. If the intention is to define the even ints, then obviously it *is* a mistake.
Comment: Thank you very much for the explanation, indeed, I've stumbled upon set-builder because of sequence expressions in F#. The main difference is that in F# (and Python) "what goes in" and "what comes out" is in a more familiar notation. It was hard to understand that even though, $\exists n \; so \; that \; ...$ is just a predicate and there is no $n$ being "injected" to test this $\Phi(n)$ on, this statement describes a set. I will need a few more hours to really understand all of your words, just know I'm really grateful that you took the time to help out a beginner with patience!
Comment: You're very welcome, I'm glad I could help.


How we can select the best number of auto-regressive terms in a time series model to avoid over-fitting

Question: To find the best neural network auto regressive model for forecasting future values of a series with 180 month of observation I plotted ACF and PACF of series as follows Using Forecast package in R.

From PACF plot I decided to have 2 non- seasonal (p=2) and 3 seasonal (P=3) terms in my model using nnatar(p,P) function. Fitted values versus observed (R2=0.56) and also forecasted values for next 12 month with CI 80% and 95% are presented in following figure.

I intentionally without any logic increased the non-seasonal terms from 2 to 10 only to compare results with former model. The produced plot in this case is as follows which show the fitted values very better fitted on observed values (R2=0.99) and confidence interval for forecasted values is also pretty narrow.

My question is if selection of the number of the model predictors (seasonal and non-seasonal) should be based  on PACF plot, how we can judge to select the best  model while increasing the input lags will increase the model R2.  I am worry about model over-fitting in second model. I am sure the behavior of my series could not be completely described by its lags. Thus certainly there may be some other exogenous variable that may have an influential effect on this series but in this model I only want to consider series lags effect. Thus I think the first model may be better selection because it described only 56% of variance but the second 99% which is not reliable!
However, I am not sure about this my selection…. Please help me know what cases is better.
Comment: how did you calculate R2 by using nnetar function?
Answer: Before fitting a nnetar() model you might try the following:

Is the series homoscedastic? If unsure, try with option lambda="auto" to automatically select the transformation is required to stabilise the variance.
Fit auto.arima() (with and without lambda inside this function) to detect both seasonal and non-seasonal AR. Then use that in the nnetar() model.
Both nnetar() and auto.arima() has options to include exogenous series through xreg option. Might be helpful to fit models with and without this option to evaluate both point forecasts and prediction intervals.
Instead of fitting one single model, you might also think of fitting several models on sliding window to figure out whether one particular model is better in terms of fitting (AIC/BIC) and  in terms of forecasting (MSE/MAPE etc.)

Hope this helps!


How many teams go through from each group in Euro 2016?

Question: I just noticed that there are 6 groups in the current European Championships, which means that - if the top two from each group were to go through - there would only be 12 teams into the last 16, which is 4 short.
However, if the top 3 from each group go through, we get 18 teams going to the round of 16, which is 2 too many.
There would have to be just 4 groups where 3 teams go through and 2 groups where the top 2 go through to make 16 teams in the round of 16.
How is it working?
Are there 4 groups where 3 teams go through? If so, how do they decide which groups?
Answer: 16 teams will progress to the knockout stages of Euro 2016 from the group stages. The top two sides from each group will qualify, followed by 4 of the 6 third-placed team in the group.
The Wikipedia article for Euro 2016 explicitly explains the qualification process for the knockout stages. I have added an excerpt here for your benefit, emphasis mine.

To accommodate the expansion from a 16 team finals tournament to 24 teams, the format will be changed from that used in 2012 with the addition of two extra groups in the group stage, and an extra round in the knockout stages. The six groups (A to F) would still contain four teams each, with the top two from each group still going through to the knockout stage. In the new format however, the four best third-ranked sides would also progress, leaving 16 teams going into the new round of 16 knockout stage, ahead of the usual quarter-finals, semi-finals and final, and only 8 teams going out at the group stage. The format is exactly the one which was applied to the 1986, 1990 and 1994 FIFA World Cups, with the exception of the absence of a third-place play-off.

There is also a handy table in the Wikipedia article which shows how the third-placed teams are ranked currently.
Answer: Euro 2016 is open to 24 teams while since 2012 was to 16 when the firsts and the seconds teams qualify for the knockout rounds.
This expansion required a modification to the first round of the qualification system and those are the criteria for the qualification:
<code>1. Points
2. Goal difference
3. Goals scored
4. Fair play (3 pts for a red card, 1 pt for a yellow, lowest score wins)
5. UEFA team coefficient
</code>
Here you can find a detailed article
The four best third teams will play knockout against the winner of the groups A-B-C-D


Creating PDF document from Word document using java api

Question: In one of my requirement I have to create a PDF from word document such that
1) There will be a page number on every page.
2) There will be line number for every line, starting from line no as 1 for each page.
Our application is written in java so Java API will be more helpful. But if it is more convenient in any other language that will be OK.
Comment: What will the word document contain?  How perfect must the PDF be?
Answer: Here is a link to the most common Java PDF API :)
http://java-source.net/open-source/pdf-libraries
IText is the most famous one, This is the link for IText
http://itextpdf.com/
I hope that I helped :)
Answer: Since word file cant be read like a .txt file , you will need 2 APIs.
One to read data from the doc file and another to write that data into pdf file.
Now to read data from the doc file you can use APACHE-POI.
and to write that data into pdf file you can use ITEXT.
Answer: You could try docx4j, although you would need to make a minor enhancement to support line numbering on every line, and possibly more problematically, probably use a commercial XSL FO processor.
docx4j uses XSL FO for PDF output, and line numbering isn't part of the 1.0 spec. (It is part of the XSL 2.0 requirements spec)
This means you'd have to use a XSL FO processor which supports a vendor-specific extension, for example Antenna House
UPDATE 2016 04
From v3.3.0, docx4j defaults to using our commercial converter, which you can try at http://converter-eval.plutext.com/
Answer: I  suggest JODReports or Docmosis since you want to start with a word document.  You can dynamically insert numbered records and page breaks from a Java api so it sounds like they will be able to meet your requirements.
You haven't indicated why you want to start with a word document.  If you are strictly generating a document, you could possibly drop that requirement and use iText or docx4j.
Comment: We are creating editorial management system and asking author to submit their script...for this requirement what do you think will be a better document format that we can use?
Comment: If authors are sending you their scripts, what does that have to do with "a number for every line".  Are you changing the document they send you by adding numbers for each line?
Comment: Actually when i will send this document to Reviewer he will review it and give his feedback with respect to line no and page no.
Answer: You can use Apache FOP(http://xmlgraphics.apache.org/fop/) only one thing I see last update on Oct 2012 for 1.1 release. But still issue are open.


Why is the value of "$?" changed in the "if" condition?

Question: I'm confused by the the value of "$?" in my shell script. I wrote a demo script as follows:
#!/bin/bash
echo "good"
if [ $? -ne 0 ];then
  echo "$? not equal 0"
else
  echo "$? equal 0"
fi

echo "good"
ret=$?
if [ $ret -ne 0 ];then
  echo "$ret not equal 0"
else
  echo "$ret equal 0"
fi

I know,"$?" is used to save the return value of the last function or command, but why is the output as below?
good
1 equal 0

good
0 equal 0

Does it mean that [ $? -eq 0 ] is also a command or function? I'm puzzled!
Comment: Because even `[ $? -ne 0 ]` is an expression which is evaluated and status is placed in the `$?` after the excecution
Comment: For the record, an idiomatic shell script should almost never need to examine `$?`.  The usual syntax is simply `if echo good; then echo "$? equal 0"; else echo "$? not equal to 0"; fi`.  You'll notice that this also preserves the value of `$?` to the inside of the conditional.
Comment: yeah,but sometimes it is useful.thanks all very much
Answer: Your original code could be rewritten as:
$ if echo "good"; then echo "$? equal 0"; fi
good
0 equal 0

Since your code is only checking the exit value of the echo command, it's almost always going to return 0 (e.g. "true") unless its file descriptor is closed. For example:
$ echo foo; echo $?
foo
0

$ echo bar >&- ; echo $?
-bash: echo: write error: Bad file descriptor
1

Comment: thanks for your help and i understand your example,but what i am still beening confused is why the value of $? changed in the first test script? And as your say, if it means its origin file descriptor is closed after the condition  " if [ $? -ne 0 ];then..."  ? thanks a lot


List of relations, union and intersections of relations

Question: I would like to know if these exercises about relations are right. I will appreciate any help.
1. Write a list of all relations from the set $A$ to the set $B$ where $A=\{\alpha,\beta\}$ and $B=\{x\}$.
$R=\{(\alpha,x),(\beta,x)\}$
2. Given the relations $R_1=\{(1,2),(3,4),(5,6),(7,8),(9,10)\}$ and $R_2=\{(a,b),(1,2),(c,d),(3,4)\}$. Find the relation $R_1∩R_2$ and $R_1∪R_2$.
$R_1∩R_2=\{(1,2),(3,4)\}$
$R_1∪R_2=\{(1,2),(3,4),(5,6),(7,8),(9,10),(a,b),(c,d)\}$
Answer: Your answer to the second question is correct.
For the first one, recall that a relation from $A$ to $B$ is a subset of $A \times B$. Since in your case, $A$ has two elements and $B$ has one element, the set $A \times B$ has two elements, and the set of subsets of $A \times B$ has $2^2 = 4$ elements. Thus you should find four relations, but you just found one of them...
Comment: I guess you mean that $R_1 = \{(\alpha,x), (\beta,x)\}$, $R_2 = \{(\alpha,x)\}$ and $R_3 = \{(\beta,x)\}$ are three relations from $A$ to $B$. So what is the fourth one?
Comment: Yes, this is it!
Comment: So are $(x,\alpha)$ and $(x,\beta)$  are too in $R$?
Comment: So is $R_4=\emptyset$ ?
Comment: Thanks so much for your help. <3
Comment: You're welcome. If you are satisfied with the answer, you have the possibility to accept it. See https://math.stackexchange.com/tour .


Duplicate Website with different theme?

Question: I would like to create a duplicate of my existing website (includes all content) and apply a different theme.
So for example I would have www.widgets.com with one theme & products.widgets.com with the same content but a totally different theme.
Also, when I add/update/delete content in www.widgets.com I would like it to change in products.widgets.com.
What's the best way to accomplish this? I'm using Drupal 6.
Thanks-in-advance
Answer: You could take a look at themekey module.

ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.

One other property is "host", which would fit into your demands, although this wouldn't be actually a copy of your site. Instead you would just switch the theme on another domain. (On a side note you should consider avoiding "duplicate content" for better serach results.)
Comment: Thanks, does themekey allow changing theme based on URL?
Comment: Also, I was thinking of setting up a Drupal Multi-Site http://drupal.org/documentation/install/multi-site
Comment: I'm not sure if ThemeKey let you change the theme based on domain, but if not, you can use [Domain Access](http://drupal.org/project/domain).

Domain access let you choice the theme based on domain.
Comment: ThemeKey works great! Switched the theme, with some minor tweeks, based on the incoming URL.
Comment: I still have one related issue with Themekey

Duplicate Website with different theme?


Is the $\sum_{n=1}^{\infty} \frac{(2n+1)^{1/2}}{n^2}$ convergent or divergent?

Question: For this question I am not really sure which test to use to determine this. I was thinking the comparison or limit comparison test but it doesn't seem to be working. I was wondering what the steps are to figure this out, and if it is the comparison test, how would you use it? Any help is appreciated!
Answer: Note that
$$\dfrac{\sqrt{2n+1}}{n^2} \leq \dfrac{\sqrt{3n}}{n^2} = \dfrac{\sqrt3}{n^{3/2}}$$
Hence, the series $$\displaystyle\sum_{n=1}^{\infty} \dfrac{\sqrt{2n+1}}{n^2} \leq \sum_{n=1}^{\infty} \dfrac{\sqrt3}{n^{3/2}} = \sqrt3 \zeta(3/2) < \infty$$
Comment: Thank you! I was just wondering how you chose to compare it to (3n)^(1/2)?
Comment: @user138069: probably since $2n+1\le3n$ for $n\ge1$.
Comment: @user138069 Note that asymptotically we have $\dfrac{\sqrt{2n+1}}{n^2} \sim \dfrac{\sqrt{2n}}{n^2}$. Hence, we know that the $n^{th}$ term goes as $\dfrac1{n^{3/2}}$. All we need to do is to find the appropriate scale. Here it turns out to be trivial.
Answer: We have
$$\frac{\sqrt{2n+1}}{n^2}\sim_\infty\sqrt2\frac{1}{n^{3/2}}$$
hence the given series is convergent by the asymptotic comparison with a convergent Riemann series.


How do I use a custom container image in a Tekton step?

Question: I'm new to Tekton and Tekton Pipelines.  The examples I found use standard container images in the Tekton task steps.  For example, the following step uses a standard ubuntu container to run a shell script:
  steps:
    - name: test-step
      image: ubuntu
      script: |
        #!/bin/sh
        echo "testing"

I would like to use my own custom container with custom applications in a Tekton step:
  steps:
    - name: custom-step
      image: custom-container
      script: |
        #!/bin/sh
        customCommand arg1 arg2

How do I do this?  I found Tekton Tasks and Pipelines Container Contract, which describes the "contract" that a custom container must follow.  However, I still don't understand how to define and use a custom container.  Specifically,

How is the custom container image actually defined?  An example Dockerfile would be helpful.
How do I tell Tekton where my custom container image is located?  Do I need save my custom container image in a Docker image repository?

Is there an example showing how to create and use a custom container image that I can refer to?  Thanks.
Comment: Yes, you need to push to a registry.
Answer:
How is the custom container image actually defined? An example Dockerfile would be helpful.

You can use any docker container. You can first test that it works on your local machine using docker run <container>. You need to carefully think about the exit code of your main process in the container, 0 means success and any other number means that it failed, Tekton use this signal to signal if the Task is successfully run or failed.

How do I tell Tekton where my custom container image is located? Do I need save my custom container image in a Docker image repository?

The containers for Tekton are run in Kubernetes. You need to make your container available on a container registry that your Kubernetes cluster can pull them from. This is the same process to how you make the container images available for Kubernetes for your applications in the cluster. E.g. docker push <container-registry-and-image-name>


Python import module from nearby directory instead of from site packages

Question: I am trying to test changes to a Python module, let's call it my_import_module.  Currently, it's in a site package.  I would like to import it from my local file structure, not from my site packages.
The folder structure looks like this:
dir
|--dirA
   |--dirB
      |--my_import_file.py
      |--__init__.py
|--dirC
   |--dirD
      |--main.py
      |--__init__.py

I am trying to import the file my_import_file.py into main.py, and not from the site packages version.
Currently I have from ../../dirA.dirB.my_import_file import XYZ.  This doesn't work.
I would like to not add __init__.py into each directory.
Two questions:

How can I import my_import_file.py from the directory instead of from site packages?
What is the Python code to import my_import_file?
Comment: Stop thinking about files and directories and start thinking about packages and modules. Then decide in which package you want the module to be (i.e. is it `import dirA.dirB.my_import_file`, or just `import my_import_file`). Then organise the directories the way you want packages to be structured and put an `__init__.py` into each package, because that is how packages are created.
Answer: See https://www.python.org/dev/peps/pep-0328/
The way to do is
from ...dirA.dirB.my_import_file import XYZ


clustering for categorical data with one column for observations

Question: I'm trying to cluster a dataset using 4 variables, all of which are categorical variables. I'd also like to include another numerical variable that's actually the number of observations of another column. My data is laid out like below:
ColA, ColB, ColC, ColD, ColE
where ColE would be the frequency of ColD; and all Columns A-D are categorical variable.
I don't want to use a supervising learning technique because of various reasons (the top one being I don't know what my result should be; only that I want to have k number of groups that are similar enough).
What's the best clustering algorithm to use for this? I've been thinking k-modes but that doesn't solve the problem of ColE being a feature of ColD.
Comment: Could you possibly provide an example of your data record. Especially the relationship of D and E seems to be unclear somehow.
Comment: Sure, so the dataset looks like this: with Color being ColD and Frequency being ColE: Item    |   Season | Type  |   Color| Frequency
Clothing| Summer| Suit| Navy| 2
Clothing| Summer| Suit| Black|  3
Clothing| Summer| Suit| Grey | 3
Comment: Sorry, the formatting here is confusing me a little bit. But the column E is a frequency column that denotes the number of observation for all the characteristics. I want a clustering of "like" ColA based on the characteristics of columns B, C, D and E but want to use unsupervised learning algorithm. thanks!
Comment: There are some answers to this question on [Stack Overflow](https://stackoverflow.com/q/29771355/4752675) Also check out [Modified Value Distance Metric](https://axon.cs.byu.edu/papers/wilson.aie96.ivdm.pdf) and variants
Comment: You can apply Multiple correspondence analysis (MCA) to your dataset, then apply appropriate clustering algorithms accordingly.
Answer: Have you tried encoding the categorical variables into numeric?
http://fastml.com/converting-categorical-data-into-numbers-with-pandas-and-scikit-learn/
I would recommend starting with maybe two variables to apply K-modes and then iterate/increase the number of variables from there, as you analyze the results.
Comment: Thanks for the suggestion! Dummy variables doesn't work in my case because you end up vastly increasing the problem size- my categorical values have many values (~1000 in one case) so I'd need to add 999 new columns just to get that one column. The categorical vars part of the problem is solved using k-means/k-prototypes. My main problem is dealing with a dependent numeric variable (frequency count of each observation) - where I want the frequency of the observation to matter as well.
Comment: @sudhareg: This is important information, and should have been added as an edit and not only as comment!
Answer: If you have only categorical variables, I would suggest to select a distance function (Hamming, Chi2,...), calculating the distance matrix between each observation, and then running a good old hierarchical clustering algorithm. You should try several distance functions to find the one giving the most meaningful results.


Given $1/2x^TQx+d^Tx$ s.t $a_1^Tx\leq b_1$ $a_2^Tx\leq b_2$ find optimal solution

Question:
Given min $1/2x^TQx+d^Tx$
s.t $a_1^Tx\leq b_1$
$a_2^Tx\leq b_2$
and $Q\succ0(n\geq3)$ $a_1,a_2,d\in\mathbb{R}^n$ and $b_1,b_2\in\mathbb{R}$,Assume that $a_1^TQ^{-1}a_1=a_2^TQ^{-1}a_2=2,a_2^TQ^{-1}a_1=0,a_1,a_2\neq0$
Find the optimal solution

I've set the lagrangian to be $L(x,\lambda,\eta)=1/2x^TQx+d^Tx+\lambda(a_1^Tx- b_1)+\eta(a_2^Tx-b_2)$
$\frac{\partial L}{\partial x}=Qx+d+\lambda a_1+\eta a_2$
I've tried setting $\lambda\neq0,\eta=0$ and solving but didn't get me anywhere,any hint please?
Comment: Sorry, not clear for me. If you look at a minimum, take $x = 0$. If you look at a maximum, select $x$ orthogonal to $a_1$, $a_2$ and $d$ for example (for n > 3). Then you get a maximum equal to $\infty$. Maybe you forgot that $x$ has a fixed norm.
Comment: I forgot to mention minimum and maybe x=0 doesn't satisfy the constraints
Comment: I forgot that $d^Tx$ may be negative!
Answer: So you got $L(x,\lambda,\eta)=1/2x^TQx+d^Tx+\lambda(a_1^Tx- b_1)+\eta(a_2^Tx-b_2)$ and derived the stationarity condition:
$$Qx+d+\lambda a_1+\eta a_2=0$$
You somehow need to use that $a_1^TQ^{-1}a_1=a_2^TQ^{-1}a_2=2,a_2^TQ^{-1}a_1=0,a_1,a_2\neq0$. If you pre-multiply the stationarity condition with $a_1^TQ^{-1}$ and $a_2^TQ^{-1}$ you get:
$$a_1^Tx+a_1^TQ^{-1}d+2\lambda=0 \quad \text{and} \quad a_2^Tx+a_2^TQ^{-1}d+2\eta=0$$
which means:
$$\lambda=-0.5(a_1^Tx+a_1^TQ^{-1}d) \quad \text{and} \quad \eta=-0.5(a_2^Tx+a_2^TQ^{-1}d)$$
Plugging that back into the stationarity condition, you get:
$$Qx+d-0.5(a_1^Tx+a_1^TQ^{-1}d) a_1-0.5(a_2^Tx+a_2^TQ^{-1}d) a_2=0$$
Since $(a_1^Tx)a_1 = a_1(a_1^Tx)=(a_1a_1^T)x$, the stationarity condition can be simplified to:
$$(Q-0.5a_1a_1^T-0.5a_2a_2^T)x+d-0.5a_1^TQ^{-1}d a_1-0.5a_2^TQ^{-1}d a_2=0$$
so
$$x = (Q-0.5a_1a_1^T-0.5a_2a_2^T)^{-1}(0.5a_1^TQ^{-1}d a_1+0.5a_2^TQ^{-1}d a_2-d)$$
Comment: The only question is how can we know that $\lambda\geq0$?
Comment: @convxy try plugging in $x$ in the formula for $\lambda$ and simplyfing the expression, you may need the Sherman-Morrison formula


Help evaluating summation.

Question: I am trying to evaluate:
$$\lim_{n \to \infty}\frac{\sum\limits_{i=1}^{n}{10}^{i/n}}{n}$$
My thought is convert it to convert it to an integral:
$$\lim_{n \to \infty}\frac{\sum\limits_{i=1}^{n}{10}^{i/n}}{n} = \lim_{n \to \infty}\sum\limits_{i=1}^{n}{10}^{i/n} \times \frac{1}{n} $$
Which means:
$$ \frac{b-a}{n} = \frac{1}{n} $$
$$ b - a = 1 $$
Therefore we can say the integral evaluates from 0 and 1 (not sure about this):
$$ \int_0^1{10^{x} dx}$$
And using U-substitution I get:
$$ \frac{1}{ln(10)} \times e^{ln(10)} - \frac{1}{ln(10)} $$
$$ \frac{9}{ln(10)} $$
Did I do this right?
Answer: You should recognize this as a Riemann sum, with value
$$\int_0^1 dx \, 10^x  = \int_0^1 dx \, e^{\log{10} x}=\frac1{\log{10}} (e^{\log{10}}-1)= \frac{9}{\log{10}}$$

Help evaluating summation.


Visualisar interface da box na virtualbox

Question: Como usar a interface da máquina virtual, e não somente pelo terminal de comandos?
Segue o link do meu vagrantfile:
https://gist.github.com/anonymous/fbd8f17a0a85ff4c223c
Answer: Pelo que eu entendi, você quer usar a interface da máquina virtual, e não apenas interagir com ela por meio da linha de comando (após executar vagrant ssh), certo?
Normalmente as máquinas virtuais são headless, o que significa que são inicializadas sem a UI (interface de usuário). Para inicializar a UI da VM, basta adicionar a seguinte configuração no Vagrantfile:
config.vm.provider "virtualbox" do |v|
  v.gui = true
end

Comment: Já fiz isso mas a box não aparece quando abro o virtualbox entende?
Comment: Já entendi o seu problema. Vou complementar a resposta.
Comment: Nesse caso eu preciso configurar algo na própria interface do virtualbox, ou só acrescentar essa configuração que você colocou ai no vagrantfile?
Comment: @Faro É só colocar a configuração.
Comment: Ainda não funcionou, será que falta algo além disso para acrescentar no vagrantfile?
Comment: Até onde eu sei é só isso mesmo. Você rodou um `vagrant down` e um `vagrant up`, ou simplesmente um `vagrant reload`, depois disso?
Comment: Resolvido caro.


Falha ao copiar todo um diretório e seus arquivos

Question: Estou precisando copiar todo um diretório que contem arquivos dentro usando o Java NIO2 com FileChannels. Porem só consigo fazer a cópia dos arquivos dentro do diretório.
Segue o código que estou usando para copiar os arquivos:
public static void copiaDestino(File destino, File origem) throws IOException{

    FileChannel inChannel = new FileInputStream(origem).getChannel();
    FileChannel outChannel = new FileOutputStream(destino).getChannel();
    try{
        int maxCont = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;

        while (position < size){
            position += inChannel.transferTo(position, size, outChannel);
        }
        }finally{
            if(inChannel != null){
                inChannel.close();
            }
            if(outChannel != null){
                outChannel.close();
            }
        }
    }
}

Comment: Então como ainda estou testando eu crio duas variáveis do tipo File e passo os caminhos (Origem/Destino). Ao executar o código passando o diretório e não o nome do arquivo da um erro (Exception in thread "main" java.io.FileNotFoundException: C:\Novapasta (Acesso negado))
Comment: Então o caminho ate encontra quando eu coloco dentro do " C: " porem se eu quiser copiar por exemplo "C:\teste" também da o mesmo erro, mas se eu adicionar:

 File origem = new File("C:\\Novapasta\\server.sql");
 File destino = new File("C:\\t");

Ele cria um arquivo com o nome de " t " em "C:"
Comment: Peço desculpas estou começando agora aqui. Mas o que estou tentando fazer é copiar o diretório "C:\Nova Pasta" para "C:\Nova Pasta2", tenho o método acima pra fazer a cópia tanto do diretório quanto dos arquivos contido nele. Na main eu instancio 2 variáveis do tipo File e passo origem e destino, se eu deixar assim como eu disse acima origem e destino ele da acesso negado na pasta de origem e se eu apontar um arquivo dentro da pasta de origem o erro de acesso negado acontece no caminho de destino, caso o caminho de origem nao exista então ele cria um arquivo e nao copia o citado na origem
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Este método só copia arquivos e não diretórios.
Pelos comentários parece estar funcionando quando usado corretamente. Eu notei que tem uma inversão de parâmetros que faz o seu uso não ser tão intuitivo e provavelmente está gerando erros porque ele está fazendo o contrário do que pensa.
Por falta de informações não posso ajudar mais que isto.
//note a inversão dos parâmetros aqui
public static void copiaDestino(File origem, File destino) throws IOException{

    FileChannel inChannel = new FileInputStream(origem).getChannel();
    FileChannel outChannel = new FileOutputStream(destino).getChannel();
    try{
    int maxCont = (64 * 1024 * 1024) - (32 * 1024);
    long size = inChannel.size();
    long position = 0;

    while (position < size){
        position += inChannel.transferTo(position, size, outChannel);
    }
    }finally{
    if(inChannel != null){
        inChannel.close();
    }
    if(outChannel != null){
        outChannel.close();
    }
}

No main():
try {
    File origem = new File("C:\\Novapasta\\server.sql");
    File destino = new File("C:\\t");
    copiaDestino(origem, destino)
} catch (Exception ex) { //isto só é útil aqui porque é o main
    System.out.println("Deu erro");
}

Coloquei no GitHub para referência futura.
Comment: Obrigado pela ajuda... Mas o erro que estava dando de acesso negado era porque eu estava passando um arquivo como origem e um diretório como destino... ficaria assim:

File origem = new File("C:\\Novapasta\\server.sql");
File destino = new File("C:\\t\\cópia.sql");

Só assim ele copiou. Obrigado e fica ai pra caso alguém esteja com a mesma dificuldade.


Oracle - Disable masive updates

Question: Is any way to disable massive updates/deletes (without where clause) in SQL Developer?
Mysql workbench has a similar tool that prevents a user run update statements without where clause. Is any similar tool in Oracle SQL developer?
Thanks
Comment: You want that only in *the* client (SQL Developer) or in the database (regardless of the client)?
Comment: You could have a look at [Oracle Resource Manager](http://www.oracle.com/technetwork/database/performance/resource-manager-twp-133705.pdf) and see if that does what you need. It has nothing to do with SQL Developer specifically though.
Comment: I prefer do it only in sql developer (for some reasons). If is not posible maybe we can do it on server side
Answer: No.
But you can limit the damage a user can unleash on your SGA/temp space/CPU by creating a resource consumer group (Docs)
It's best to control this sort of problem at the database/server level. If you build 'security' into the client, then you're in trouble as soon as they go and use another client, like SQL*Plus or one of the 100 other Oracle database clients out there.
If you have a database user that does this frequently, use the READ privilege in 12c and higher. It allows you to grant ONLY the ability to ONLY do a SELECT.
Comment: Is any way to limit the maximum records afected in a update query? I need to prevent that a single user updates a complete table by error. There is no problem if i need to use a specific client (or grant any system privilege). Its only for precaution.
Comment: @Mickey basically the answer is 'no' - you can restrict ability to do UPDATES completely, or they can update as much as they want - whether that's 'too many' or not. Also, what if there where clause is 1=1? Or they think they have a good one but it effectively is always true for every row?
Comment: The clause 1=1 is not a problem. Normally the user should updates in some tables but in certain situations he forget the where clause.... I want to prevent that user writes "update table set field=123" and forgets where clause and do a massive update. If he write "where 1=1 " it's not a problem because he wrote it...

Oracle - Disable masive updates


Nginx rewrite certain port to subpath (nginx + uwsgi + django)

Question: My goal is to rewrite everything under http://localhost:8000 to http://localhost/foo
I followed every step mentioned in this link, but still couldn't get it work.
Here's my settings:
urls.py (Django)
urlpatterns = [
    url(r'^$', 'home.view'),
    url(r'^foo$', 'foo.view'),
]

uwsgi.ini (uWSGI)
[uwsgi]

chdir           = /home/user/folder/project
wsgi-file       = /home/user/folder/project/iTrends/wsgi.py
home            = /home/user/.pyenv/versions/project
master          = true
processes       = 10
threads         = 5
socket          = /tmp/project.sock
chmod-socket    = 666
vacuum          = true
logto           = /tmp/project_uwsgi.log
http-websocket  = true
buffer-size     = 65535

nginx80.conf (nginx with port 80)
server {
    listen       80;
    server_name = _;

    location /test {
        rewrite ^/test/(.*)$ /$1 break;
        proxy_pass  http://127.0.0.1:8000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

nginx8000.conf (nginx with port 8000)
server {
    listen      8000;
    server_name _;
    charset     utf-8;

    client_max_body_size 75M;

    location /static {
        alias /home/user/folder/project/static_all;
    }

    location / {
        uwsgi_pass  unix:///tmp/project.sock;
        include     /etc/nginx/uwsgi_params;
    }
}

Now
http://localhost/test is equivalent to http://localhost:8000
but when I go to http://localhost/test/foo, nginx tells me "not found"
(I expect this the same as http://localhost:8000/foo)
What did I miss?
Comment: Old question, but stumbled over it: I think proxy_pass is never reached because the rewrite is done before.
Answer: It seems that the problem is the extra $ in the rewrite rule (in the first argument). I removed it and it has started working fine.
    location /test {
        rewrite ^/test/(.*) /$1 break;
        proxy_pass  http://127.0.0.1:8000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

Comment: I just include the location part, but  the rest is just the same as yours
Comment: Can you please post the full configuration block you are using?
Comment: No problem, I've updated my question.
Comment: Updated the answer; Seems the extra $ was the cause of your troubles; I tested it locally with the above configuration
Comment: Still not working, the problem might be uwsgi instead of nginx...
Comment: Try setting the error_log level to debug. You might get additional insights there. With the above configuration, I can confirm that I was able to get nginx redirection (or rather proxy) work


How to change line color of kableExtra::spec_pointrange when knitting PDF

Question: kableExtra creates a table with some plots, as its manual demonstrates.
We will have the following table with a pointrange plot with kableExtra::spec_pointrange(), running the code at the bottom of this post.
But how can I change colour of lines of the plot (Note, NOT the colour of the centre dots), when knitting a PDF.
It should be awesome if we can freely specify the colour of the error bar and vertical dot line also in PDF, since somehow it seems to be possible to change the line colour interactively when knitting HTML as suggested in a blog post.

coef_table <- data.frame(
  Variables = c("var 1", "var 2", "var 3"),
  Coefficients = c(1.6, 0.2, -2.0),
  Conf.Lower = c(1.3, -0.4, -2.5),
  Conf.Higher = c(1.9, 0.6, -1.4)
)
data.frame(
  Variable = coef_table$Variables,
  Visualization = ""
) %>%
  kbl(booktabs = T) %>%
  kable_classic(full_width = FALSE) %>%
  column_spec(
    2,
    image = spec_pointrange(
      x = coef_table$Coefficients,
      xmin = coef_table$Conf.Lower,
      xmax = coef_table$Conf.Higher,
      vline = 0
    )
)

Answer: The author of the package Hao Zhu added line_col to spec_pointrange. So now the kableExtra supports the line colour configuration.


User need to click on save button twice if flatlist is inside scrollview

Question: I have placed Flatlist and save button inside scrollview and each Flatlist item has a input field.
When the input field is in focus and keyboard is open.
When I touch the save button first time it is dismissing the keyboard and next time when the user clicks on button action is performed.
I have tried adding keyboardShouldPersistTaps ={'handled'}
In scrollview and flatlist.
But it is not working.
Please find my pseudo code below.
<code>   <Scrollview>
   <TouchableWithoutFeedback>
   <View>
   <Flatlist/>
   <TouchableOpacity>
   </TouchableOpacity>
   </View>
   </TouchableWithoutFeedback>
   </Scrollview>

</code>
Please help me resolving this issue.
Answer: You can use this props in your Scrollview Component,
keyboardShouldPersistTaps='always'
keyboardDismissMode='on-drag'
Comment: Hi @AKAK
Thanks for your reply.
I have tried this but not working.
Comment: example


WSL apt install jdk results in 404 Not Found

Question: Windows 11 WSL. Installing JDK 11 results in the error: 404 not found.
 wsl> sudo apt install openjdk-11-jdk-headless

    Reading package lists... Done
    Building dependency tree... Done
    Reading state information... Done
    The following additional packages will be installed:
      alsa-topology-conf alsa-ucm-conf ca-certificates-java fontconfig-config fonts-dejavu-core java-common libasound2 libasound2-data
      libavahi-client3 libavahi-common-data libavahi-common3 libcups2 libfontconfig1 libfreetype6 libgraphite2-3 libharfbuzz0b
      libjpeg-turbo8 libjpeg8 liblcms2-2 libnspr4 libnss3 libpcsclite1 openjdk-11-jre-headless
    Suggested packages:
      default-jre libasound2-plugins alsa-utils cups-common liblcms2-utils pcscd openjdk-11-demo openjdk-11-source libnss-mdns
      fonts-dejavu-extra fonts-ipafont-gothic fonts-ipafont-mincho fonts-wqy-microhei | fonts-wqy-zenhei fonts-indic
    The following NEW packages will be installed:
      alsa-topology-conf alsa-ucm-conf ca-certificates-java fontconfig-config fonts-dejavu-core java-common libasound2 libasound2-data
      libavahi-client3 libavahi-common-data libavahi-common3 libcups2 libfontconfig1 libfreetype6 libgraphite2-3 libharfbuzz0b
      libjpeg-turbo8 libjpeg8 liblcms2-2 libnspr4 libnss3 libpcsclite1 openjdk-11-jdk-headless openjdk-11-jre-headless
    0 upgraded, 24 newly installed, 0 to remove and 0 not upgraded.
    Need to get 260 MB of archives.
    After this operation, 410 MB of additional disk space will be used.
    Do you want to continue? [Y/n] Y
    Get:1 http://archive.ubuntu.com/ubuntu jammy/main amd64 alsa-topology-conf all 18.104.22.168-2 [15.5 kB]
    Get:2 http://archive.ubuntu.com/ubuntu jammy/main amd64 libasound2-data all 18.104.22.168-1ubuntu1 [19.1 kB]
    Get:3 http://archive.ubuntu.com/ubuntu jammy/main amd64 libasound2 amd64 188.8.131.52-1ubuntu1 [390 kB]
    Err:4 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 alsa-ucm-conf all 22.214.171.124-1ubuntu1.1
      404  Not Found [IP: 22.214.171.124 80]
    Get:5 http://archive.ubuntu.com/ubuntu jammy/main amd64 java-common all 0.72build2 [6782 B]
    Get:6 http://archive.ubuntu.com/ubuntu jammy/main amd64 libavahi-common-data amd64 0.8-5ubuntu5 [23.9 kB]
    Get:7 http://archive.ubuntu.com/ubuntu jammy/main amd64 libavahi-common3 amd64 0.8-5ubuntu5 [23.7 kB]
    Get:8 http://archive.ubuntu.com/ubuntu jammy/main amd64 libavahi-client3 amd64 0.8-5ubuntu5 [28.1 kB]
    Ign:9 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 libcups2 amd64 2.4.1op1-1ubuntu4.1
    Get:10 http://archive.ubuntu.com/ubuntu jammy/main amd64 liblcms2-2 amd64 2.12~rc1-2build2 [159 kB]
    Get:11 http://archive.ubuntu.com/ubuntu jammy/main amd64 libjpeg-turbo8 amd64 2.1.2-0ubuntu1 [134 kB]
    Err:9 http://security.ubuntu.com/ubuntu jammy-updates/main amd64 libcups2 amd64 2.4.1op1-1ubuntu4.1
      404  Not Found [IP: 22.214.171.124 80]

Comment: and we do not support home and enduser questions. mostly solveable by apt update and a stable dns resolution
Comment: Could you explain how "apt update" resolved this 404 issue? Thanks.
Comment: After posting this question, I am not allowed to post any more questions. Any one know why? This question is not out of scope. This forum is for those who needs help, not for experts, right?
Answer: Apt uses a local cache to speed up fetching new packages.
This package could get stale.
Location of lists
/var/lib/apt/lists

what update do
Manpage Says about it:
      update (apt-get(8))
           update is used to download package information from all configured sources. Other commands operate on this data to e.g. perform package
           upgrades or search in and display details about all packages available for installation.

Mostly, when using different sources or changed it, then is it recommended running a clean before
      clean
           clean clears out the local repository of retrieved package files. It removes everything but the lock file from /var/cache/apt/archives/ and
           /var/cache/apt/archives/partial/.

Why did it solve now an 404 error?
We have to look into an Packages
to keep confusion low, i use one of the packges:
Package: libasound2-data
Source: alsa-lib
Version: 1.2.8-1
Installed-Size: 200
Maintainer: Debian ALSA Maintainers <firstname.lastname@example.com>
Architecture: all
Replaces: libasound2 (<< 1.2.8-1)
Recommends: alsa-ucm-conf, alsa-topology-conf
Suggests: alsa-utils
Breaks: libasound2 (<< 1.2.8-1)
Description: Configuration files and profiles for ALSA drivers
Multi-Arch: foreign
Homepage: https://www.alsa-project.org/
Description-md5: 41f916f1c1cbcf480b3b7fe38fbcef23
Tag: role::shared-lib
Section: libs
Priority: optional
Filename: pool/main/a/alsa-lib/libasound2-data_1.2.8-1_all.deb
Size: 20488
MD5sum: 8cdd32445982638bf5d024453da19673
SHA256: fe0780d2d3674b2977e0acb0d48b448ad72ba1642564b7dc537f55e839984c2d

It tells apt, that the file is located in pool/main/a/alsa-lib/libasound2-data_1.2.8-1_all.deb
But it could happen, that the file has been replaced by another version and may now unavailable. That is the reason, why it is so important to execute apt update regularly before installing packages.
Comment: Thanks. But the 404 error shows that IP address can not be found, not a file.
Comment: error 404 is file not found
Comment: After posting this question, I am not allowed to post any more questions. Any one know why? This question is not out of scope. This forum is for those who needs help, not for experts, right?
Comment: I am wondering who has the right to lock other accounts :)
Comment: The best way to address your request is by posting it on meta.serverfault.com. However, please note that if your question is about how to handle a 404 error on a home computer or end-user device, it may be off-topic. The focus of this platform is on managing information technology systems in a business environment and the question should have a direct impact on it. Also, keep in mind that you need to be a business administrator in charge of this environment.
Comment: And shortly responded to the question "this forum is for help not experts" I am sorry to inform you that this is wrong. Superuser.com is the best choice for you imho, moreover here some helpful links: [help] ontopic: [help/on-topic], don't ask:[help/dont-ask], behavior: [help/behavior] and meta help: [meta-help]


Detecting that the stack is full

Question: When writing C++ code I've learned that using the stack to store memory is a good idea.
But recently I ran into a problem:
I had an experiment that had code that looked like this:
void fun(const unsigned int N) {
    float data_1[N*N];
    float data_2[N*N];

    /* Do magic */
}

The code exploted with a seqmentation fault at random, and I had no idea why.
It turned out that problem was that I was trying to store things that were to big on my stack, is there a way of detecting this? Or at least detecting that it has gone wrong?
Comment: Oh come on, how can you resist using the [tag:stackoverflow] tag?
Comment: g++ allows VLAs in C++ as well, as an extension.
Comment: Is your question about C or C++?
Comment: I think you can not initialize an array on the stack using variables in C/C++ !
Comment: How big is your data? I suggest that you store 100KB+ data in heap using malloc/free. (Other people may suggest an even lower bound)
Comment: @MartinKristiansen then why also mark it C?
Comment: May be you overrun array boundaries?
Comment: The code you wrote is not valid C++, so I assume you are talking about C99 or C11, those have VLAs.
Answer: float data_1[N*N];
float data_2[N*N];

These are variable length arrays (VLA), as N is not a constant expression. The const-ness in the parameter only ensures that N is read-only. It doesn't tell the compiler that N is constant expression.
VLAs are allowed in C99 only; in other version of C, and all versions of C++ they're not allowed. However, some compilers provides VLA as compiler-extension feature. If you're compiling with GCC, then try using -pedantic option, it will tell you it is not allowed.
Now why your program gives segfault, probably because of stack-overflow due to large value of N * N:

Consider using std::vector as:
#include <vector>

void fun(const unsigned int N)
{
  std::vector<float> data_1(N*N);
  std::vector<float> data_2(N*N);

  //your code
}

Comment: @SPIRiT_1984: In fact, it is bad idea to use `malloc` from the start. Use `std::vector` when you need dynamic array. Use `malloc/new` and manage memory yourself, when you've *very strong reason* to do so.
Comment: const function parameter doesn't change anything here, the value is still only known at runtime so you're still relying on a compiler extension. Anyway be it C or C++, the point is- if you need lots of memory, use heap instead (via `std::vector`).
Comment: @MartinKristiansen: I edited my answer, saying *"The const-ness in the parameter only ensures that `N` is read-only. It doesn't tell the compiler that `N` is constant expression."*
Comment: @MartinKristiansen: Try using `-pedantic` option if you're using GCC to compile your code.
Comment: I added the const to the questing :-)
Comment: I was actually not aware that I was using a compiler extention. I'm runing the code on two platforms using Intel icc on Linux and gcc on a mac, and neither of the complain.
Comment: It's a bad idea from the start to use a vector, if you just need an array. This will give the overhead in time (and in memory also). So I would use the simple malloc, instead of using a vector.
Answer: It's extremely difficult to detect that the stack is full, and not at all portable. One of the biggest problems is that stack frames are of variable size (especially when using variable-length arrays, which are really just a more standard way of doing what people were doing before with alloca()) so you can't use simple proxies like the number of stack frames.
One of the simplest methods that is mostly portable is to put a variable (probably of type char so that a pointer to it is a char*) at a known depth on the stack and to then measure the distance from that point to a variable (of the same type) in the current stack frame by simple pointer arithmetic. Add in an estimate of how much space you're about to allocate, and you can have a good guess as to wether the stack is about to blow up on you. The problems with this are that you don't know the direction that the stack is growing in (no, they don't all grow in the same direction!) and working out the size of the stack space is itself rather messy (you can try things like system limits, but they're really quite awkward). Plus the hack factor is very high.
The other trick I've seen used on 32-bit Windows only was to try to alloca() sufficient space and handle the system exception that would occur if there was insufficient room.
int have_enough_stack_space(void) {
    int enough_space = 0;

    __try {           /* Yes, that's got a double-underscore. */
        alloca(SOME_VALUE_THAT_MEANS_ENOUGH_SPACE);
        enough_space = 1;
    }  __except (EXCEPTION_EXECUTE_HANDLER) {}

    return enough_space;
}

This code is very non-portable (e.g., don't count on it working on 64-bit Windows) and building with older gcc requires some nasty inline assembler instead! Structured exception handling (which this is a use of) is amongst the blackest of black arts on Windows. (And don't return from inside the __try construct.)
Comment: This was all based on the stack checking code that was in the implementation of Tcl 8.4; the code with SEH use was converted to using the first pointer-based method in 8.5, and dropped entirely in 8.6 (which uses a "stackless" engine implementation instead, and so doesn't need this sort of thing nearly so much).
Comment: BTW, storing the variable-sized arrays on the heap is going to be far more reliable, especially if you can use RAII-techniques to ensure reliable deletion.
Answer: Try using instead functions like malloc. It will return null explicitly, if it failed to find a block of memory of the size you requested.
Of course, in that case don't forget to free this memory in the end of function, after you are done.
Also, you can check the settings of your compiler, with what stack memory limit it generates the binaries.
Comment: If yoy want to allocate arrays dynamically, using `std::vector` would be my first choice.
Comment: @JoachimPileborg: Keeping track of allocated memory manually *is* hard in C++, due to the presence of exceptions. Like Kos said, the best solution is to rely on RAII by using a vector.
Comment: Malloc does help -- and using malloc was my sollution, but that means that now I have a pointer to keep track of.
Comment: Yes, that's true about the pointer, but since it is resided inside single function, there is no problem about that. Just add delete at the end of the function
Comment: @MartinKristiansen you don't need to keep track of pointers every time you use dynamic memory. There's a paradigm called `RAII` that simplifies that, google for it. And in the meantime, use a local `std::vector` object
Comment: +1 for compiler settings, which are really the only way to manage the stack.
Comment: @MartinKristiansen Keeping track of a pointer isn't that hard. Allocate the memory at the beginning of the function, and free it at the end and at every `return` statement.
Answer: One of the reasons people say it is better to use stack instead of heap memory can be because of the fact that variables allocated on top of the stack will be popped out automatically when you leave the body of the function. For storing big blocks of information it is usual to use heap memory and other data structures like linked lists or trees. Also memories allocated on the stack is limited and much more less than you can allocate in the heap space. I think it is better to manage the memory allocation and releasing more carefully instead of trying to use stack for storing big data.
You can use framework which manage your memory allocations. As well you can use VDL to check your memory leaks and memories which is not released.
Comment: That is my point, I've written the code to be 'mostly' used on small 'N's, but one in a while a big N will accure.
Answer:
is there a way of detecting this?

No, in general.
Stack size is platform depedent. Typically, Operating System decides the size of the stack. So you can check your OS (ulimit -s on linux) to see how much stack memory it allocates for your program.
If your compiler supports stackavail() then you can check it. It's better to go heap-allocated memory in situations where you are unsure whether you'd exceed the stack limit.
Comment: but here is the thing, I was developing on a Linux box with some highend hardware, and Spend alot of time figuring out why my code did'nt run on my MacBookPro. The Linux box had no problem with a 4 MB stack alloc, but the OSX box did not like it.

Detecting that the stack is full


IndexedDB object to jQuery custom trigger event?

Question: I am working on IndexedDB functionality in JS - i would like to add some custom jquery trigger event with object of IndexedDB upon success callback, not sure whether it is possible but when i test event fired but it doesn't pass IndexedDB object
            if ( !window.indexedDB ) {
                console.log( `Your browser not support IndexedDB` ) ;
                return ;
            }
            const request = indexedDB.open( 'pdr' , 1 ) ;
            request.onupgradeneeded = ( event ) => {
                let db = event.target.result ;
                let store = db.createObjectStore( 'CanvasObjects' , {
                    autoIncrement : true
                } ) ;
            } ;
            request.onerror = ( event ) => {
                console.error( `Database error: ${event.target.errorCode}` ) ;
            } ;

            request.onsuccess = ( event ) => {
                const db = event.target.result ;
                console.log(db);
                jQuery( document ).trigger( 'test_db_connected' , db ) ;

            } ;

After that i perform function on test_db_connected jquery event with following code
jQuery( document ).on( 'test_db_connected' , function ( db ) {
    console.log( 'testing_db' ) ;
    console.log( db ) ;
    const txn = db.transaction( 'CanvasObjects' , 'readwrite' ) ;
   } ) ;

but with above code it create error

Uncaught TypeError: db.transaction is not a function

Further check i figure out that whatever object return on request.onsuccess is not same in jQuery custom trigger event.
Is there any possibilities to pass IndexedDB object to the custom jquery trigger event?
Appreciate your response.
Answer: You are not using jQuery's event methods correctly. The handler accepts additional parameters for any custom data you send. So your handler should look like this:
jQuery(document).on('test_db_connected', function(ev, db) {
  console.log('testing_db');
  console.log(db);
  const txn = db.transaction('CanvasObjects', 'readwrite');
  console.log(txn);
});

Additionally, you really should use jQuery's Event object for constructing and triggering custom event. The docs state that the String event type parameter is to be used for DOM level events. But this still works fine.
Working Solution
Comment: Thank you so much, yes it works just great :-)


Gaussian Quadrature - derivation problem

Question: Derive a formula of the form
$$\int_{a}^{b}f(x)dx=w_0f(a)+w_1f(b)+w_2f'(a)+w_3f'(b)$$
that is exact for polynomials of the highest degree possible.
Not sure how to derive this formula. Possibly method of undetermined coefficients, but I'm not sure. Any help would be great :)
Answer: The fact that the right hand side contains $f(a)$, $f(b)$, $f^\prime(a)$ and $f^\prime(b)$ makes me think to the application of the integration by parts.
Indeed, on integrating by parts the first time, we have
$$\int_a^b f(x)dx=\left[xf(x) \right]_a^b-\int_a^bxf^\prime(x)dx$$
On integrating by parts the second time, we finally have
$$\int_a^b f(x)dx=-af(a)+bf(b)+\frac{a^2}{2}f^\prime(a)-\frac{b^2}{2}f^\prime(b)+\int_a^b\frac{x^2}{2}f^{\prime\prime}(x)dx.$$
giving $w_0=-a$, $w_1=b$, $w_2=a^2/2$ and $w_3=-b^2/2$.
The error of this formula is provided by
$$R(x)=\int_a^b\frac{x^2}{2}f^{\prime\prime}(x)dx$$
which is vanishing if $f^{\prime\prime}(x)=0$, namely, if $f^\prime(x)=c$ or $f(x)=cx+d$. So, the above integration formula is exact for polynomials of degree $1$.


Network card enabled but not working

Question: I have a strange behavior on one of my windows2003/IIS6 servers.
I have two network cards on it, let's call card A the card which connects the server with the internet, and let's call card B the card which connects the server with the intranet. The server is used by many users who connect to IIS with their netbooks.
The problem is that from time to time, the card A stops working.
I can reach the server in RDP through the card B, and I see that A is enabled but without any traffic. I can reset it, disable and re-enable it, but with no luck. The only thing that I can do is reboot the server, which is annoying.
Nothing useful in the system logs.
Only once I've been able to reproduce this behavior, when calling a very simple aspx page which only streamed a file (using Response.WriteFile), and calling the page from a netbook. reinstalled windows on that netbook, and it started downloading the file without locking the server card.
I am out of answers, any help greatly appreciated.
Thanks.
Comment: so your server is multi-homed?  maybe it would help if you showed us your routing table?  are both NIC's connecting to the network at the same speed?
Comment: I don't think it can be called multihomed, since web traffic can only get to the server through card A, correct me if I'm wrong.
the A card is 10/Mbps, the B 100Mbps.
Answer: Check your default gateways on the cards.  Make sure that only card A has a gateway.
Also, if you haven't tried performing an issreset you should perhaps do that first before disabling an enabling the card, then if that doesn't fix it, after the card.  If doing it first fixes it, you could be looking at an IIS problem.
Comment: for the gateways: do you think that the B card does change its ip configuration? I don't think so, the B card keeps working just like before the outage happens. Anyway, I'll check that.
I'll also try the iisreset as soon as the problem happens again, and will let you know
Comment: Regarding the gatway, no, I don't think they change.  I've seen setups where both NIC's had a gatway which would at times cause the OS to route the return traffic incorrectly making it appears as though the NIC was not working.  Examination using tcpdump on the firewall (wireshark would also work on the server) finally pointed out the problem.  Traffic would come in on one NIC but try to return on the other.
Comment: OK palehorse. now I understand. anyway when I disable-reenable the NIC, the traffic counters stay at 0 both for incoming and outgoing traffic.
Comment: Did you verify that only card A has a default gateway?  I did not see any response to that specifically.
Comment: AFAIK windows will pick the default route to be which ever NIC connects at a faster speed.  In your case B will be your default gateway, but something may be messing this up.  You might need to change your TCP/IP & put in some metric weights on your NIC, or as someone else suggested only give 1 NIC a gateway
Answer: I think there is a very good possibility that you have a firewall or some other external device that is causing this behavior and not the server itself.  This sounds like an attack script or rate limiting type behavior of a firewall protecting your server.
Do you have other devices in the same subnet as the 'A' card?  If so, try connecting from that device to your 'A' card and see if it is successful.
Comment: I agree that this could be a possibility, but int this case the weird thing would be the fact that rebooting the server fixes the problem... if it is an external device that cuts the connection (this would be ok with the fact that windows says that the NIC is healthy) why is the connection restored when the server reboots?
I cannot reach the A card from the LAN, the servers are hosted and not in my datacenter.
Comment: Rebooting the server will cause the interface to go up/down which may reset the attack script (if there is one).  Cisco switches (and probably others) have rate limiting features that could also cause this -- if you can wait about 10 minutes does it unblock?

http://www.cisco.com/en/US/docs/switches/lan/catalyst2950/software/release/12.1_22ea/SCG/swtrafc.html
Comment: Thanks Peter. No, the NIC does not unblock after 10 mins: it stays "offline" until I reboot. For hours, if nobody reboots the servers. alas, it happened.

Network card enabled but not working


Show that $\tau_A=\{U\cap A: U\in\tau\},A\subset X$, where $\tau$ is all open sets in $(X,d)$ is equal to the topology induced by $d|_{A\times A}$

Question: Let $(X,d)$ be a metric space and let $A\subset X$. Show that the topology $\tau_A=\{U\cap A: U\in\tau\}$ induced by the metric topology of $X$, $\tau$ (meaning $\tau$ is a collection of all subsets of $X$ open with respect to $d$), is equal to the metric topology of $A$ with the restriction $d|_{A\times A}: A\times A\to \Bbb{R}_{+}$.
(If I used any term incorrectly, or wasn't clear in the way I put it, it was due to a lack of the relevant terminology in English.).
I almost thought I can handle this question, that is, until I realized such a subset, $A\subset X$, can be closed. Suppose there is some $V\in \tau_A$. It is an intersection of $A$ and some open set $U$ in the metric topology $\tau$ of $X$. Before I can show it can be represented as a union of open balls with respect to the restriction of $d$ to $A\times A$, I have to clarify to myself that it is actually open in $A$. I mean, what if $\partial A$ intersects $V$? I am totally confused and could use some guidance.
Answer: Let $V \in \tau_A$, and choose $x \in V$.
By the definition of $\tau_A$, there must exist some $U \in \tau$ such that $V = U \cap A$. In particular, since $\tau$ is the topology induced by $d$, there is some $r>0$ such that $d(x,y)<r$ implies that $y\in U$. Hence, for any $y \in A$ that satisfies $d\vert_{A \times A} (x,y) <r$, it must be the case that $y \in V$. Thus, $V$ is open in the topology induced by $d\vert_{A \times A}$.
Fix some $x\in A$, and let $r>0$. Notice that
$$ \{ y \in A : d\vert_{A \times A}(x,y) < r \} = \{ y \in X : d(x,y)<r \} \cap A $$
This means that the open ball (with respect to $A$) around $x$ is in fact a member of $\tau_A$.
To (hopefully) answer the concern you outline at the end of your question: your normal intuitions about what sets are open and closed in the ambient space don't necessarily always apply.
To be more specific, consider the topology induced on $[0,1]$ by the standard topology on $\mathbb R$. Sets of the form $(a,1]$ where $a\ge0$ are open in $[0,1]$ (but clearly not in $\mathbb R$).


Red recording bar distorting view

Question: I'm having a heck of a time figuring this out.
I have a modal view that appears when tapping on one of the tabs of a tab bar. In the new view that takes over the whole screen, there is a button a user taps to start recording audio, and when they're finished recording audio, or if they cancel recording, the modal view is dismissed.
The problem is that, once they start recording, that red recording bar should appear on this new view. But it's not. And as soon as that view is dismissed, in the next view that is presented (a table view, which is found in one of the tabs), you can see the red recording bar at the top for a split second and it disappears BUT it shoves the tab bar down the screen and obscures part of the tab bar, which you can see in the third screenshot below.

Modal view pops up - recording is currently in progress, but red recording indicator is not showing at the top

Right when the recording is done and the view is about to disappear, the red bar appears

And once the view disappears and we're left with the table view that lives in one of the tabs, the tab bar is shoved down past the bottom of the screen :( It SHOULD look like this (with the fourth tab selected):

My questions:
1) What am I doing wrong that's causing the red recording bar to NOT show up in the modal view?
2) Is there a way to maybe refresh this view from the screenshot so that when it appears, it resizes properly?
Here's the code. I removed some of the non-important stuff that doesn't deal with the views.
<code>@interface AudioViewController ()

@end

@implementation AudioViewController

@synthesize fileData;

UILabel *countdownLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.friendsRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];
    self.recipients = [[NSMutableArray alloc] init];
}

- (void) viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    self.audioPicker = [[UIViewController alloc] init];
    self.audioPicker.view.backgroundColor = [UIColor yellowColor];

    self.friendsRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];
    PFQuery *query = [self.friendsRelation query];
    [query orderByAscending:@"username"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            NSLog(@"Error %@ %@", error, [error userInfo]);
        }
        else {
            self.friends = objects;
            [self.tableView reloadData];
        }
    }];

    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    cancelBtn.frame = CGRectMake(50.0, 200.0, 200.0, 200.0);
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];
    [self.audioPicker.view addSubview:cancelBtn];
    cancelBtn.center = CGPointMake(self.view.center.x, 400);
    [cancelBtn addTarget:self action:@selector(exitRecordingScreen) forControlEvents:UIControlEventTouchUpInside];

    UIButton *recordBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    recordBtn.frame = CGRectMake(50.0, 50.0, 200.0, 200.0);
    recordBtn.titleLabel.font = [UIFont systemFontOfSize:50];
    [recordBtn setTitle:@"Record" forState:UIControlStateNormal];
    recordBtn.center = CGPointMake(self.view.center.x, 100);
    [self.audioPicker.view addSubview:recordBtn];

    if ([self respondsToSelector:@selector(timeout)]) {
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeout) userInfo:nil repeats:NO];
    } else {
        NSLog(@"Error: missing selector");
    }

    AVAudioSession *session = [AVAudioSession sharedInstance];

    [session setCategory:AVAudioSessionCategoryPlayAndRecord
             withOptions:AVAudioSessionCategoryOptionDuckOthers
                   error:nil];

    if (!fileData) {
        [self presentViewController:self.audioPicker animated:NO completion:nil];
        NSLog(@"File data: %@", fileData);
        [recordBtn addTarget:self action:@selector(startRecordingAudio) forControlEvents:UIControlEventTouchUpInside];
    } else {
        NSLog(@"Existing File data: %@", fileData);
    }
}

- (void) timeout {

    [self.navigationController popViewControllerAnimated:YES];
}

# pragma mark - Audio Recording Methods

////////
// Removed some stuff here that is not manipulating views
////////

- (void) stopRecordingOnAudioRecorder:(AVAudioRecorder *)paramRecorder{
    /* Just stop the audio recorder here */
    [paramRecorder stop];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder
                           successfully:(BOOL)flag{
    if (flag) {
        NSLog(@"Stopped recording process");
        NSError *playbackError = nil;
        NSError *readingError = nil;
        fileData = [NSData dataWithContentsOfURL:[self audioRecordingPath]
                              options:NSDataReadingMapped
                                error:&readingError];

        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData
                                                         error:&playbackError];

        if (self.audioPlayer != nil) {
            self.audioPlayer.delegate = self;

            //Prepare and start playing
            if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]) {
                NSLog(@"Started playing recorded audio");
            } else {
                NSLog(@"Couldn't play recorded audio");
            }

        } else {
            NSLog(@"Failed to create audio player");
        }
    } else {
        NSLog(@"Stopping audio recording failed");
    }
    self.audioRecorder = nil;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
                       successfully:(BOOL)flag{
    if (flag){
        NSLog(@"Audio player stopped correctly.");
    } else {
        NSLog(@"Audio player did not stop correctly.");
    }
    if ([player isEqual:self.audioPlayer]){
        self.audioPlayer = nil;
    } else {
        /* This is not the player */
    }
}

# pragma mark - TableView methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.friends count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    PFUser *user = [self.friends objectAtIndex:indexPath.row];
    cell.textLabel.text = user.username;

    // makes sure checkmark isn't reused if user didn't explicitly select name
    if ([self.recipients containsObject:user.objectId]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

- (void)reset {
    self.audioFile = nil;
}

// User hits "Cancel" button
-(void)exitRecordingScreen {
    [self reset];
    [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
    [self.tabBarController setSelectedIndex:0];
    NSLog(@"exit recording screen button pressed");

}

- (IBAction)send:(id)sender {
    if (self.audioFile == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Please try again." message:@"Please record audio again to share." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [alertView show];
        [self presentViewController:self.audioPicker animated:NO completion:nil];
    } else {
        [self uploadMessage];
        [self.tabBarController setSelectedIndex:0];
    }
}
// Cancel sending recorded file
- (void)cancel:(id)sender {
    fileData = nil;
    [self reset];
    [self.tabBarController setSelectedIndex:0];
}

@end
</code>
Sorry for the wall of text and the length. I'm really stumped.
Comment: I got the same problem, and found no way to solve it gracefully. The thing I learned was DO NOT transition view controllers when recording audio.
Comment: have you tried to set the `edgesForExtendedLayout` property for such scenario yet?
Answer: Solution : You have to reset frame for UITabBarController.
1. Initially frame for UITabBarController will be (0,0,screenWidth,screenHeight).
2. But when this recording red bar appear it becomes (0,20,screenWidth,screenHeight)
3. Here you are supposed to change height for UITabBarController
CGRect changedFrame = objMainTabBarController.view.frame;
  changedFrame.size.height = [UIScreen mainScreen].bounds.size.height - CGRectGetMinY(changedFrame);
  objMainTabBarController.view.frame = changedFrame;
That's it..

Red recording bar distorting view


How to add custom css in ng2-smart-table

Question: I am using angular 2 with ng2-smart-table.
Here is my code.
settings = {
    mode:"external",
    actions:{add:false,position:'right',custom: [{ name: 'View', title: `<i class="fa fa-eye" aria-hidden="true"></i>` }]},
    edit: {
      editButtonContent: '',
      saveButtonContent: '',
      cancelButtonContent:'',
    },
    delete: {
      deleteButtonContent: '',
      confirmDelete: true
    },
    columns: {
       Check:{
        title: "Check",
        type: 'html',
        },
        filter: false
       },
       orderby:{
        title: "Name",
        filter: true
       },
       purchased:{
        title: "Purchased",
        type: 'html',
        },
        filter: false
       },
       shipto:{
        title: "Ship To",
        filter: true
       },
       date:{
        title: "Date",
        filter: true
       },
       total:{
        title: "Total Amount",
        filter: true
       },
       status: {
        title: "Status",
        filter: true
      }
    }
  };

I added custom view icon in table. It works, but how to add custom css in ng2-smart-table?
I tried this
 ng2-smart-table thead > tr > th { background-color: blue; }

But it doesn't work.
Answer: Try this making using of host in order to style the components as view encapsulation is not set.
:host /deep/ ng2-smart-table thead > tr > th  {
        background-color:blue;
}

More info on host and hostcontext link
Comment: What if I need to change style conditionally for some rows?
Comment: @PardeepJain you should checkout the *rowClassFunction*
refer here:- https://akveo.github.io/ng2-smart-table/#/documentation
Answer: use below configuration in the setting object
attr: {
        class: 'table table-bordered'
      },

and
 :host /deep/ ng2-smart-table {
    font-size: 16px;
}

Example :
settings = {
  columns: {
    id: {
      title: 'ID'
    },
    name: {
      title: 'Full Name'
    },
    username: {
      title: 'User Name'
    },
    email: {
      title: 'Email'
    }
  },
attr: {
        class: 'table table-bordered'
      }
};

Answer: I have made the changes in the tables with below Changes in SCSS files
:host /deep/ ng2-smart-table-title a:focus { color: #009ECE; }

:host /deep/ ng2-smart-table thead > tr > th > div { color: #009ECE; }

:host /deep/ td.ng2-smart-actions a {cursor: pointer;color: #009ECE; }

Answer: we can directly use the following I am using the same in my code.
:host>>>table tr th {
  // your css here.
}

Answer: [_nghost-c2] {
    font-size: 1.5rem !important;
}

This worked for me.
Answer: You should use ::ng-deep
::ng-deep ng2-smart-table thead > tr > th { background-color: blue; }
Answer: I am achieving it as follows
:host /deep/ ng2-smart-table { font-size: medium; }


load recent nodes with node_load()

Question: How can I load recent nodes with node_load()?
I used the following code, but I can't edit the links because it creates a list where they are inside it. I want to load the node IDs, and then use node_load() to load each node.
$output = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, n.created FROM {node} n WHERE n.type = '%s' AND n.status = 1 ORDER BY n.created DESC"), story, 0, 10));
print $output;

How is that possible?
Answer: Using only node_load() you cannot get a list of the most recent nodes, as node_load() returns a single node object for the node that matches some criteria; it's not a function that returns a list of nodes.
The faster, but a little inefficient, way to get a list of more recent nodes is to:

Get the list of node IDs associated with the most recent nodes
Call node_load() for each of the node IDs obtained from the first step

You could use code similar to the following one.
   $nodes = array();
   $result = db_query_range("SELECT n.nid FROM {node} n ORDER BY n.created DESC", array(), 0, $number_of_posts);

   while ($nid = db_result($result)) {
     $nodes[] = node_load($nid);
   }

After that code is executes, $nodes will contains the $number_of_poststh recent nodes.
Comment: That works, but it is making the assumption newer nodes have a higher node ID; while that is generally true, it is not necessary true. I would rather join that database table with the node table.
Comment: `SELECT DISTINCT(n.nid) FROM {node} n INNER JOIN {term_node} tn ON n.vid = tn.vid WHERE tn.tid = '1' AND n.status = 1 ORDER BY n.created DESC`
Comment: Really Thanks, I tried this code but I couldn't get the result. maybe I'm missing something. can you make an example of showing list of nodes IDs ?
Comment: Did you define `$number_of_posts`? I tested the code, and it works.
Comment: Yes I did, I think I'm making a mistake somewhere. can you please tell me e.g. how to print all titles? Thanks
Comment: Thanks, I changed `$nodes[]` to `$node` and it works fine now. I modified the code to show nodes from a specific term but it doesn't work. can you please tell me how to do that ?
Comment: That is a different question. `:)`
Comment: I'll try first, If failed I think I should open a new thread :D
Comment: just one thing, Is this code ok? I want to display newer posts first: `SELECT nid FROM term_node WHERE tid = '1' ORDER BY nid DESC`
Comment: Thanks, Actually I had problem with `INNER JOIN` so I tried to use this method. Can you just make an example of what you're saying?

load recent nodes with node_load()


ARM Keil Version 5 [Expected a ')']

Question: I am using the Keil version 5 toolchain to program STM32F0 Series and I am not able to resolve the below-given error.
I am sure I am missing something in it, but having a hard time finding it out.
<code>> ..\Core\Src\max2871.c(169): error:  #18: expected a ")"
      if (((test_data[2] & ((1 << 28) | (1 << 27) | (1 << 26))) >> 26) == 0b110)
</code>
Thanks in Advance.
here is the complete function block:
<code>void plo_check_lock_status(void)
{
    // Saves the status only if the muxout pin is set correctly.
    if (((test_data[2] & ((1 << 28) | (1 << 27) | (1 << 26))) >> 26) == 0b110)
        plo_buff_push(HAL_GPIO_ReadPin(PLO_MUXOUT_GPIO_Port, PLO_MUXOUT_Pin));
    else
        HAL_NVIC_DisableIRQ(EXTI0_1_IRQn);
}
</code>
Comment: is the binary literals syntax (`0bxxx`) supported on this compiler? Replace the `0b110` with `0x6` and see if the error goes away. This syntax is not standard.
Comment: Check the line above this one.
Comment: `if ((test_data[2] >> 26) & 7)` As far as I remember Keil does not support gcc extension `0bxxxx`.
Comment: void plo_check_lock_status(void)
{
    // Saves the status only if the muxout pin is set correctly.
    if (((test_data[2] & ((1 << 28) | (1 << 27) | (1 << 26))) >> 26) == 0b110)
        plo_buff_push(HAL_GPIO_ReadPin(PLO_MUXOUT_GPIO_Port, PLO_MUXOUT_Pin));
    else
        HAL_NVIC_DisableIRQ(EXTI0_1_IRQn);
}
Comment: You are correct, `0bxxx` BIN format was not supported by the compiler, So changed that to HEX format `0x6` and the issue is resolved. Thank you.
Comment: Hint: To find the exact location with a compiler that reports only the line number, you can temporarily split the line into multiple lines, placing each token (symbol, value, operator) on its own line.
Answer: You use if statement but you forgot to used { and }. When you used if statement
you have two ways:

Use if statement by single state and ;
If(...) ...;

Use if statement by multy states and use {}.
If(...){
...
}
Else{
...
}
Good Luck

ARM Keil Version 5 [Expected a ')']