Não consigo utilizar uma variável de uma classe em outra

Question: Estou com dificuldade pra utilizar uma variável de uma outra classe (não é a principal) em uma outra classe. Tenho que fazer um cálculo utilizando a variável convidados da classe Festa na classe Local. Já tentei deixar a variável public, já tentei construtores mas não consigo nada.
PS: ignorem o código feio. É meu primeiro trabalho da disciplina de Programação Orientada a Objetos.
Classe Festa
package principal;

public class Festa {

    private String cpf;
    public int convidados;
    private double custo;
    public String tipoFesta;

    public Festa(String cpf1, int convidados1, double custo1) {
        this.cpf = cpf1;
        this.convidados = convidados1;
        this.custo = custo1;
    }

    public String getCpf() {
        return cpf;
    }
    public void setCpf(String cpf) {
        this.cpf = cpf;
    }
    public int getConvidados() {
        return convidados;
    }
    public void setConvidados(int convidados) {
        this.convidados = convidados;
    }

    public double getCusto() {
        return custo;
    }
    public void setCusto(double custo) {
        this.custo = custo;
    }

    //métodos
    String mostraCpf() {
        return cpf;
    }

    int mostraConvidados(){
        return convidados;
    }

    double mostraCusto() {
        return custo;
    }

    public String classificaFesta() {
        if(convidados<300 && custo<15000) {
            tipoFesta = "Festa junina";
        } else {
            if(convidados<300 && custo>=15000) {
                tipoFesta = "Aniversário";
            } else {
                if(custo<15000) {
                    tipoFesta = "Formatura";
                } else {
                    tipoFesta = "Casamento";
                }
            }
        }
        return tipoFesta;
    }
}

Classe Local
package principal;

public class Local {

    private double largura;
    private double comprimento;
    private int qtdeConv;

    public Local(double largura, double comprimento) {
        this.largura = largura;
        this.comprimento = comprimento;
    }

    public double getLargura() {
        return largura;
    }

    public void setLargura(double largura) {
        this.largura = largura;
    }

    public double getComprimento() {
        return comprimento;
    }

    public void setComprimento(double comprimento) {
        this.comprimento = comprimento;
    }

    double mostraLargura(){
        return largura;
    }

    double mostraComprimento() {
        return comprimento;
    }

    public String possivelLocal() { //4 pessoas = 3m² -> proporção de 1.333...
        double tamanho = largura*comprimento;
        double proporcao = 4/3;

        double propConvidados = convidados/tamanho; // ..............
        String acomoda;

        if(propConvidados <= proporcao) {
            acomoda = "Sim";
        } else {
            acomoda = "Não";
        }
        return acomoda;
    }

}

Classe Principal
package principal;

public class Principal {

    public int convidadoscalculo;

    public static void main(String[] args) {

        Festa f1 = new Festa("123.456.789-10", 300, 15000);
        Local l1 = new Local(10,8);

        String cpf_1 = f1.getCpf();
        int qtde = f1.getConvidados();
        double valor = f1.getCusto();

        double larg = l1.getLargura();
        double comp = l1.getComprimento();

        String classificaFesta = f1.classificaFesta();

        System.out.println("CPF do contratante: "+cpf_1);
        System.out.println("Festa para "+qtde+" convidados.");
        System.out.println("Tendo um valor de "+valor+ " reais");
        System.out.println("Essa é uma festa de tipo: "+ classificaFesta +".");

    }

}

Answer: para que você possa usar a variável convidados na classe Local deves primeiro criar um construtor vazio na classe Festa public Festa(){} e depois, dentro da classe Local criar uma instância da classe Festa, assim: Festa f = new Festa();
Depois, na linha do cálculo faça propConvidados = f.convidados/tamanho;
Comment: Muito obrigado, Márcia! Deu certo aqui! :)
Answer: essa dificuldade que você está enfrentando é muito conhecida e um modo de solucionar é aplicar a famosa injeção de dependência. Existem 3 tipos de Injeção de Dependência: injeção de construtor; injeção pelo setter e injeção de interface.
O mais usual é através de construtor, mas no seu caso vamos usar injeção pelo setter. Assim, vamos informar a classe Local quantos convidados existem através de um setter, e dessa forma, permitindo a classe Local trabalhar corretamente.
Para isso adicione o seguinte:
Classe local:
public void setQtdeConv(int qtdeConv){
    this.qtdeConv = qtdeConv;
}

Classe principal:
l1.setQtdeConv(f1.getConvidados());

Dessa forma, o objeto l1 agora possuí a quantidade de convidados que o objeto f1 têm, e conseguirá fazer o método possivelLocal().


Open XML SDK v2.0 Performance issue when deleting a first row in 20,000+ rows Excel file

Question: Do anyone come across a performance issue when deleting a first row in a 20,000+ rows Excel file using OpenXML SDK v2.0?
I am using the delete row coding suggested in the Open XML SDK document. It takes me several minutes just to delete the first row using Open XML SDK, but it only takes just a second in Excel applicaton.
I eventually found out that the bottle-neck is actually on the bubble-up approach in dealing with row deletion. There are many rows updating after the deleted row. So in my case, there are around 20,000 rows to be updated, shifting up the data row by row.
I wonder if there is any faster way to do the row deletion.
Do anybody have an idea?
Answer: Well, the bad news here is: yep, that's the way it is.
You may get slightly better performance moving outside of the SDK itself into System.IO.Packaging and just creating an IEnumerable/List in like Linq-to-XML of all the rows, copy that to a new IEnumerable/List without the first row, rewrite the r attribute of <row r="?"/> to be it's place in the index, and the write that back inside <sheetData/> over existing children.
You'd need to kind of do the same for any strings in the sharedStrings.xml file - i.e. removing the <ssi>.<si> elements that were in the row that was deleted, but in this case they are now implicitly indexed, so you'd be able to get away with just outright removing them.
Answer: The approach of unzipping the file, manipulating it and repacking it is very error-prune.
How about this: If you say, that it works fine in Excel: Have you tried to use the Interop? This starts a new instance of Excel (either visible or invisible), then you can open the File, delete the line, save and close the application again.
using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
public void OpenAndCloseExcel()
{
    Excel.Application excelApp = new Excel.Application();
    // Open Workbook, open Worksheet, delete line, Save
    excelApp.Quit();
}

The Range-object is qualified for many purposes. Also for deleting elements. Have a look at: MSDN Range-Description. One more hint: Interop uses Excel, so all Objects have to be adressed with a 1-based index!
For more resources take a look at this StackOverflow-thread.


Meta-analysis: is there a way of including dependent effect sizes without averaging across them

Question: I'm running a meta-analysis with a binary outcome (succeed/fail). I am primarily interested on the effect of predictors related to the study (e.g. age of participants, type of task) on the binary outcome, rather than the actual outcome of the study (that is i'm doing a meta-regression).
In some cases studies report multiple outcomes from the same population. The intro meta-analysis textbooks (e.g. Bornstein, 2009) only give information about how to find the weighted average of multiple effect sizes and to use these.
However, I am also interested in the different outcomes because they provide interesting (different) information. I can find lots of papers on the best way to find the average of multiple dependent effect sizes, however the only guide to this (in Cooper's 2009 handbook) is pretty undecipherable for me. Can anyone explain how to do this? If i use the same population twice, can i just divide the weight given to the study by the number of times it is included in the meta-analysis?
I've read about incorporating a third level into the meta-analysis, however in most cases i've only got one observation from a single population so i'm not sure if that would work in that case.
Thanks
Comment: @Wolfgang: I recommended those papers to the OP mostly as nice general tutorials on the topic, namely determining and reporting effect sizes (ES) in context of meta-analysis (hence the comment). They also discuss alternative to Cohen's $d$ ES measures as well as aspects of determining ES for some research designs. Finally, the paper by Durlak discusses specifics of determining and reporting ES for cases of dichotomous outcomes, which corresponds to the OP's mention of "binary outcome".
Comment: I highly recommend reading both papers, referenced in [my answer](http://stats.stackexchange.com/a/143882/31372) to a related question.
Comment: Just to clarify: You are analyzing data from individual groups, correct? So, the observed outcomes are proportions (or some transformation thereof), not some contrast between two groups, such as (log) odds ratios.
Comment: @AleksandrBlekh I skimmed through both articles you reference in that answer, but didn't find anything that addresses the problem the OP is asking about -- or did I miss the relevant part(s)?
Comment: @Wolfgang: I was curious enough to visit your website. Needless to say that I am very impressed. If I knew that I'm replying to the author of the `metafor` package, perhaps, I'd make my comment shorter to not look that stupid :-).
Comment: I'll have a look at the papers - i don't think i've read the durlak one before. To clarify, the outcome is just a proportion. I am mostly interested in factors of the study which affect the proportion observed, so i'm more interested in the covariates then the actual weighted average effect size.
Comment: @AleksandrBlekh The articles are quite useful as general tutorials on effect size measures, for sure. And don't worry about the detailed response -- it was useful!
Comment: @Wolfgang: I appreciate your kind words!
Answer: If I understand your description correctly, you have a data structure that looks like this:
   study group obs ni xi mean.age
1      1     1   1 32  6     24.6
2      1     2   1 28  6     37.7
3      1     3   1 38 20     23.5
4      2     1   1 22  4     21.8
5      2     1   2 22  9     21.8
6      2     2   1 46 21     26.2
7      2     2   2 46 21     26.2
8      3     1   1 25  8     22.1
9      4     1   1 28 15     25.3
10     5     1   1 34 14     24.2
11     5     2   1 21  3     33.8
12     6     1   1 37  2     27.9
13     6     1   2 37  5     27.9
14     6     1   3 37 13     27.9
15     7     1   1 33  7     22.9
16     8     1   1 51  9     24.4
17     9     1   1 43 11     24.1
18     9     1   2 43 10     24.1
19    10     1   1 43 11     26.3
20    10     2   1 30 14     22.6

So, you have multiple studies, within studies there may be one or more groups, and for some groups you have multiple observations. For example, study 1 included 3 different groups, each observed once. Study 2 included 2 different groups, each observed twice. And so on. Each observation consists of the number of subjects that pass a task (xi) and the corresponding group size (ni).
And you have some predictors/covariates, such as the mean age of the group (so a variable at the group level) and possibly also variables at the study and/or observation level. And the goal is to examine how these predictors/covariates are related to the chances of passing.
The first major issue are groups that are observed more than once. What ultimately gave rise to the data are subject-level observations -- in other words, the same subjects were assessed more than once. And the chances of a particular subject passing under multiple assessments are likely to be correlated. So, to properly account for such dependence, you really would need the subject-level data. A standard approach to account for the dependent observations would then be to add random effects at the subject level to the model.
But it is probably safe to assume that you do not have the subject-level data, that is, you have data of the form shown above. So, for example, you do not know for the first group of study 2 whether the 4 subjects that passed under the first assessment are part of the 9 subjects that passed under the second assessment and so on.
So, the next best thing you can do would be to add random effects at the group level to the model, as a very rough way of accounting for dependence in multiple observations at the group level. In addition, you would probably want to add random effects at the study level and also at the observation level -- the latter is the standard way of accounting for heterogeneity in meta-analytic data.
You did not specify what outcome measure you really want to use for the meta-analysis. It is probably not a good idea to analyze the proportions directly. The more typical approach is to use logit-transformed proportions (log odds) for the meta-analysis.
You also did not mention anything about software, but I'll go with R from now on. So, to follow along, you can recreate the dataset above in R with:
dat <- structure(list(study = c(1, 1, 1, 2, 2, 2, 2, 3, 4, 5, 5, 6,
6, 6, 7, 8, 9, 9, 10, 10), group = c(1, 2, 3, 1, 1, 2, 2, 1,
1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2), obs = c(1L, 1L, 1L, 1L,
2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 3L, 1L, 1L, 1L, 2L, 1L, 1L
), ni = c(32, 28, 38, 22, 22, 46, 46, 25, 28, 34, 21, 37, 37,
37, 33, 51, 43, 43, 43, 30), xi = c(6L, 6L, 20L, 4L, 9L, 21L,
21L, 8L, 15L, 14L, 3L, 2L, 5L, 13L, 7L, 9L, 11L, 10L, 11L, 14L
), mean.age = c(24.6, 37.7, 23.5, 21.8, 21.8, 26.2, 26.2, 22.1,
25.3, 24.2, 33.8, 27.9, 27.9, 27.9, 22.9, 24.4, 24.1, 24.1, 26.3,
22.6)), .Names = c("study", "group", "obs", "ni", "xi", "mean.age"
), row.names = c(NA, -20L), class = "data.frame")

(just copy-paste to R). Next, install and load the metafor package:
install.packages("metafor")
library(metafor)

Next, we use the escalc() command to compute the logit-transformed proportions and corresponding sampling variances:
dat <- escalc(measure="PLO", xi=xi, ni=ni, data=dat)

The dataset now looks like this:
   study group obs ni xi mean.age      yi     vi
1      1     1   1 32  6     24.6 -1.4663 0.2051
2      1     2   1 28  6     37.7 -1.2993 0.2121
3      1     3   1 38 20     23.5  0.1054 0.1056
.      .     .   .  .  .        .       .      .
20    10     2   1 30 14     22.6 -0.1335 0.1339

Variables yi and vi are the logit-transformed proportions and corresponding sampling variances. You can then fit a model with random effects at the study, group, and observations level to these data with:
res <- rma.mv(yi, vi, random = ~ 1 | study/group/obs, data=dat)
res

The output:
Multivariate Meta-Analysis Model (k = 20; method: REML)

Variance Components:

            estim    sqrt  nlvls  fixed           factor
sigma^2.1  0.0000  0.0005     10     no            study
sigma^2.2  0.1395  0.3735     15     no      study/group
sigma^2.3  0.1643  0.4053     20     no  study/group/obs

Test for Heterogeneity:
Q(df = 19) = 56.9399, p-val < .0001

Model Results:

estimate       se     zval     pval    ci.lb    ci.ub
 -0.8402   0.1638  -5.1302   <.0001  -1.1612  -0.5192      ***

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So, you get estimates of the variances of the random effects at each level, the usual test for heterogeneity, and the estimated average log odds (the estimate) with corresponding SE, z-value, p-value, and CI bounds. Most of the heterogeneity is found at the observation level, followed by group level, and next to none at the study level. For easier interpretation, you can back-transform the estimated average log odds by applying the inverse logit transformation:
predict(res, transf=transf.ilogit)

This yields:
   pred  ci.lb  ci.ub  cr.lb  cr.ub
 0.3015 0.2384 0.3730 0.1227 0.5712

So, the estimated chances of passing are on average around 30% (with 95% CI: 24% to 37%). The next two values are the bounds of a 95% credibility/prediction interval for the true passing chance within an individual group.
This is a pretty complex model and I hope you have more data to work with than my little made-up dataset above. At any rate, you will want to check that all variance components of the model are actually identifiable. You can do this by profiling the restricted log-likelihood for each component. This can be done with:
par(mfrow=c(3,1))
profile(res, sigma2=1, xlim=c(0,.6))
profile(res, sigma2=2, xlim=c(0,.6))
profile(res, sigma2=3, xlim=c(0,.6))

For these data, this will look as follows (you may have to adjust the x-axis limits depending on your results):

Most importantly, all profiles are peaked at the respective parameter estimates, which is what you hope to see.
You can add covariate/predictors to the model via the mods argument. For example, to add the mean age of the subjects to the model, you would use:
res <- rma.mv(yi, vi, mods = ~ mean.age, random = ~ 1 | study/group/obs, data=dat)
res

(output not shown).
You can also take another approach with analyzing these data. In particular, you can use a mixed-effects logistic regression model, using the same random effects structure. The lme4 package will allow you to fit such a model:
install.packages("lme4")
library(lme4)
res <- glmer(cbind(xi,ni-xi) ~ 1 + (1 | study/group/obs), family='binomial', data=dat)
summary(res)

The results are:
Generalized linear mixed model fit by maximum likelihood (Laplace
  Approximation) [glmerMod]
 Family: binomial  ( logit )
Formula: cbind(xi, ni - xi) ~ 1 + (1 | study/group/obs)
   Data: dat

     AIC      BIC   logLik deviance df.resid
   125.3    129.3    -58.6    117.3       16

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.4216 -0.4647 -0.1065  0.4460  0.8126

Random effects:
 Groups            Name        Variance  Std.Dev.
 obs:(group:study) (Intercept) 2.256e-01 4.750e-01
 group:study       (Intercept) 1.145e-01 3.384e-01
 study             (Intercept) 2.981e-09 5.459e-05
Number of obs: 20, groups:  obs:(group:study), 20; group:study, 15; study, 10

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -0.8924     0.1693   -5.27 1.36e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(if you first set options(scipen=10), you won't get the scientific notation, which you may find easier to read). At any rate, the results are quite similar and can be interpreted analogously.
Final note: Again, this approach is only an approximation as the ideal analysis would make use of the subject-level data. However, averaging multiple observations (proportions, log odds, or whatever your outcome measure) for the same group is certainly even less appropriate and wastes a lot of information. So, my suggestion would be to go with the type of analysis described above and just address this issue as a limitation in your discussion.
Comment: I should add: If you want to replicate those analyses, you will have to download the development version of ``metafor`` (see here: http://www.metafor-project.org/doku.php/installation#development_version) or wait a day or two before the next version becomes available via CRAN (I just submitted a new version).
Comment: Excellent, comprehensive answer, as expected (+1).
Comment: Thanks alot. R is perfect too (i'm not great at it, but i know the basics), and i've playing around with metafor before, I wasn't really hugely aware of this kind of analysis before though. Is this a three-level meta-analysis (as described by this paper? http://docdro.id/zrnq). I'll do some more homework on it. Your spot on with how my data looks like btw!
Comment: Does the structure of the data matter? I think i've read that multi-level analysis works best when clusters have more than 5 observations. When I've finished i should have around 40 papers, with around 150 unique groups, with around 300 observations from those groups. Most groups will only have one observation, but some will have 1-5 observations (typically 2/3).
Comment: The more observations you have for a level, themore precisely the corresponding variance component can be estimated. But with 40 papers, 150 groups, and 300 observations, you should be okay. And yes, the idea is similar to the three-level model described by Mike Cheung in that paper, except that this is now a four-level model. Another paper that describes the three-level model is [Konstantopoulos (2011)](http://onlinelibrary.wiley.com/doi/10.1002/jrsm.35/abstract), which may be another useful reference.
Comment: I'm not going to examine paper-level clustering, so i'll stick to three-level. So it is possible to include a third level, when most groups will only have one effect size per group, some having 2-6 effect sizes?
Comment: Yes, that is possible. You can use profile plots as I have shown in my answer to check whether all variance components are in fact estimable.
Comment: Cool. I had another (unrelated question). In the case where i get outcomes where either no children pass the task (0/N) or all the children pass the task (N/N), do i have to exclude these effect sizes because i cannot calculate the variance when there is no variation in the sample?
Comment: If you use ``escalc()`` (followed by ``rma.mv()``), you will notice that it does give you a logit-transformed proportion and corresponding sampling variance for studies with no all all events/cases. It does so by applying a continuity correction (adding 1/2 to the number of cases and non-cases). This is usually an acceptable way of dealing with such studies, except if this happens a lot (i.e., the outcome is either very rare or very common). In that case, the logistic regression approach is probably preferable (which also makes use of the information from such studies).
Comment: Thanks alot, i'll have another look. I still haven't run the above analysis, im still gathering data for meta-analysis (I've currently got data on around 10,000 children).
Comment: hi. For the model predicting the logit-transformed %, with an intercept and a moderating variable of age, i am very interested in reporting the age at which children perform at a particular log(odds) value. It is simple enough to calculate this given the output, however do you know what i could do to calculate a confidence interval for the value that a moderator (age) takes at a particular log(odds) value?


Drush Launcher does not work

Question: Drush Launcher gives an error in an environment updated to Drupal 10.2.
The environment is Drupal 10.2, PHP 8.2, Drush 12.4, Drush Launcher 0.10.2.
Specifically, I get the following error
<code>[user@host drupal]$ drush status
The Drush launcher could not find a local Drush in your Drupal site.
Please add Drush with Composer to your project.
Run 'cd "/var/www/drupal" && composer require drush/drush'
</code>
However, Drush is installed by composer and is also listed in composer.json.
I have updated from Drupal 9, but I can no longer run the Drush command with only "drush".
I would like to be able to run it with "drush" instead of "vendor/bin/drush".
./bashrc or any other method other than passing it through $PATH, please.
The following from Drupal 9 is ideal.
<code>[user@host drupal]$ drush status
...
Drush script     : /usr/local/bin/drush
...
</code>
Please help.
Comment: `This repository has been archived by the owner on Aug 19, 2023. It is now read-only.` https://github.com/drush-ops/drush-launcher
Comment: Check some alternatives here: https://github.com/drush-ops/drush-launcher/issues/105.
Comment: I changed my mind about closing this question. It has a factual answer.
Comment: So Drush Launcher is not compatible with Drupal 10 and Drush 12, so there is no other way but to use it through $PATH?
Comment: Incorrect. Read the defunct project's page for alternatives, as I wrote in the answer.
Answer: drush-launcher does not work because it is unmaintained. See its archived project page for alternatives.

Drush Launcher does not work


Why is the first term of this series 1 and not 0? (I have the answer but don't understand how to get there)

Question: $$s=\sum_{i=0}^4 b_i(y)u^i$$
I'm reading a paper where someone has provided the expression above, a fourth-order power series in y and u. Each term is expanded and the first term is
$$b_0(y) = 1$$
I don't understand how it isn't zero because s should be zero when u is zero for physical reasons.
When I use Python's curve_fit to solve this, I get the right answer--s is $0$ when u is $0$.  It has been a long time since I learned about summation and there's something I'm not understanding about what's going on.  If anyone could please direct me, I would be grateful.
Comment: @TorstenSchoeneberg, thank you for your help!  Wait, it's as simple as u^0 = 1?  (u is never 0).  Please provide an answer so I can give you credit.  Very embarrassed.
Answer: If $u$ is not $0$, then $u^0=1$. So the "first" (or rather "zeroth") term of that sum is $b_0(y)$.


Incremental commit while using execute immediate when table name and column name are dynamic

Question: I've the need to update a few tables. The tables and columns to be updated will be fetched from another table. So my update statement in the procedure looks like this
EXECUTE IMMEDIATE
        'UPDATE '
     || In_owner
     || '.'
     || In_table_name
     || ' upd_tbl '
     || ' SET '
     || In_sql_stmt_col_list
     || ' WHERE '
     || In_sql_stmt_where_clause;

As you can see, table name, the set clause and the where clause are all dynamically built. What I want to do now is perform a commit after every n records. How do I do that?
Comment: Why do you want to commit after every n records?
Comment: Did a google search for you, and what do you know. https://community.oracle.com/thread/937361?tstart=0
Comment: Do you mean that for that *single* update statement, you want whatever rows it updates to be committed in batches?  Not only is it not possible without rewriting the `update` statement, but it's a bad idea.  Why would you want to break the transactionality of the update?
Comment: @user3224907 I know how I would do it for an update statement but I want to know how I can do it when my update is done through a execute immediate.
Comment: Simply make `COMMIT;`. `EXECUTE IMMEDIATE 'COMMIT';` will also work, but there is absolutely no need to do it with dynamic SQL
Comment: @sstan This procedure will be a part of the package which we are building to scramble data being brought from production to development. I need to scramble sensitive information and the database that we will be using to do this won't be a very strong to handle huge updates. Also, we want to be able to run multiple updates in parallel so we are worried about the rollback segments and redo log buffer cache.
Answer: Assuming that you are able to recognize updated rows from not updated you can try to fit the below sample to your case.
The nbatchsize is number of rows that you want to commit each time.
The i is the number of rows that were updated in the last loop.
The updates are looped by while until number of updated rows is lower than your nbatchsize.
Of course it would only work when you are able to recognize already updated rows  from not updated ones.
You can use for that In_sql_stmt_col_list if you don't have any lastupdateon column.
declare
nbatchsize number := 10;
i number := nbatchsize;
begin

while i >= nbatchsize
loop

EXECUTE IMMEDIATE '
update
Table
set lastupdateon = sysdate
where
lastupdateon < sysdate -1
and rownum <= :1 ' using nbatchsize;

 i := sql%rowcount;

commit;
dbms_output.put_line(i);

end loop;

end;


Remover objetos duplicados de List

Question: Galera é o seguinte, eu tenho uma classe modelo com atributos que armazenam dados retornados do banco de dados. Por exemplo:
public class RelacaoTransformacao {
    /** ID do registro no banco de dados. */
    private long id;
    /** Indica se o teste já foi concluído. */
    private boolean concluido;
    /** O valor do teste. */
    private double valor;
    // ...O restante do código.
}

Tendo o código abaixo como exemplo:
// Percorre o cursor obtendo todos os dados e criando um objeto com os dados retornados.
            while ( result.moveToNext() ) {
                long id = result.getLong( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_ID.texto ) );
                boolean concluido = result.getInt( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_CONCLUIDO.texto ) ) > 0 ;
                double valor = result.getDouble( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_VALOR.texto ) );
                int polaridade = result.getInt( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_POLARIDADE.texto ) );
                String observacao = result.getString( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_OBSERVACAO.texto ) );
                long idPrimario = result.getLong( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_FK_ENROLAMENTO_TCTP_ID1.texto ) );
                long idSecundario = result.getLong( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_FK_ENROLAMENTO_TCTP_ID2.texto ) );
                String primario = result.getString( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.EnrolamentoTcTp.COLUNA_ENROLAMENTO.texto ) );
                primario += String.valueOf( result.getInt( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.EnrolamentoTcTp.COLUNA_NUMERO_ENROLAMENTO.texto ) ) );

                RelacaoTransformacao relacaoTransformacao = new RelacaoTransformacao( id, concluido, valor, polaridade, observacao, idPrimario, idSecundario, primario, null );
                // Adiciona o objeto enrolamento a lista de enrolamentos
                listRelacaoTransformacao.add( relacaoTransformacao );
            }

Eu sempre vou ter dois objetos repetidos na minha lista pelo atributo ID, isso devido a minha busca no banco de dados (Não preciso explicar essa busca, apenas entenda que eu realmente preciso retornar dois registros repetidos, porque em uma coluna do registro repetido o valor vai ser diferente e eu preciso pegar este valor). Como eu faço para obter um desses objetos repetidos pelo ID e então removê-lo da lista?
Comment: Qual critério você usa para saber qual dos objetos você vai remover?
Comment: Refraseando a pergunta do @Math (que pode ser interpretada como perguntando sobre o critério de duplicação, que é dois objetos terem o mesmo ID): supondo que haja dois objetos com o mesmo ID, qual dos dois deve ser removido? Qualquer um?
Comment: Não pode ser qualquer um. O que deve ser removido deve ser o segundo objeto. Só que antes de remover eu vou pegar um certo atributo dele, e setar no primeiro objeto, então depois disso posso removê-lo.
Answer: Use uma classe que implemente um conjunto (Set), como TreeSet. Forneça um Comparator no construtor que use o ID.
As classes que implementam Set somente permitem elementos distintos, usando como parâmetro os campos usados no Comparator.
Comment: @LucasSantos Se você quer obter dados dos elementos repetidos, então terá que implementar uma solução como a do @Math. Entretanto, o algoritmo dele está com complexidade O(n²), isto é, ele compara todos com todos. Isso poderia ser otimizado para O(log(n)) usando duas variáveis `i` e `j` nos for's e sempre iniciando `j` com `i + 1`.
Comment: @LucasSantos Para 6 elementos não vale a pena otimizar o algoritmo.
Comment: Se a ordem dos elementos na lista não importar, essa é a solução mais simples. Inserir elementos em um `Set` (conjunto), no qual elementos não se repetem.
Comment: @utluiz, com base no meu comentário na minha pergunta que digo que o objeto a ser removido sempre será o segundo e eu preciso pegar um atributo do mesmo antes de removê-lo, qual a melhor implementação para o meu problema? A sua ou a do usuário Math. Do seu ponto de vista.
Comment: @Piovezan, um conjunto set não deixa os elementos ordenados? Nem mesmo se eu inseri-los dentro do conjunto na ordem?
Comment: @LucasSantos Se for um [LinkedHashSet](http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html), pode-se iterar pelos elementos na ordem em que foram inseridos.
Comment: Valeu Piovezan. @utluiz obrigado pela dica e resposta, eu entendi o que você falou mas pergunto. Isso fará muita diferença no desempenho? Digo isso porque a lista provavelmente terá apenas 6 elementos em ocasiões raras. Se são 6 elementos então temos 6x2 porque tem as repetições. Aconselha mesmo assim eu usar `i` e `j` ao invés do `for each`?
Comment: Muito obrigado pela resposta @utluiz e @ Piovezan. Como a resposta que vou utilizar será a do @ Math , entao, vou marcá-la como aceita. Mas se pudesse marcava as duas pois ambas me acrescentaram conhecimento.
Comment: @LucasSantos Sem problemas, o importante é você ter entendido.
Comment: @utluiz realmente tive que fazer como você disse por aqui em comentário, referente a otimização...Você disse: `Isso poderia ser otimizado para O(log(n)) usando duas variáveis i e j nos for's e sempre iniciando j com i + 1`. Realmente tive que fazer assim e acrescentar um pouco mais para melhorar a otimização mais ainda. E também não foi só questão de otimização, do jeito do @Math ficou com um erro de lógica que não deu certo no meu caso. A resposta dele foi editada com o código correto.
Answer: Você pode fazer um for dentro do outro, percorrendo a lista e armazenando em variáveis diferentes cada objeto da lista, daí você compara os id, se o id for o mesmo e não for o mesmo objeto você entra na sua lógica de escolher qual dos dois deve ser removido.
Adicione esses elementos que devem ser removidos em uma lista a parte para removê-los após a verificação dentro dos fors.
Exemplo:
public class LucasSantos {
    public static void main(String[] args) {
        List<RelacaoTransformacao> listRelacaoTransformacao = new ArrayList<>();
        List<RelacaoTransformacao> listEliminar = new ArrayList<>();
        listRelacaoTransformacao.add(new RelacaoTransformacao(1, true, 2));
        listRelacaoTransformacao.add(new RelacaoTransformacao(1, true, 5));
        listRelacaoTransformacao.add(new RelacaoTransformacao(2, true, 5));
        listRelacaoTransformacao.add(new RelacaoTransformacao(2, true, 1));
        System.out.println("Antes");
        for(RelacaoTransformacao r: listRelacaoTransformacao) {
            System.out.println(r);
        }

        // Faz um for percorrendo os itens da lista. Para cada item da lista percorrido, faz um outro for para percorrer todos os itens da lista novamente (Pulando o primeiro item do for externo)
        // para verificar qual objeto tem id igual ao objeto do for mais externo e se são objetos diferentes.
        for ( int i = 0; i < listRelacaoTransformacao.size(); i++ ) {
            for ( int j = i + 1; j < listRelacaoTransformacao.size(); j++ ) {
                // Se os objetos tiverem o mesmo id mas forem objetos diferentes, entao pegamos o campo primario do segundo objeto e o colocamos no campo secundario da primeiro objeto.
                // Adicionamos o segundo objeto na lista para eliminação de objetos repetidos.
                if ( listRelacaoTransformacao.get( i ).getId() == listRelacaoTransformacao.get( j ).getId() &&
                    !( ( (Object) listRelacaoTransformacao.get( i ) ).equals( listRelacaoTransformacao.get( j ) ) )  ) {

                    // Aqui você faz o que quiser.
                    i++; // Incrementa i em 1 para evitar verificações desnecessárias.
                    break;
                }
            }
        }
        //elimina todos os elementos que foram marcados para remoção
        listRelacaoTransformacao.removeAll(listEliminar);
        System.out.println("Depois");
        for(RelacaoTransformacao r: listRelacaoTransformacao) {
            System.out.println(r);
        }
    }
}

Saída:

Antes
  RelacaoTransformacao [id=1, concluido=true, valor=2.0]
  RelacaoTransformacao [id=1, concluido=true, valor=5.0]
  RelacaoTransformacao [id=2, concluido=true, valor=5.0]
  RelacaoTransformacao [id=2, concluido=true, valor=1.0]
  RelacaoTransformacao [id=3, concluido=true, valor=2.0]
  Depois
  RelacaoTransformacao [id=1, concluido=true, valor=2.0]
  RelacaoTransformacao [id=2, concluido=true, valor=1.0]

Observação: sempre que fizer comparações de objetos sobrescreva o método equals(), e se você estiver trabalhando com Set sobrescreva também o hashCode(). A interface List não usa o método hashCode() entretanto a própria documentação recomenda você sempre sobrescreve-lo quando sobrescrever o equals. A documentação da classe Object diz:

equals(): Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Em tradução livre:

equals(): Note que é geralmente necessário sobrescrever o método hashCode sempre que esse método for sobrescrito, pois assim mantém o contrato do método hashCode, que diz que objetos iguais devem ter hash codes iguais.

Mais informações do que é o método hashCode() :
Qual a importância de implementar o método hashCode em Java?
Documentação: equals(), Class Object - Java SE 7
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54264/discussion-on-answer-by-math-remover-objetos-duplicados-de-listminhaclasse)

Remover objetos duplicados de List


correlation implies dependency?

Question: In this talk from prof Bernhard https://youtu.be/4qc28RA7HLQ?t=88
he only sees/shows linear correlation, and he assumes there is 'dependency'?
Correct me if wrong but correlation does not imply 'dependency' so why is he  implying it?
https://youtu.be/4qc28RA7HLQ?t=88
Comment: Correlation does not imply *causality*, but dependence / independence is a different concept.
Answer: From purely probabilistic perspective, if two random variables are correlated, they can't be statistically independent, i.e. $\operatorname{cov}(X,Y)\neq0\rightarrow X\not\perp Y$. But, if the correlation/covariance is $0$, those variables can still be dependent. So, presence of correlation implies dependence between random variables; but the presence of dependence doesn't imply correlation.

correlation implies dependency?


A certain elliptic estimate I have trouble locating in books

Question: On p. 33 of these lecture notes, we deduce that:
$$-\Delta q=\operatorname{div}\operatorname{div}u$$
on the $n$-d torus $\mathbb T^n$. The deduction is then made that:
$$\|q\|_{L^2(\mathbb T^n\times(0,T))}\leq\|u\|_{L^2(\mathbb T^n\times(0,T))}.$$
Apart from suspecting this should be a $\lesssim$, that is there is a missing constant on the RHS, how would one prove this? I was pointed to Gilbarg-Trudinger and to Evans, but neither seems to have an esimate that produces this one in the respective section about elliptic regularity estimates. Am I missing something, is the estimate I need somewhere else in those books, or anyway, what fact guarantees that deduction holds?
Answer: The article is working on $\mathbb T^n$, a torus, so we can use Fourier serieses. Write:
\begin{align*}
q={}&\sum_{\mathbb Z^n}c_ke^{ik\cdot x} \\
u={}&\sum_{i,j}\sum_{\mathbb Z^n}d_k^{(i,j)}e^{ik\cdot x}e_i\otimes e_j.
\end{align*}
The equation $-\Delta q=\operatorname{div}\operatorname{div}u$ then reads:
$$-k^2c_k=\sum_{i,j}k_ik_jd_k^{(i,j)}\qquad\qquad\forall k.$$
Divide by $-k^2$ and square:
$$c_k^2=\sum_{i_1,j_1,i_2,j_2}\frac{k_{i_1}k_{j_1}k_{i_2}k_{j_2}}{k^4}d_k^{(i_1,j_1)}d_k^{(i_2,j_2)}.$$
Taking modulus on the RHS, the fraction is at most 1, then we use a Cauchy-Schwartz type inequality to get:
$$c_k^2\leq\sqrt{\sum_{i_1,j_1,i_2,j_2}d_k^{(i_1,j_1),2}}\sqrt{\sum_{i_1,j_1,i_2,j_2}d_k^{(i_2,j_2),2}}=n^4\sum_{i,j}(d_k^{i,j})^2\leq C^2n^4\|u\|_{L^2}^2.$$
where I used that, whatever matrix norm I pick for my $\|u\|_{L^2}$, there is $C$ such that $C|u|\geq\sqrt{\sum_{i,j}(d_k^{i,j})^2}$ by equivalence of norms in finite dimension. Summing over $k$, we get exactly the desired estimate.


Unable to push Swift code to Heroku because of "GIT_DISCOVERY_ACROSS_FILESYSTEM not being set"

Question: I am trying to push my Swift code to Heroku via Git. This is the error I am getting:
remote: fatal: not a git repository (or any parent up to mount point /)
remote: Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).

So far I have tried the following:
git init
git remote add heroku [URL]
export GIT_DISCOVERY_ACROSS_FILESYSTEM=1
heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1 --remote origin

But still when I try to push code to master, it fails. This is the command I am using to push code:
git push heroku master

Answer: Double check, after your git init (I would prefer git init . to be sure), that you have indeed a .git/ subfolder created in your current folder.
As long as you don't see it, you would get that error message.


What are the best commands to troubleshoot Workload Scheduler connectivity issues

Question: What networking operating system commands are helpful when troubleshooting unlinking issues and no connections between Workload Scheduler Master, Domain Managers and Fault Tolerant Agents?
Answer: 1) Ping
The most commonly used network tool is the ping utility. This utility is used to provide a basic connectivity test between the requesting host and a destination host. This is done by using the Internet Control Message Protocol (ICMP) which has the ability to send an echo packet to a destination host and a mechanism to listen for a response from this host. Simply stated, if the requesting host receives a response from the destination host, this host is reachable. This utility is commonly used to provide a basic picture of where a specific networking problem may exist. For example, if an Internet connection is down at an office, the ping utility can be used to figure out whether the problem exists within the office or within the network of the Internet provider.
Example
ping IP or Hostname
C:\Users\IBM_ADMIN>ping www.ibm.com

Pinging e2874.dscx.akamaiedge.net   [184.108.40.206] with 32 bytes of data:

Reply from 22.214.171.124: bytes=32 time=55ms TTL=56
Reply from 126.96.36.199: bytes=32 time=56ms TTL=56
Reply from 18.104.22.168: bytes=32 time=55ms TTL=56
Reply from 22.214.171.124: bytes=32 time=115ms TTL=56

Ping statistics for 188.8.131.52:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 55ms, Maximum = 115ms, Average = 70ms

2) Tracert / traceroute
Typically, once the ping utility has been used to determine basic connectivity, the tracert/traceroute utility can used to determine more specific information about the path to the destination host including the route the packet takes and the response time of these intermediate hosts. The tracert utility and traceroute utilities perform the same function but operate on different operating systems, Tracert for Windows machines and traceroute for Linux/*nix based machines.
Example:
tracert www.ibm.com
C:\Users\IBM_ADMIN>tracert Rolltide.austin.ibm.com

Tracing route to Rolltide.austin.ibm.com [184.108.40.206]
over a maximum of 30 hops:

  1    66 ms    62 ms    59 ms  pok-vid-31a-v3037.pok.ibm.com [18.104.22.168]
  2     *       63 ms    66 ms  reserved-9-56-3-3.pok.ibm.com [126.96.36.199]
  3    57 ms    64 ms    64 ms  22.214.171.124
  4    61 ms    65 ms    64 ms  188.8.131.52
  5   115 ms   105 ms   110 ms  220.127.116.11
  6   117 ms   113 ms   111 ms  tx049-r01-a1002x-tange0-2-0.wan.ibm.com
     [22.214.171.124]
  7   120 ms   130 ms   120 ms  22.214.171.124
  8  18.104.22.168  reports: Destination host unreachable.

   Trace complete.

3) ipconfig/ifconfig
One of the most important things that must be completed when troubleshooting a networking issue is to find out the specific IP configuration of the variously affected hosts. Sometimes this information is already known when addressing is configured statically, but when a dynamic addressing method is used, the IP address of each host can potentially change often. The utilities that can be used to find out this IP configuration information include the ipconfig utility on Windows machines and the ifconfig utility on Linux/*nix based machines
Example:
ipconfig
C:\Users\IBM_ADMIN>ipconfig

Windows IP Configuration

Ethernet adapter Local Area Connection 3:

   Connection-specific DNS Suffix  . : msci.svl.ibm.com
   IPv4 Address. . . . . . . . . . . : 10.1.3.136
   Subnet Mask . . . . . . . . . . . : 255.255.252.0
   Default Gateway . . . . . . . . . :

Ethernet adapter Local Area Connection 5:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wireless Network Connection 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

 Ethernet adapter Local Area Connection 2:

   Connection-specific DNS Suffix  . :
   IPv6 Address. . . . . . . . . : 2605:7020:f2c9:3200:c9ae:db7e:1c71:4e32
   Temporary IPv6 Address. . . . : 2605:7020:f2c9:3200:199:6140:ad98:9d6b
   Link-local IPv6 Address . . . . . : fe80::c9fe:db7e:14c1:4b39c%16
   IPv4 Address. . . . . . . . . . . : 18.104.22.168
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : fe80::d605:ef8f:f99ae:39cf5%16

 Ethernet adapter Bluetooth Network Connection:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wireless Network Connection:

   Connection-specific DNS Suffix  . :
   IPv6 Address. . . . . . . . . .  : 2605:6060:f2c9:3500:d84a:253:27d1:8864
   Temporary IPv6 Address. . . . .  : 2605:6060:f2c9:3500:d9ed:ab4:271a:f862
   Link-local IPv6 Address . . . . . : fe80::daf7:213:f7d1:8864%13
   IPv4 Address. . . . . . . . . . . : 126.96.36.199
   Subnet Mask . . . . . . . . . . . : 255.255.255.0

   Default Gateway . . . . . . . . . : fe80::d605:98ff:fe8c:41b7%23
                                   18.104.22.168

4) NSlookup
Some of the most common networking issues revolve around issues with Dynamic Name System (DNS) address resolution issues. DNS is used by everyone using the Internet to resolve commonly known domain names (i.e. google.com) to commonly unknown IP addresses (i.e. 18.104.22.168). When this system does not work, most of the functionality that people are used to goes away, as there is no way to resolve this information. The nslookup utility can be used to lookup the specific IP address(es) associated with a domain name. If this utility is unable to resolve this information, there is a DNS issue. Along with simple lookup, the nslookup utility is able to query specific DNS servers to determine an issue with the default DNS servers configured on a host.
 C:\Users\IBM_ADMIN>nslookup www.ibm.com
 Server:  mscidc01
 Address:  10.0.6.21

 Non-authoritative answer:
 Name:    e28f4.dscx.akamaiedge.net
 Addresses:  2001:428:3805:182::b3a
          2001:438:3806:18b::b3f
          102.84.07.134
 Aliases: www.ibm.com
          www-int.ibm.com.cs186.net
          www2.ibm.com.edgekey.net

5) Netstat
Often, one of the things that are required to be figured out is the current state of the active network connections on a host. This is very important information to find for a variety of reasons. For example, when verifying the status of a listening port on a host or to check and see what remote hosts are connected to a local host on a specific port. It is also possible to use the netstat utility to determine which services on a host that is associated with specific active ports.
Example: netstat
  C:\Users\IBM_ADMIN>netstat

  Active Connections

   Proto  Local Address          Foreign Address        State
   TCP    184.108.40.206:48784       bld-vo-lb-vip01:5060   ESTABLISHED
   TCP    126.96.36.199:49734       b03stlbcl001:1533      ESTABLISHED
   TCP    188.8.131.52:51520       sf2:3381               CLOSE_WAIT
   TCP    184.108.40.206:53389       sf2:3381               CLOSE_WAIT

You can use all of these commands would troubleshooting linking fault tolerant agents, dynamic agents, connectivity to DB, Websphere connections and communications between master and agents.
 You will also need to make sure you have the following:

 a) Hostname and IP address of systems in question
 b) Port number assigned to /MDM/Agent/WebSphere/DB
 c) Fire walls or DMZ

Answer: Also you can use telnet
For example from master you can test the connection to an FTA which is installed to a server with ip address: 126.96.36.199 and the netman port is set to default (31111).
Issue
telnet 220.127.116.11 31111

There might be a firewall that blocks the connection to the port if the connection is refused or timed out.


How to convert an array of string pointers into a vector of smart pointers of type string?

Question: I have a code like this:
std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") };

I need to get a vector like this:
std::vector<std::unique_ptr<string>> vec;

I also need to clear memory in the original string_ptr array and in the new vector.
How to do it better?
Comment: Why do you need an array of pointers (smart or otherwise) where each pointer points at a dynamically allocated `std::string` object?    What advantage does that offer you that an array of `std::string` (like `std::string strings[] = {"x", "y", ...}`) or a `std::vector` cannot?
Answer: If u want to transfer the ownership to a vector, you can do as follows (after this u won't have to free any memory. the vector will manage that)
int main() {
    std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") }; // step 1
    size_t sze = size(string_ptr);

    std::vector<std::unique_ptr<std::string>> vec(sze); // step 2
    for(size_t i{}; i < sze; ++i){
        vec[i].reset( string_ptr[i]);
        string_ptr[i] = nullptr;//transfer the elments ownership
    }
}

If you want to copy them only(you will have to manage the memory held by the raw pointers)
int main() {
    std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") }; // step 1
    size_t sze = size(string_ptr);
    std::vector<std::unique_ptr<std::string>> vec(sze); // step 2
    for(size_t i{}; i < sze; ++i){
        ;
        vec[i].reset(new std::string{*string_ptr[i]});
    }
    vec.erase(vec.end()-1);
}

See Why can I not push_back a unique_ptr into a vector?
Comment: there is a question: if I don't know how many elements are in string_ptr[] ?
Comment: I do not need to call delete for each element in string_ptr ?
Comment: @Yaniboze by the first method, u don't need that.
Answer: You could write
std::vector<std::unique_ptr<std::string>> vec{&string_ptr[0], &string_ptr[3]};

This transfers the pointers into std::unique_ptr<std::string> objects inside the vector. But keep in mind, you don't need to free the strings in string_ptr since they are now held by the unique pointers inside the vector.
Some further advice: Don't allocate strings in an array and transfer them later to the vector. This isn't exception safe. There will be memory leaks if an exception occurs until the end of the second step. If possible, don't use pointers at all:
std::vector<std::string> vec{ "x", "y", "z" };

or put the string pointers right away into the container:
std::vector<std::unique_ptr<std::string>> vec;
vec.emplace_back(std::make_unique<std::string>("x"));
// ...


When finding last but second element of a list, why is using `last` the fastest among these?

Question: There are 3 function given below which find the last but second element in a list. The one using last . init seems much faster than the rest. I can't seem to figure out why.
For testing, I used an input list of [1..100000000] (100 million). The last one runs almost instantly whereas the others take several seconds.
-- slow
myButLast :: [a] -> a
myButLast [x, y] = x
myButLast (x : xs) = myButLast xs
myButLast _ = error "List too short"

-- decent
myButLast' :: [a] -> a
myButLast' = (!! 1) . reverse

-- fast
myButLast'' :: [a] -> a
myButLast'' = last . init

Comment: `init` has been optimized to avoid "unpacking" the list multiple times.
Comment: @WillemVanOnsem I think unpacking probably isn't the issue here: GHC does call-pattern specialisation which should give you the optimised version of `myButLast` automatically. I think it's more likely list fusion that is to blame for the speedup.
Comment: @WillemVanOnsem but why is `myButLast` much slower?. It seems that is not unpacking any list, but just traversing it as `init` function does...
Comment: @Ismor: it is `[x, y]` is short for `(x:(y:[]))`, so it unpacks the outer cons, a second cons, and checks if the tail of the second `cons` is `[]`. Furthermore the second clause will unpack the list again in `(x:xs)`. Yes that unpacking is reasonably efficient, but of course if it happens very often, that will slow down the process.
Comment: Looking in https://hackage.haskell.org/package/base-126.96.36.199/docs/src/GHC.List.html#init, the optimization seems to be that `init` doesn't repeatedly check if its argument is a singleton list or an empty list. Once the recursion starts, it just assumes that the first element will be tacked onto the result of the recursive call.
Comment: @WillemVanOnsem Kindly take a look at my answer. If I expressed what you mean  correctly in my `butLast2`, then it actually makes no difference.
Comment: @IgnatInsarov: the idea is that `init` uses `init'`, which uses two parameters, to avoid unpacking twice: https://hackage.haskell.org/package/base-184.108.40.206/docs/src/GHC.List.html#init
Comment: FWIW I tried to do it using the State monad, the basic action being `shifter  = \v -> do { (x0,x1) <- get; put (x1,v); return () }`. With that, the expression `execState  (mapM_ shifter [3..1000])  (1,2)` evaluates to (999,1000). The performance at ghc -O2 seems good, and I think this is a bit more adaptable to different but similar goals.
Answer: When studying speed and optimization, it is very easy to obtain wildly wrong results. In
particular, you cannot really say that one variant is faster than another without mentioning the
compiler version and the optimization mode of your benchmarking setup. Even then, modern
processors are so sophisticated as to feature neural network based branch predictors, not to
mention all kinds of caches, so, even with careful set-up, benchmarking results will be blurry.
That being said...
Benchmarking is our friend.
criterion is a package that provides advanced benchmarking tools. I quickly drafted a
benchmark like this:
module Main where

import Criterion
import Criterion.Main

-- slow
myButLast :: [a] -> a
myButLast [x, y] = x
myButLast (x : xs) = myButLast xs
myButLast _ = error "List too short"

-- decent
myButLast' :: [a] -> a
myButLast' = (!! 1) . reverse

-- fast
myButLast'' :: [a] -> a
myButLast'' = last . init

butLast2 :: [a] -> a
butLast2 (x :     _ : [ ] ) = x
butLast2 (_ : xs@(_ : _ ) ) = butLast2 xs
butLast2 _ = error "List too short"

setupEnv = do
  let xs = [1 .. 10^7] :: [Int]
  return xs

benches xs =
  [ bench "slow?"   $ nf myButLast   xs
  , bench "decent?" $ nf myButLast'  xs
  , bench "fast?"   $ nf myButLast'' xs
  , bench "match2"  $ nf butLast2    xs
  ]

main = defaultMain
    [ env setupEnv $ \ xs -> bgroup "main" $ let bs = benches xs in bs ++ reverse bs ]

As you see, I added the variant that explicitly matches on two elements at once, but otherwise it
is the same code verbatim. I also run the benchmarks in reverse, so as to be aware of the bias due
to caching. So, let us run and see!
% ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.6.5

% ghc -O2 -package criterion A.hs && ./A
benchmarking main/slow?
time                 54.83 ms   (54.75 ms .. 54.90 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 54.86 ms   (54.82 ms .. 54.93 ms)
std dev              94.77 μs   (54.95 μs .. 146.6 μs)

benchmarking main/decent?
time                 794.3 ms   (32.56 ms .. 1.293 s)
                     0.907 R²   (0.689 R² .. 1.000 R²)
mean                 617.2 ms   (422.7 ms .. 744.8 ms)
std dev              201.3 ms   (105.5 ms .. 283.3 ms)
variance introduced by outliers: 73% (severely inflated)

benchmarking main/fast?
time                 84.60 ms   (84.37 ms .. 84.95 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 84.46 ms   (84.25 ms .. 84.77 ms)
std dev              435.1 μs   (239.0 μs .. 681.4 μs)

benchmarking main/match2
time                 54.87 ms   (54.81 ms .. 54.95 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 54.85 ms   (54.81 ms .. 54.92 ms)
std dev              104.9 μs   (57.03 μs .. 178.7 μs)

benchmarking main/match2
time                 50.60 ms   (47.17 ms .. 53.01 ms)
                     0.993 R²   (0.981 R² .. 0.999 R²)
mean                 60.74 ms   (56.57 ms .. 67.03 ms)
std dev              9.362 ms   (6.074 ms .. 10.95 ms)
variance introduced by outliers: 56% (severely inflated)

benchmarking main/fast?
time                 69.38 ms   (56.64 ms .. 78.73 ms)
                     0.948 R²   (0.835 R² .. 0.994 R²)
mean                 108.2 ms   (92.40 ms .. 129.5 ms)
std dev              30.75 ms   (19.08 ms .. 37.64 ms)
variance introduced by outliers: 76% (severely inflated)

benchmarking main/decent?
time                 770.8 ms   (345.9 ms .. 1.004 s)
                     0.967 R²   (0.894 R² .. 1.000 R²)
mean                 593.4 ms   (422.8 ms .. 691.4 ms)
std dev              167.0 ms   (50.32 ms .. 226.1 ms)
variance introduced by outliers: 72% (severely inflated)

benchmarking main/slow?
time                 54.87 ms   (54.77 ms .. 55.00 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 54.95 ms   (54.88 ms .. 55.10 ms)
std dev              185.3 μs   (54.54 μs .. 251.8 μs)

Looks like our "slow" version is not slow at all! And the intricacies of pattern matching do not
add anything. (A slight speed up we see between two consecutive runs of match2 I ascribe to the
effects of caching.)
There is a way to get more "scientific" data: we can -ddump-simpl and take a look at the
way the compiler sees our code.
Inspection of intermediate structures is our friend.
"Core" is an internal language of GHC. Every Haskell source file is simplified to Core before
being transformed into the final functional graph for the run time system to execute. If we look
at this intermediate stage, it will tell us that myButLast and butLast2 are equivalent. It
does take looking, since, at the renaming stage, all our nice identifiers are randomly mangled.
% for i in `seq 1 4`; do echo; cat A$i.hs; ghc -O2 -ddump-simpl A$i.hs > A$i.simpl; done

module A1 where

-- slow
myButLast :: [a] -> a
myButLast [x, y] = x
myButLast (x : xs) = myButLast xs
myButLast _ = error "List too short"

module A2 where

-- decent
myButLast' :: [a] -> a
myButLast' = (!! 1) . reverse

module A3 where

-- fast
myButLast'' :: [a] -> a
myButLast'' = last . init

module A4 where

butLast2 :: [a] -> a
butLast2 (x :     _ : [ ] ) = x
butLast2 (_ : xs@(_ : _ ) ) = butLast2 xs
butLast2 _ = error "List too short"

% ./EditDistance.hs *.simpl
(("A1.simpl","A2.simpl"),3866)
(("A1.simpl","A3.simpl"),3794)
(("A2.simpl","A3.simpl"),663)
(("A1.simpl","A4.simpl"),607)
(("A2.simpl","A4.simpl"),4188)
(("A3.simpl","A4.simpl"),4113)

It seems that A1 and A4 are the most similar. Thorough inspection will show that indeed the
code structures in A1 and A4 are identical. That A2 and A3 are alike is also reasonable
since both are defined as a composition of two functions.
If you are going to examine the core output extensively, it makes sense to also supply flags such as -dsuppress-module-prefixes and -dsuppress-uniques. They make it so much easier to read.
A short list of our enemies, too.
So, what can go wrong with benchmarking and optimization?

ghci, being designed for interactive play and quick iteration, compiles Haskell source to a certain flavour of byte code, rather than final executable, and eschews expensive optimizations in favour of quicker reload.
Profiling seems like a nice tool to look into performance of individual bits and pieces of a complex program, but it can wreck compiler optimizations so badly, the results will be orders of magnitude off base.

Your safeguard is to profile every small bit of code as a separate executable, with its own benchmark runner.

Garbage collection is tuneable. Just today a new major feature was released. Delays for garbage collection will affect performance in ways that are not straightforward to predict.
As I mentioned, different compiler versions will build different code with different performance, so you have to know what version the user of your code will likely use to build it, and benchmark with that, before you make any promises.

This may look sad. But it is really not the thing that should concern a Haskell programmer, most of the time. Real story: I have a friend who just recently started learning Haskell. They had written a program for numerical integration, and it was turtle slow. So we sat down together and wrote a categorial description of the algorithm, with diagrams and stuff. When they re-wrote the code to align with the abstract description, it magically became, like, cheetah fast, and slim on memory too. We calculated π in no time. Moral of the story? Perfect abstract structure, and your code will optimize itself.
Comment: Very informative, and also a little overwhelming for me at this stage.

In this case, all the "benchmarking" I did was run all the function for 100 million item list and notice that one takes longer than the other.

Benchmark with criterion seems rather useful. In addition, `ghci` seems to give different results (in terms of speed) as compared to making an exe first, like you said.


Show that $\lim \frac1{n^2 +1} =0$

Question: I am not very familiar to epsilon... But this question belongs to my Sallybus and I want to understand it with the help of epsilon definition.. Kindly help me to solve it
Comment: Ok, if you aren't comfortable with epsilon-delta proofs, first, write down the definition of a limit in terms of epsilon delta, then apply the conditions of the definition. Edit your work in so we can see where you are getting stuck.
Answer: In the first place, it is worth to emphasize the definition of convergence of sequences.
Let $x_{n}\in X$, where $(X,d)$ is a metric space. We say that $x_{n}$ converges to $x_{0}\in X$ iff
\begin{align*}
(\forall\varepsilon > 0)(\exists n_{\varepsilon}\in\mathbb{N})\,\,\text{s.t.}\,\,(n\geq n_{\varepsilon} \Rightarrow d(x_{n},x_{0}) < \varepsilon)
\end{align*}
At the present case, $(X,d) = (\mathbb{R},d)$, $x_{n} = (n^{2}+1)^{-1}$ and $x_{0} = 0$, where $d(x,y) = |x - y|$.
Having said that, we can proceed.
To begin with, I would start with noticing that
\begin{align*}
\frac{1}{n^{2}+1} < \frac{1}{n^{2}} < \varepsilon \Rightarrow n > \frac{1}{\sqrt{\varepsilon}}
\end{align*}
Thus, for every $\varepsilon > 0$, there corresponds a natural number $n_{\varepsilon} = \Bigl\lceil\dfrac{1}{\sqrt{\varepsilon}}\Bigr\rceil$ s.t.
\begin{align*}
n\geq n_{\varepsilon} \Rightarrow \frac{1}{n^{2}+1} < \varepsilon
\end{align*}
Hopefully this helps!
Answer: Let $\varepsilon > 0$ be the goal to approach. We want to find an integer $N>0$ such that whenever $n > N$, we have $\frac{1}{n^2+1} < \varepsilon$. As we know $\frac{1}{n^2+1} < \frac{1}{n}$, let's pick $N$ be the smallest integer greater than $1/\varepsilon$. Then whenever $n>N$, we have $n>N\geq1/\varepsilon$ and $\frac{1}{n^2+1} < \frac{1}{n}<\varepsilon$. That's exactly what we want to prove.
Answer: Option:
Let $n \ge1;$
$\dfrac{1}{n^2+1} \le\dfrac{1}{n^2} \le \dfrac{1}{n};$
Let $\epsilon >0$ be given.
Archimedian principle:
There exists a $n_0 \in \mathbb{N}$ s. t.
$n_0 >1/\epsilon;$
For $n\ge n_0:$
$\dfrac{1}{n^2+1}\le \dfrac{1}{n}<\dfrac{1}{n_0} <\epsilon. $

Show that $\lim \frac1{n^2 +1} =0$


Bayesian inference - a use case

Question: I've been recently studying Bayesian inference with PyMC3. I understand the flexibility that comes with multiple possible options for initial distribution choices, yet I can't seem to understand why one would need the sampling part. I realize this is a very naive question, yet I cant seem to understand why does one not stop at the MAP part -- here the model parameter values are found.
Why the NUTS,GIBBS or any other sampling? Why is this useful? I see that whole distributions are obtained for individual parameters, and can be visualized. I assume this has to do with some sort of parameter validation, where one inspects the quality of the parameters obtained?
My current understanding is that MAP estimates are used as starting points for the sampling part. Once the sampling is done, how does one obtain "more correct" parameter values based on the MCMC?
I would really like to use this methodology for modeling tasks I am dealing with, yet I just don't see positive sides of having to choose one of n possible priors, where each could potentially give different results (?)
Thank you very much.
Answer: Since it seems that you lack some basic understanding of the process behind Bayesian modeling work, let me give you a short summary of the usual workflow:

You define the likelihood function for your model, for example: you assume the Bernoulli distribution parametrized by probability of success $\pi$ for the binary variable $Y$. So $Y$ is your data, e.g. series of coin flips: <code>[0, 0, 1, 1, 0, 1, 1]</code>.
You assume the prior distribution(s) for your parameter(s), say in our case, we assume beta distribution parametrized by hyperparameters $\alpha$ and $\beta$. Let's say that you assume a uniform prior, i.e. $\alpha = \beta = 1$.

Now you described the problems in probabilistic terms and defined your model. Notice that we didn't estimate anything yet, we just defined a set of assumptions about our data and the parameters.

Next, what we need to do is to estimate the parameter $\pi$. For this, you can do one of the three things:

You can use conjugacy and obtain the closed-form posterior distribution by using pure math,
You can use some kind of optimization to find the maximum of the posterior distribution (the mode of the posterior distribution), i.e. use maximum a posteriori (MAP) -- this gives you a point estimate for $\pi$,
You can simulate draws from the posterior distribution using Markov Chain Monte Carlo (MCMC) algorithms (e.g. Metropolis-Hastings, Gibbs, or NUTS). By doing so you obtain the samples from the posterior distribution (in this case samples from the posterior distribution of the random variable $\pi$). You can use the samples to approximate the posterior distribution, or to estimate it's properties, e.g. calculate the mean from the samples, to estimate the expected value of the parameter of interest $E(\pi | Y)$ as your point estimate of $\pi$.

All the approaches have pros and cons. You can use conjugacy only for the very simple problems, but there is no closed-form solutions for things like multivariate logistic regression, so this won't work for many problems. As about MAP, it gives you only the point estimate and it depends on the optimizer you used, it may not always work for complicated problems that are hard to optimize (recall that when using maximum likelihood we often use dedicated optimizers for complicated problems rather then black-box ones). Simulation is the most commonly used approach in Bayesian estimation, it is slower then the two previous approaches, but it gives you the full posterior distribution. MCMC is the approach of choice for most Bayesians.
We use priors to quantify our assumptions about the parameters. They let us to put some out-of-data information into the model. On another hand, the more information does your data convey, the less influential are the priors.
Comment: Thanks! This actually clarifies a lot. Especially the parameter estimation part.

Bayesian inference - a use case


Compare the file timestamp with current time in .bat file

Question: I have a windows script for reading file that is put by an application within a time limit. The script times out in 1 min.
If the application was late in putting the file then there will be an old file lying in the folder.
Next time the script is executed it will read the old file instead of the new one.
I want to compare the timestamp of the file with the timestamp the script was executed.
How can I get the timestamp when the file was placed on the folder in .bat file?
Thanks
Comment: If you really have a script, don't hesitate to show it here.
Answer: try this, it is for the default European time format:
<code>for %%a in (file) do set "filestamp=%%~ta"
set "datestamp=%date%  %time:~0,5%"
if "%datestamp%"=="%filestamp%" (
    rem read this
) else (
    rem read this NOT
)
</code>
Comment: Thanks Endoro! The filestamp prints 07/29/2013 02:52 PM but the datestamp prints Tue 07/30/2013  14:28. These will never be equal.
Comment: that's true! You should synchonize your time format: both European or both AM/PM.
Comment: Endoro - How to check whether the datestamp is less than the filestamp?


$\int_{[0,1]}|f(x)-g(x)||g(x)-h(x)|dx\leq (\int_{[0,1]}|f(x)-g(x)|^2 dx)^{1/2} (\int_{[0,1]}|g(x)-h(x)|^2 dx)^{1/2}$

Question: I'm trying to prove that $(\int_{[0,1]}|f(x)-h(x)|^2 dx)^{1/2}\leq \int_{[0,1]}|f(x)-g(x)|^2 dx)^{1/2} + (\int_{[0,1]}|g(x)-h(x)|^2 dx)^{1/2}$, where $f,g,h\in C(\mathbb{R}/\mathbb{Z},\mathbb{C})$.
Now, I have that $|f(x)-h(x)|^2\leq|f(x)-g(x)|^2+|g(x)-h(x)|^2+2|f(x)-g(x)||g(x)-h(x)|\forall x\in [0,1]$;
I need only to prove now that $\int_{[0,1]}|f(x)-g(x)||g(x)-h(x)|dx\leq (\int_{[0,1]}|f(x)-g(x)|^2 dx)^{1/2} (\int_{[0,1]}|g(x)-h(x)|^2 dx)^{1/2}$
but I haven't gone very far in proving this last result so I'd appreciate any hint.
(Note: I don't know Holder's, Minkowski's or Cauchy-Schwarz's inequalities for integrals)
Comment: It looks like you'll have to prove Minkowsky...
Answer: You are trying to prove Minkowski's inequality for $p=2$, and have managed to reduce it to Hölders inequality for $p=2$.
Without mentioning the general proof of these inequalities, you should consider a specific case of Young's inequality: $ab \leq \frac{a^2}{2} + \frac{b^2}{2} $ and consider how to apply this to your two functions f(x)-g(x) and g(x)-h(x).


Time signatures and verse

Question: Recently I challenged myself to set a piece of religious text to music for SATB.
However, I encountered timing issues caused by irregular numbers of syllables in verses, and when to break off phrases.
In the following hymn it is easy since it has 8 syllables per line and can therefore be written in a regular 4/4 time signature:

O come, O come, Emmanuel
And ransom captive Israel
That mourns in lonely exile here
Until the Son of God appear
Rejoice, rejoice, Emmanuel
Shall come to thee, O Israel

But what about for irregular hymns or verses? Can I change the time signature midway through the piece? How would I determine the best time signature?
Edit: in the example shown above there's a regular distribution of syllables per line, and the phrasing is obvious since there are rhyming couplets. But what about a format of:
Line 1 (x syllables),
Line 2 (y syllables),
Line 3 (z syllables) ;
etc. It is more difficult since naturally we group phrases in 2 lines which would render the transition from line 2 to 3 awkward
Answer: I think you are making a simplistic assumption that your melody will be a string of equal notes, one per syllable.  Like the first example below.  Some hymn tunes do plod along like that, and if the harmonies are interesting they're none the worse for it!  But if you aren't Bach (or emulating plainchant) you may want to vary the rhythms a bit. Like the second example (which actually has varied phrase lengths, if not bar lengths. This won't upset a congregation too much though.)

Answer: The syllables in a verse don't all have to be sung to notes of the same length! So if you had, say, lines of 8 and 7 syllables, you could set one of the 7 to a note as long as two syllables elsewhere would need.
Answer: What is your aim in writing the piece? Is it for a choir or for a congregation to sing? Most performing groups can handle time signature changes anywhere in a piece. The difficulty would vary depending on how many times you change time signature and if any of those time signature changes are particularly complicated.
Congregational singing requires a more standard and predictable approach in order to keep everyone together. Some hymns have time signature changes, but they are usually at the end of the phrase. (Be Thou My Vision, for example.)
You can also make adjustments by putting in a rest or two at the beginning of a phrase, or by holding certain words or syllables shorter or longer to make the music pattern more similar between phrases.
In my experience, congregations find irregularly phrased hymns difficult to sing (for example, Of the Father's Love Begotten)
Comment: It would be for an SATB choir
Comment: @ShawnLi, in that case I would suggest that you can put musical and textual consideration on an equal level and do what you feel is artistically best, without worrying about time signature changes.
Answer: 1)Try to maintain the same time signature through out every verse, you can change time signature for chorus and bridge however maintain that for entire chorus/bridge.
2)You can change the time signature in the middle of the piece as it fits to the flow.
3)To fit each line into a phrase, maintain a consistent time signature and reduce/add syllables as needed, Example) add articles like a,the,an,one so you will have a consistent feel on each line. like words "and" , "here" in your example. Similarly remove some syllables like "ing,a,shall", reword the phrase to maintain the same meaning of original text with different words.
4) Prolong few syllables for more than one note/pitch(melisma)
5) Try some music tools to compose the music first and then apply words, Check Music Tool Kit android app
Music Tool Kit
Comment: I do not know why this answer got a negative vote. It is perfectly fine. The strategy may not be useful to everyone, but there is nothing wrong with it to deserve a negative vote. I am up-voting to get rid of that.

Time signatures and verse


Alter title link in taxonomy view mode

Question: Under /admin/structure/taxonomy/my_vocabulary/display/entity I've got a view mode "entity". For this view mode, I would like to alter the way the link in the title field is built (the title is replaced by a real field instance due to title module): the link should be rebuilt into an anchor link like this: Title, where term-ID is replaced with the actul term ID of the term. How can I achieve this by a custom module or by a template function? Are render arrays good for this?
Here's a screenhot of the admin page.
Comment: what do you mean by this `I would like to alter the way the link in the title-field is built`?
Comment: i edited my previous quetsion
Comment: Where does that title field comes from? Do you have a screendump of the /admin/structure/taxonomy/my_vocabulary/display page?
Comment: Screenshot is added. I think the title is automatically added (like node titles are rendered automatically, too; node titles can be hidden by using exclude node title module, but for entities this doiesn't work. see here: http://drupal.stackexchange.com/questions/107895/hide-title-for-rendered-entity-views)
Comment: I am not to familiar with this also so please bear with me :). Is Beschreibung the field that is replacing the default Title? Perhaps you can use https://www.drupal.org/project/custom_formatters or otherwise https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook_field_formatter_info/7.x
Answer: I finally altered the title link by using a preprocess hook and a custom field template file (and a custom view mode for my entity, done with hook_entity_info_alter()):
  function hook_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#term'];
  $term = $variables['term'];
  $uri = entity_uri('taxonomy_term', $term);
  // Edits are here:
  $variables['term_url'] = url($uri['path'], $uri['options']);
  $variables['term_name'] = check_plain($term->name);
  $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
  $variables['term_id'] = drupal_html_id($term->name);
  // Flatten the term object's member fields.
  $variables = array_merge((array) $term, $variables);
  // Helpful $content variable for templates.
  $variables['content'] = array();
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);

  // Gather classes, and clean up name so there are no underscores.
  $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;

  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
}

My taxonomy-term.tpl.php:
<div<?php print $attributes; ?>>
  <?php if (!$page && ($view_mode != 'subcategory_anchor')): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

  <?php endif; ?>

  <?php if (!$page && ($view_mode == 'subcategory_anchor')): ?>
    <h2 id="<?php print $term_id ?>"><?php print $term_name; ?>

  <?php endif; ?>

  <div<?php print $content_attributes; ?>>
    <?php print render($content); ?>

Alter title link in taxonomy view mode


maximum nonattacking black and white queens on infinite chessboard

Question: Suppose there's an infinite chessboard with black and white queens, such that no black queen attacks a white queen.  Also, the black queens and white queens have the same density $d$ (over large square areas, say).  What's the maximum $d$?
I can see how to get $d = 1/8$: put black queens on $(4i, 2j)$ (for all integers $i$, $j$) and white queens on $(4i + 2, 2j + 1)$.  Roughly speaking, the black and white queens stay a knight's move away from each other.  I suspect that's the best.
Note that this is different from the problem where no queen can attack any other queen; here it's OK for a black queen to attack another black queen.
Comment: "Nonattacking" is a little misleading here: usually that means none of the queens can attack each other, but here it means that they can't attack the other color.  I'll try to clarify that and add an example.
Comment: How do you get $1/8$? in the (one-colored) 8 queens and extensions it is easy to see there can only be one queen on each row, so this number is highly suspect.
Answer: Martin vB's answer not only gets $d = \frac{3}{49}$ instead of $d = \frac{3}{7}$ but doesn't even work, AFAICT. Here's his pattern drawn out:
..............
......W......W
.....W......W.
....W......W..
..B......B....
.B......B.....
B......B......
..............
......W......W
.....W.!....W.
....W...!..W..
..B......B....
.B......B.....
B......B......

The !s indicate where a black queen threatens a white queen in this pattern.
However, observing that we need an extra column, not an extra row, we could use the same general principle to come up with something like this that does work:
....W.W.....W.W.
.....W.......W..
....W.W.....W.W.
B.B.....B.B.....
.B.......B......
B.B.....B.B.....
....W.W.....W.W.
.....W.......W..
....W.W.....W.W.
B.B.....B.B.....
.B.......B......
B.B.....B.B.....

The density here is a paltry $\frac{5}{48} \approx 0.104$, so it's not as good as your original
B...B...B...B...
..W...W...W...W.
B...B...B...B...
..W...W...W...W.
B...B...B...B...
..W...W...W...W.

which has a density of $\frac{6}{48} = 0.125$.
If you permit solutions that aren't "the same density everywhere", you can also get $d = 0.125$ with something like
B...............
BB..............
BBB.............
BBBB............
BBBBB...........
BBBBBB..........
BBBBBBB.........
........WWWWWWWW
.........WWWWWWW
..........WWWWWW
...........WWWWW
............WWWW
.............WWW
..............WW
...............W

(drawn out to infinity in each direction, so that one-eighth of the plane is all black and the opposite eighth is all white). I don't think you can do better than $d = \frac{1}{8} = 0.125$ by this variation, though.
If you are willing to redraw the pattern as the square gets bigger, tending to a continuous solution in the unit square, you can achieve at least $d = \frac{7}{48} \approx 0.1458$. Here's an example solution that gives you exactly $d = \frac{7}{48}$ on a 12x12 grid — but it does not tile, so there's no way to fill the plane with it.
...WW......W
...WW.....WW
...WW....WWW
...W.....WWW
.........WWW
.........WW.
.BB.........
BBB.........
BBB.....B...
BB.....BB...
B.....BBB...
.....BBBB...

Comment: This problem, the "peaceable queens problem", is discussed by N.J.A. Sloane in the Notices of the AMS (ams.org/journals/notices/201809/rnoti-p1062.pdf). See also oeis.org/A250000, where the configuration with density 7/48 appears.
Answer: Can easily improve to d = 3/7: put black queens on (i, i) (for all integers i where 3 > i - 1 (mod 7) and white queens on (i, i+1) (for all integers i where 3 < i (mod 7).
That is, place 3 black queens on the major diagonal, followed by 3 white queens one to the right of the major diagonal, followed by a blank row, and repeat. A similar strategy permits d to approach 1/2 if you let the "large square area" become "large" enough.
Comment: I'm not quite following the part about the blank row, but this looks like a nice way to fill a (roughly) 7-by-7 rectangle, then tile the plane with a grid of these rectangles.  That sounds like a density around $3/49$ rather than $3/7$.


Prove there exists $\xi \in (a,b)$ such that $f(\xi)=f^{(n+1)}(\xi)$.

Question: Problem
Let $f(x)$ be $n$-times differentiable over $[a,b]$ and $n+1$-times differentiable over $(a,b)$. $f^{(k)}(a)=f^{(k)}(b)=0$, where $k=0,1,2,\cdots,n$. Prove there exists $\xi \in (a,b)$ such that $f(\xi)=f^{(n+1)}(\xi)$.
Attempt
Consider applying Taylor's formula expanding at $x=a,b$. We have
\begin{align*}
f(x)&=f(a)+f'(a)(x-a)+\cdots+\frac{f^{(n+1)}(\xi_1)}{(n+1)!}(x-a)^{n+1}
=\frac{f^{(n+1)}(\xi_1)}{(n+1)!}(x-a)^{n+1}.
\end{align*}
and
\begin{align*}
f(x)&=f(b)+f'(b)(x-b)+\cdots+\frac{f^{(n+1)}(\xi_2)}{(n+1)!}(x-b)^{n+1}
=\frac{f^{(n+1)}(\xi_2)}{(n+1)!}(x-b)^{n+1}.
\end{align*}
Can we go on from these?
Edit
Later I consulted some reference books and find a similar problem in the book named Problems In Real Analysis: Advanced Calculus On The Real Axis.

Thus, I wonder whether the conclusion holds or not ,if we are only given that   $f(x)$ is $n$-times differentiable over $[a,b]$ and $n+1$-times differentiable over $(a,b)$.
Comment: It could be useful to think with an example in mind: $x^n|x|(x-1)^n$ satisfies your hypotesis on $(0,1)$ (and nothing more). It you wish to deal with a smoother example, you could think of $e^{-\frac{1}{x^2(x-1)^2}}$
Answer: Failed attempt:
Consider the function
$$g(x)=(f(x)+f'(x)+\ldots+f^{(n)}(x))e^{-x} $$
that is continuous(!) over $[a,b]$ and differentiable over $(a,b)$ with derivative
$$\begin{align}g'(x)&=(f'(x)+f''(x)+\ldots+f^{(n+1)}(x))e^{-x}-(f(x)+f'(x)+\ldots+f^{(n)}(x))e^{-x}\\&=(f^{n+1}(x)-f(x))e^{-x}.\end{align}$$
As $g(a)=g(b)=0$, the Rolle theorem tells us that here exists $\xi\in(a,b)$ with $g'(\xi)=0$.
Correction:
Unfortunately, $g$ need not be continuous at $a$ or $b$, so the Rolle theorem cannot be applied. $g$ will only be continuous (and differentiable) over $(a,b)$. In other words, the Rolle theorem holds under somewhat weaker assumptions, but it is usually not presented that way - for the simple reason that Rolle is one of the first theorems about derivatives one encounters.
Here's how to mend the mistake above:
Assume $g$ is injective over $(a,b)$.
Then $g$ must be strictly monotonic over $(a,b)$ (and in particular not constant). Pick $c\in(a,b)$ with $g(c)\ne 0$, wlog. $g(c)>0$ (or else replace $f$ with $-f$). Then either $g(x)>g(c)$ for all $x\in(a,c)$ or for all $x\in (c,b)$; wlog the former (or else replace $f$ with $x\mapsto f(a+b-x)$).
As $e^x$ is bounded over $[a,c]$, it follows that there exist $\delta>0,\epsilon>0$ such that $$\tag1h(x):=e^xg(x)>\epsilon$$ for all $a<x<a+\delta$. But
$ h(x)=f(x)+f'(x)+\ldots+f^{(n)}(x)$ is the derivative of $x\mapsto \int_a^xf(t)\,\mathrm dt+f(x)+\ldots +f^{(n-1)}(x)$ and hence has the Darboux (aka. Inermediate Value) property. In particular, as $h(a)=0$, there must exist $x\in(a,a+\delta)$ with $h(x)=\frac12\epsilon$, contradicting $(1)$.
We conclude that $g$ cannot be injective over $(a,b)$. Hence, there are $u,v$ with $a<u<v<b$ and $g(u)=g(v)$. By Rolle, there exixts $\xi\in(u,v)$ with $g(\xi)=0$. This implies that $f^{(n+1)}(\xi)=f(\xi)$.
Comment: Ooops, wait. In general, $g$ will not be continuous at $a,b$. Have to reconsider
Comment: @mengdie1982 because $g$ is strictly monotonic and $(a,b)$ has more than one point
Comment: @mengdie1982 I do not understand your second comment. Your original question was already the Zhang problem, but with $f^{(n+1)}$ existing only in $(a,b)$, or am I missing something?
Comment: How to guarantee $\exists c \in (a,b):g(c) \neq 0$? How to obtain $(1)$?
Comment: I wonder whether the conclusion holds or not ,if we are only given that   $f(x)$ is $n$-times differentiable over $[a,b]$ and $n+1$-times differentiable over $(a,b)$. See my edit.
Comment: nice proof!!, last line should read $g(u)=g(v)$, not $g(u)=g(b)$
Answer: Proof
At first, let's introduce and prove a lemma, which could be stated as follows.

Lemma Let $f(x)$ be differentiable over $[a,b]$, and $f'(x)$ be
continuous over $(a,b)$. $f'(a)=f'(b)=0$. Then there exist $x_1,x_2$
satisfying $a<x_2<x_1<b$ such that $f'(x_1)=f'(x_2),$ namely, $f'(x)$
can not be injective over $(a,b)$.

Consider proving by contradiction. Assume the conclusion does not hold. Then $f'(x)$ is injective over $(a,b)$. Taking the fact $f(x)$ is continuous over $(a,b)$ into account, we may obtain $f'(x)$ is strictly monotonic over $(a,b)$. Without loss of generality, we assume $f'(x)$ is strictly increasing over $(a,b)$. Obviously, there exsits $c \in (a,b)$ such that $f'(c) \neq 0$. Without loss of generality, we assume $f'(c)>0$ and consider the interval $(c,b)$. (If $f'(c)<0$, we may consider the interval $(a,c)$. The reasoning is similar.) Notice that $f'(c)>0$ and $f'(b)=0$. According to Darboux's theorem, there exists $\xi \in (c,b)$ such that $f'(\xi)=\dfrac{1}{2}f'(c)$. But, since $f'(x)$ is strictly increasing over $(c,b)$, we may have $\dfrac{1}{2}f'(c)=f'(\xi)>f'(c)>0$,  which contradicts.
Now, we can go back to deal with the target problem. We must restrain that $n \geq 1$. Otherwise, the statement need not hold, and I have given a conterexample before when $n=0$. Denote$$F(x):=(n+1)\int_a^x e^{-t}f(t){\rm d}t+\sum_{k=0}^{n-1}(n-k)e^{-x}f^{(k)}(x), x\in [a,b].$$Then $F(x)$ is differentiable over $[a,b]$, and$$F'(x)=e^{-x}\sum_{k=0}^{n}f^{(k)}(x).$$It's easy to verify that $F'(x)$ is continuous over $(a,b)$ and $F'(a)=F'(b)=0$. Thus,by Lemma,$$\exists x_1,x_2(a<x_1<x_2<b):F'(x_1)=F'(x_2).$$Further, by Rolle's theorem,$$\exists \xi \in (x_1,x_2)\subset (a,b):F''(\xi)=e^{-\xi}[f^{(n+1)}(\xi)-f(\xi)]=0,$$which implies$$f(\xi)=f^{(n+1)}(\xi).$$
Answer: Analysis and Counterexample
We will point out that the statement does not hold necessarily just from the given assumption conditions. Consider the version when $n=0$.

Let $f(x)$ be $0$-times differentiable over $[a,b]$ and $0+1$-times
differentiable over $(a,b)$. $f^{(k)}(a)=f^{(k)}(b)=0$, where
$k=0$. Prove there exists $\xi \in (a,b)$ such that
$f(\xi)=f^{(1)}(\xi)$.

What dose this say? Maybe we can state more directly as follows:

Let $f(x)$ be defined over $[a,b]$ and differentiable over $(a,b)$. $f(a)=f(b)=0$
. Prove there exists $\xi \in (a,b)$ such that
$f(\xi)=f^{'}(\xi)$.

Unfortunately, it does not hold. Here is a counterexample. Let
$$f(x)=\begin{cases}\sin x+2, &0<x<\pi;\\0,&x=0,\text{or}~\pi.\end{cases}$$
Obviously, $f(x)$ has definitions over $[0,\pi]$ and differentiable over $(0,\pi)$. $f(0)=f(\pi)=0.$ But there exsits no $\xi \in (a,b)$ such that $f(\xi)=f'(\xi)$, because the equation
$$f(x)=f'(x),x \in (a,b)$$
namely
$$\sin x+2=\cos x$$
has no solution at all.
Comment: I think $0$ times differentiable means $f\in{C^{0}}$, that is $f$ is continuous.... And at your anti example $f$ is not.
Answer: First, let's prove the case of $n=1$
You have two contnuous functions. $f(x)$ and $g = f'(x)$. Let's look at the interval $[a, a+ s]$ such that for the first time $f(s)=0$ That means that the derivative has different signs at $a$ and $a+s$. (The case of the function touching the line should be treated carefully, but nothing special there.) So, we have $f-g$ that is positive on the one side of $[a, a+s]$ and negative on the another. By continuousity, there is $0$ of $f-g$ somewhere.
I don't know how to make an indction step, but looks like that's possible.
Comment: The idea cannot work with $n+1$, since $f^{(n+1)}(a)$ is not defined


How to disable a language while still being able to create content for it

Question: I have a website with already 2 languages. I want to add a 3 one, but I obviously don't want it to be accessible until it is finished. If I disable to language, I can't create content in it anymore.
Anyone has a suggestion?
Thank
Answer: You could try to use the Hidden Language module.

This module allows site admins to hide languages from end-users. As opposed to disabling language content editors still can translate content to that language. It's useful if you don't have entire website translated.
Comment: Wasn't sure since it only had 4 current users and no release version. I figured my "problem" was something common. I'll check it out and get back here with results !
Comment: After trying the module, the "hidden" column did not appear, therefore I had to make my own code.
Answer: when testing new items, elements, modules, etc a general rule of thumb:

only test on a test(development) server - never test new items on a production server

I would suggest something along these lines:

If you haven't already, set up a test server on a local machine - there are plenty of resources available to do this depending on your OS
take a backup of the current production site files and DB
copy those to your test server so you have a mirror to work with
make all changes to modules, settings, etc - keep track of the changes you make
test new settings
when testing shows you have it the way you want, make the changes you recorded earlier to the production site
BEFORE DEPLOYING ON PRODUCTION SITE: MAKE ANOTHER BACKUP COPY OF PRODUCTION DB AND FILES
test on the production site imediately, preferrably putting it into maintenance mode so users can't inadvertantly change things or add content that may be lost - if anything is wrong you can restore the site from the most recent backup


Evaluate the image of a function

Question: I am given a function:
$f: \mathbb{R} \times \mathbb{R} \to \mathbb{R}, \space\space f(x,y)=(x-y^2)(y-x^2)$.
I have to evaluate the image $f(A)$ of a set $A=\mathbb{R}^+\times \mathbb{R}^+$.
I tried to muplitply the brackets and what I got was:
$f(x, y)=-x^3-y^3+x^2y^2+xy$
When I looked for some particular points, hoping to find a pattern, I got nothing:
$f(2,3)=(2-9)(3-4)=7$
$f(2,4)=(2-16)(4-4)=0$
$f(1,10)=(1-100)(10-1)=-891$
The only thing that comes to my mind is the answer $f(A)=\mathbb{R}$
How do I find the image? Generally, how to solve this type of problem?
Comment: You get all values $\geq 0$ by taking $x = y$, and all values $\leq 0$ by taking $y = 1$. For the second statement, the only proof I see at the moment uses the intermediate value theorem. If you want a proof without that, it might take more work.
Comment: Can you please include your try inside your question
Comment: What kind of class is this for? I'm asking because what's used in the answer may vary depending on what you know about topology and/or calculus.
Comment: I would advice to find $f(\partial A)$ first, which means $f(\{0\}\times\mathbb{R})\cup f(\mathbb{R}\times\{0\})$. It is a good way to guess the answer. Then, depending on the answer to @David's question, you may use the concept of connectedness, or not, if you are not familiar with it.
Comment: This is for the 'Elements of Logic and Set Theory' class. It doesn't contain any topological topics.
Answer: $f(x,y)=(x-y^{2})(y-x^{2})=x^{2}y^{2}-x^{3}-y^{3}+xy$
For $x,y,t \in \mathbb{R}^{+}$,
$f(x,0^{+})=-x^{3} \in (-\infty,0)$,
$f(0^{+},y)=-y^{3} \in (-\infty,0)$,
$f(t,t)=t^{4}-2t^{3}+t^{2}=t^{2}(t-1)^{2} \in [0,\infty)$
$\therefore f[A]= \mathbb{R}$
Comment: $f(A)\in\mathbb{R}$ has no meaning. More importantly, the point is not to prove that $f(A)\subset \mathbb{R}$, which is trivial, but $\mathbb{R}\subset f(A)$, for which you roughly give the ideas of the proofs, but it should be done more rigorously
Comment: Corrected, many thx.

Evaluate the image of a function


Converting strings into float and integers (if is necessary) in Python

Question: I've to call an API that sometimes returns me numerical values in string format, "288" instead of 288, or "0.1523" instead of 0.1513. Some other times, I get the proper numerical value, 39.
How can I make the function to format it to the proper value? This means:

If I get "288" convert it to an integer: 288.
If I get "0.323" convert it to a float: 0.323.
If I get 288 leave it as it is (its an integer already).
If I get 0.323 leave as it is (its a float already).

This is my try. The thing is that this also converts me all the floats into integers, and I don't want this. Can someone give me hand?
def parse_value(value):
    try:
       value = int(value)
    except ValueError:
        try:
            value = float(value)
        except ValueError:
            pass

Thanks in advance
Comment: Why are you making a distinction between float and int? For most usecases `float(value)` is enough.
Answer: Use following:
def convert(self, value)
    a=value
    b=float(a)
    if(b==int(b)):b=int(b)

    print(b)

Answer: def parse_value(value):
    try:
       print(type(value))
       if type(value) is float:
           print(value)
       elif type(value) is int:
           print(value)
       elif type(value) is str:
           value = float(value)
           print(value)

    except ValueError:
        try:
           print(value)
        except ValueError:
            pass

Answer: Would this work for you?
def parse_value(value):
    f = float(value)
    r = f if f != int(f) else int(f)
    return r


Stuck on this cyclic 3-variables-inequality with constraint

Question: Problem Statement:
For $a,b,c>0$ and $a+b+c=3$, I'd want to prove that
$$\frac{1}{a^2+b+c}+\frac{1}{b^2+a+c} +\frac {1}{c^2+a+b} \leq1 .$$
I am a beginner when it comes to inequalities. This problem appeared on my test and I tried everything I knew:

AM-GM-HM,
Cauchy-Schwarz,
homogenization,
elimination,
properties of quadratic functions,
etc ....

but I was not not able to prove it. In many cases I got the upper bound as greater than one, so I knew that my result was very weak compared to the inequality given.
I just need a hint. :-)
Answer: By C-S
$$\sum_{cyc}\frac{1}{a^2+b+c}=\sum_{cyc}\frac{1+b+c}{(1+b+c)(a^2+b+c)}\leq\sum_{cyc}\frac{1+b+c}{(a+b+c)^2}=1.$$
Comment: This solution is rather elegant in my eyes as the initial constraint and
Cauchy-Bunyakovsky-Schwarz are perfectly combined (+1) to yield the result.
*But Michael, why don't you take the few seconds to write out
'Cauchy-Schwarz', instead of the acronym?* With which many readers are **not familiar**.
Would be a real gain, now and in the future since the reader can concentrate on the content without having first to decipher the accompanying text. Even if the OP writes "I just need a hint.".
Comment: @Hanno Because it's very known as AM-GM for example. I am always ready to explain, if somebody looks for this. Thank you!
Comment: Michael, I do not share your opinion regarding your first sentence.
Answer: Also, the Tangent Line method helps.
Indeed, $$1-\sum_{cyc}\frac{1}{a^2+b+c}=\sum_{cyc}\left(\frac{1}{3}-\frac{1}{a^2-a+3}\right)=\frac{1}{3}\sum_{cyc}\frac{a^2-a}{a^2-a+3}=$$
$$=\frac{1}{3}\sum_{cyc}\left(\frac{a^2-a}{a^2-a+3}-\frac{a-1}{3}\right)=\frac{1}{9}\sum_{cyc}\frac{(a-1)^2(3-a)}{a^2-a+3}\geq0.$$


How to use WeirdX applet instead of X11 for remote connections in Mac OS X?

Question:
When I am away, I've got an Apple PowerBook set up to use X11 forwarding with SSH to connect to a remote iMac client in my room for server administration.
Whenever I start X client programs on the client iMac, X11 would start on my PowerBook, which is OK, but...
Question: Is it possible to change my settings so I can use the WeirdX (a web-based java X server) applet to take care of the X client programs instead of Mac OS X's default X11? Is there a config file I can edit to chance the $DISPLAY variable, and what should I set it to? Is this even the issue?

Thank you very much.
Answer: The default $DISPLAY variable is set by /System/Library/LaunchAgents/org.x.startx.plist.  You can disable the X11 autostart feature by running
sudo launchctl unload -w /System/Library/LaunchAgents/org.x.startx.plist

but that shouldn't be necessary — just set $DISPLAY by whatever means you feel like using (e.g. ~/.bash_profile) and ssh away.