Remove Magento unused files and database tables

Question: Iv been developing a Magento site for a few months now, during this process I have installed and removed many extensions that themselves have created many tables within my database and files on the server, along with that I've tried building multiple extensions of my own including lots of files.
Im wondering if there is a way to monitor which files are being read and used, and then have the ability to remove any, unused tables, or files.
Basically i just want to clean up the store of unused files and tables.
does anyone know if this has been done before? also where to start looking if it has?
Regards
Comment: By the way, don't forget to accept answers. It looks like you have had some good answers for your questions, and it helps you and the SO community when answers are accepted (the checkbox below the vote indicator).
Comment: There you go. ;-) You can now upvote. You can accept answers no matter what your reputation is.
Comment: haha yeah, sorry I must have only tried to press the up arrow, I was getting a little annoyed at not being able to do anything to thank people :/ still learning this ins and outs of this site
Comment: can I ask what the difference between a green tick and the up arrow is?
Comment: The green check marks the question as answered. That answer will always be at the top of other answers, and helps other visitors know what fixed your problem. Mouse over the upvote (or downvote) buttons for a short description of what they do.
Answer: To my knowledge, there isn't a tool that will "remove all unused extension tables" automagically, as that could potentially be quite dangerous (removing still used, or tables where the extension is just disabled, etc).
If you want to proceed, BACK IT UP, BACK IT UP, BACK IT UP!!. Then, and only then, manually go through the database and look at each table (phpMyAdmin makes this a lot easier). If it starts with an extension's namespace that is not being used (usually table names are like: namespace_module_tablename), look at the table to see if it has current/relevant data in it. There is a handy reference for the Magento DB schema (http://www.magereverse.com/). However, I don't know how familiar you are with Magento DB, and if one is not careful/knowledgeable, you can cause tremendous damage.
If you aren't super familiar with Magento, I would steer you away from doing this operation. Depending on if it is a live store or just your development machine, you could always start over. Then you know it is a good, clean start.
Comment: hmm, ok, im probably not classed as super familiar, although I have spent months staring at different tables while creating my site. I leave it be until I feel I fully understand the workings of the magento database system.(iv already experienced the "tremendous damage" you speak of :P ) Thanks for the response :)
Answer: Unused tables don't take up much room and removing them can cause so much more grief on version upgrades than the room you'll save if you're looking to remove any tables that Magento itself creates for Magento modules you've disabled.
As to working with third party modules, since Magento's free, it's best if you set up a separate test server for module installations to see if they're really useful and/or compatible and then install them in your dev installation for running with your website.
That being said, after the fact, every module has a mysql installer script that you can read to see what database changes were made so you can attempt to reverse them out. These usually live in app/code/local/(namespace)/(modulename)/sql/(modulename)_setup/* or app/code/community/(namespace)/(modulename)/sql/(modulename)_setup/*. They will be named along the lines of mysql4-install-*.php or mysql4-upgrade-*.php though any of the above conventions could be broken by third party developers who don't follow the conventions closely.
You can use the SQL code in these to reverse out the changes the module made. Backups highly recommended.


Continuity in time variable

Question: Given a function $u \in L^{1}(\mathbb{R} \times (0, \infty))$ does there exist a function $v \in C((0,\infty); L^1(\mathbb{R}))$ such that $v=u$ a.e. in $\mathbb{R} \times (0, \infty).$
If not is there any additional assumptions on $u$ which ensures existence of such a $v$?
Answer: The answer is NO. Take $u(x,t)=e^{-|x|}g(t)$ where $g$ is a positive integrable function on $(0,\infty)$. If $v$ exist as stated then there is at least on $x$ such that $e^{-|x|}g(t)=v(x,t)$ for almost all $t$. But then $t \to \|v(x,t)\|_1$ is
continuous which implies $t \to g(t)$ is almost everywhere equal to a continuous function. But this is not true in general. An example of a function $g$ for which this fails is $I_C$ where $C$ is  a fat Cantor set.
Trying to get a continuous function which is almost everywhere equal to a given integrable function seems pretty unrealisitic and I cannot think of any simple sufficient conditions for this.

Continuity in time variable


Discontinuous and converge uniformly

Question: constract a sequence of functions on [o,1] each of which is discontinous at every point on [0,1] and which converges uniformly to a function that is continous at every point
Answer: $$  f_n(x)=\begin{cases}
    0 & \text{if } x \text{ is rational,} \\
    \frac{1}{n} & \text{if } x \text{ is irrational.}
  \end{cases}
$$
Answer: $$f_n(x) =\begin{cases} \frac1n, & x \notin \mathbb{Q}  \\0, & x \in \mathbb{Q} \end{cases}.$$ This  sequence of function converges uniformly to the function $f(x) =0$ for all $x$.

Discontinuous and converge uniformly


Biostats two way anova in R boxplot visualisation

Question: I am having a problem analyzing some data from a recent experiment in R.
The experiment was balanced with 5 replicates in each group. It included two factors (plant type and leaf age) with 15 combinations (5 plant types x 3 age classes within each plant type).
I arranged the data in long form and conducted a two way ANOVA in R. The main effects were separately significant, but the interaction of both was not.
Now I am unsure what my next steps are.
I want to display my results in boxplots showing which plant types have significant differences, and which leaf ages are significantly different?
Comment: Welcome to our site.  Your question is unclear: are you asking whether boxplots would be useful or are you asking how to produce those boxplots?
Comment: Box plots are typically based on medians and quartiles. ANOVA is based on means and variances or SDs. Looking at the data with boxplots might well help you understand the ANOVA, but the pertinence is indirect.
Comment: Thank you for your reply! Sorry I was not clear. The issue isn't drawing the box plots. I generated those fine. What I cannot seem to do is to determine the significance of each set (and therefore box) in relation to the group. In the example I have, the significance of the set is indicated as a '*' above each box as an annotation.
Comment: The title and question are not clear then. You emphasised box plot visuallzation in your title and closed with "I want to display my results in box plots". Please consider rewriting the title and text to focus on what you want to know.
Answer: You should try the predictmeans::predictmeans() function - this will take the fitted model and produce graphs with least significant difference bars which will clearly show which groups are different from one another. The function also allows you to chose a method for correcting when conducting multiple comparisons.
I wouldn't recommend boxplots for the above mentioned reason in the comments and they only way I have seen them used to show differences between groups is putting letters above them to show which pairs are different - this is quite confusing for the reader though.
Comment: Thank you for your reply! Ok, will definitely try this. I am also reconsidering the use of boxplots too. If I may ask another question though - after thinking over the stats some more, I was also considering whether a nested anova is more appropriate for my analysis rather than two way?
Comment: No worries. Personally, I typically avoid ANOVAs altogether as they have a strict set of assumptions that are rarely met, and don't usually handle complex designs well. Instead I would recommend a mixed-effects model - you can fit these with the `lme4` package and they are compatible with the `predictmeans` function. What does your data look like? Are group sizes equal? Is your data normally distributed? How would you nest? Sorry for all the questions but I can't offer more guidance without understanding your data.


Como montar consultas customizada usando Entity Framework?

Question: Possuo um banco SQL Server que é acessado via ORM Entity Framework Core, onde acesso uma coleção de produtos, estes produtos são filtrados através de um DTO que possui os termos da busco, que pode ser composta ou simples, exemplo: o cliente pode informar na busca somente o Nome do produto ou Nome, Material de fabricação e UF.
A questão é como montar uma query legível que abarque todos os cenários customizáveis?
DTO de pesquisa:
public class DtoPesquisaProduto
{
    public string Nome { get; set; }

    public string Material { get; set; }

    public EstadosEnum? Estado { get; set; }

    public decimal PrecoInicial { get; set; }

    public decimal PrecoFinal { get; set; }
}

A Consulta:
_context.Produtos
.Where(x => x.Nome == pesquisa.Nome
    && x.Material == pesquisa.Material
    && x.Estado == pesquisa.Estado
    && (x.Preco >= pesquisa.PrecoInicial && x.Preco <= pesquisa.PrecoFinal))
 .ToListAsync();

A consulta Where deve ser dinâmica considerando somente a expressão cujo valor for diferente de nulo.
Answer: Um coisa que poucas pessoas entendem é que o LINQ é um construtor de expressões. Ele não está executando tudo aquilo de uma só vez, ele faz um passo de cada vez, desde que esteja em métodos diferentes. Seu código é, em essência, o mesmo que:
IQueryable<Produtos> query = _context.Produtos;
query = query.Where(x => x.Nome == pesquisa.Nome);
query = query.Where(x => x.Material == pesquisa.Material);
query = query.Where(x => x.Estado == pesquisa.Estado);
query = query.Where(x => x.Preco >= pesquisa.PrecoInicial && x.Preco <= pesquisa.PrecoFinal);
resultado = query.ToListAsync();

Agora basta colocar um if para cada linha para decidir se a expressão vai entrar ou não. Exemplo:
IQueryable<Produtos> query = _context.Produtos;
if (pesquisa.Nome != null) query = query.Where(x => x.Nome == pesquisa.Nome);
if (pesquisa.Material != null) query = query.Where(x => x.Material == pesquisa.Material);
... //aqui coloca tudo o que deseja
resultado = await query.ToListAsync();

Coloquei no GitHub para referência futura.
E pense se realmente o Async() é a melhor opção, em muitos casos ele fica pior, especialmente se não for usado se forma correta. E se questione se esta é a hora certa para dar o ToList(), é muito comum que as pessoas deem antes do que deve por não entender o LINQ. _ não é idiomático em C#. Mas essas são outras questões.
Isto funciona bem para casos puramente de and, mas se precisa algo mais complexo aí pode usar um predicate builder ou biblioteca que construa dinamicamente para você.
Comment: Sinceridade eu trabalho com EF a muito tempo e isso que está explicado acima não faz muito sentido, eu queria realmente entender antes de colocar uma opinião plausivel, visto que o ToListAsync no final do código não terá os filtros posteriores! A resposta mais correta é ao do Marcelo que levou votos negativos sem necessidade (talvez por causa do IEnumerable, talvez)
Comment: Eu questionei o `ToListAsync()`, apenas deixei o que ele está fazendo.  De fato eu esqueci de colocar a atribuição. Bom você ter questionado porque eu não tinha percebido. A do Marcelo usa `HasValue` em campos que claramente são por referência, e tem um método que só ele sabe o que faz, e o erro que você apontou. então não sei como isto pode ser certo.
Comment: Bom `_context` não seria uma atribuição legal, é a variável `DBContext`, deve ser feita para outra variável mediante pergunta. Posso concordar que tem alguns pontos que melhora a resposta do amigo, mas, em compensação a dele antes era a mais próxima da realidade, inclusive Maniero, tem duplicata, eu já vi, mas, não encontro pelo sistema de busca.
Comment: Acho que tem razão. Se tiver algo mais que viu de errado eu melhoro. Obrigado pelos questionamentos, só colaborou pra um resultado melhor para todos. Realmente a busca é ruim ,se achar marca lá que eu termino de fechar.
Comment: Maniero para essa sua função funcionar você tem que alterar de IQueryable para IQueryable e alterar de query.Produtos.Where para query.Where depois nas query subsequentes.
Comment: @LucianoOiticicaLemgruber sim, tinha esses erros e corrigi agora, obrigado, eu reconheço meus erros e quem me ajuda. Só não entendi porque o mesmo erro em outra resposta recebe parabéns.
Answer: Os .Where(this IEnumerable<T>, Predicate<T>) são carregados preguiçosamente, ou seja, não são processados no momento da declaração, mas sim quando a consulta final (o resultado final do .Where()) é iterada.
IQueryable<Produto> query = _context.Produtos;

if (!string.IsNullOrEmpty(pesquisa.Nome))
{
    query = query.Where(where => where.Nome == pesquisa.Nome);
}

if (!string.IsNullOrEmpty(pesquisa.Material))
{
    query = query.Where(where => where.Material == pesquisa.Material);
}

if (pesquisa.Estado.HasValue)
{
    query = query.Where(where => where.Estado == pesquisa.Estado.Value);
}

// ... assim por diante, para cada propriedade

return query.ToList(); // Materializa query.

Comment: `IEnumerable query = _context.Produtos;` o correto seria `IQueryable query = context.Produtos;`, se mudar isso a sua resposta é a correta e o mais engraçado levar votos negativos.
Comment: Por questão de ética e igualdade, porque colocar um `return Mapear(query)` em sua resposta? não faz parte da pergunta original, e também não faz parte de um método ou classe da sua pergunta, poderia explicar ou até remover colocando um `query.ToList()` no final. ?
Comment: Concordo com o Virgilio Novic essa é a melhor resposta, reformulei a minha resposta com base nos seus comentários Virgilio Novic.
Comment: @LucianoOiticicaLemgruber nem o Virgilo concorda, ele apresentou dois problemas nela, e eu apresentei um mais. De qualquer forma obrigado por concordar com a minha resposta já que a nova versão da sua faz o mesmo que está na minha.
Comment: Alterado para `IQueryable`.
Comment: Alterado para `query.ToList();`.
Answer: Olá Ricardo boa noite.
Vamos lá você deve querer isso dentro de uma mesma consulta correto ?
para isso você deve usar um operador ternário
await _context.Produtos
.Where(x => pesquisa.Nome != null ? x.Nome == pesquisa.Nome : false)
.Where(x => pesquisa.Material  != null ? x.Material == pesquisa.Material : false)
.Where(x => pesquisa.Estado != null ? x.Estado == pesquisa.Estado : false)
.Where(x => pesquisa.PrecoInicial != null ? x.Preco >= pesquisa.PrecoInicial : false)
.Where(x => pesquisa.PrecoFinal != null ? x.Preco <= pesquisa.PrecoFinal : false)
.ToListAsync();

Um pouco sobre operador ternário com o Mestre Macoratti
http://www.macoratti.net/14/11/c_tern1.htm
Dessa forma irá procurar por todos os atributos na mesma consulta.
UPDATE
Peço desculpas tinha colocado um true no final que pega valores nulos da tabela.
Utilize o false que ele não vai buscar valores nulos da tabela.
Segue abaixo exemplo da query gerada em uma tabela minha com o true
.Where(x => pesquisa.PrecoInicial != null ? x.Preco >= pesquisa.PrecoInicial : true)

SELECT [a].[ViaturasID],[a].[ValorPrestacao]
FROM [Viaturas] AS [a]
WHERE ((@__prestacaoInicial_0 IS NOT NULL AND ([a].[ValorPrestacao] >= @__prestacaoInicial_1)) OR @__prestacaoInicial_0 IS NULL) AND ((@__prestacaoFinal_2 IS NOT NULL AND ([a].[ValorPrestacao] <= @__prestacaoFinal_3)) OR @__prestacaoFinal_2 IS NULL)

e com o false
.Where(x => pesquisa.PrecoInicial != null ? x.Preco >= pesquisa.PrecoInicial : false)

SELECT [a].[ViaturasID],[a].[ValorPrestacao]
FROM [Viaturas] AS [a]
WHERE (@__prestacaoInicial_0 IS NOT NULL AND ([a].[ValorPrestacao] >= @__prestacaoInicial_1)) AND (@__prestacaoFinal_2 IS NOT NULL AND ([a].[ValorPrestacao] <= @__prestacaoFinal_3))

================ NOVA SOLUÇÃO ================
Me baseando nos comentários do Virgilio Novic realmente vi que assim vai ficar mais eficaz a consulta.
Sendo que isso veio tudo a partir da resposta do Marcelo Uchimura.
IQueryable<Produtos> query = _context.Produtos;

if (pesquisa.Nome != null)
{
    query = query.Where(x => x.Nome == pesquisa.Nome);
}
if (pesquisa.Material  != null)
{
    query = query.Where(x => x.Material == pesquisa.Material);
}
if (pesquisa.Estado != null)
{
    query = query.Where(x => x.Estado == pesquisa.Estado);
}
if (pesquisa.PrecoInicial != null)
{
    query = query.Where(x => x.Preco >= pesquisa.PrecoInicial);
}
if (pesquisa.PrecoFinal != null)
{
    query = query.Where(x => x.Preco <= pesquisa.PrecoFinal);
}
query.ToList();

Exemplo da query gerada em uma tabela minha
SELECT [m].[ViaturasID],[m].[ValorPrestacao]
FROM [Viaturas] AS [m]
WHERE ([m].[ValorPrestacao] >= @__prestacaoInicial_0) AND ([m].[ValorPrestacao] <= @__prestacaoFinal_1)

Caso queira usar .ToListAsync() mude o final para
await query.ToListAsync();

Comment: Isto será extremamente ineficiente e gerará uma *query* terrível.
Comment: Ninguém questionou se você está aqui para ajudar ou não. Ele quer montar um condição dinamicamente, ele tem vários campos em uma estrutura na memória, aí se o dado não for nulo ele deve entrar na condição, se o dado não for nulo não tem porque usá-lo, ele não deve entrar na condição, o seu tudo está entrando na condição. Experimenta gerar a *query* com 2 ou mais condições.
Comment: Sim, eu mostrei um problema no código, você começou fazer questionamentos especulativos, e continua, a hostilidade parte de sua parte que quer ver problema em um simples questionamento de um problema no seu código. Se você se ater ao problema e ao código e não às pessoas a hostilidade cessa, e assim não criará discussão que não deseja. Se alguém desrespeitou você sinalize a postagem que um outro moderador avaliará a situação. Aqui no SOpt nós avaliamos as soluções para sempre obter o melhor possível, se não deseja que as pessoas avaliem o que você posta terá problemas aqui.
Comment: Se você acha que uma *query* que tem verificações desnecessárias está limpa, e que por causa disto não consegue utilizar possíveis índices, então tá.
Comment: Estou aqui para tentar ajudar. Se ele quer buscar por todos os parametros em conjunto todos tem que estar na mesma query.

Ele não quer buscar por Nome = XX ou Material = Y. Ele quer buscar Nome = X e Material = Y.
Answer:  await _context.Produtos
.Where(x => (pesquisa.Nome == null || x.Nome == pesquisa.Nome)
       &&   (pesquisa.Material  == null || x.Material == pesquisa.Material)
       &&   (pesquisa.Estado == null || x.Estado == pesquisa.Estado)
       &&   (pesquisa.PrecoInicial == 0 || x.Preco >= pesquisa.PrecoInicial)
       &&   (pesquisa.PrecoFinal == 0 || x.Preco <= pesquisa.PrecoFinal))
.ToListAsync();``

Faça igual a uma consulta no SQL, se ele for nulo ele não fará nada na pesquisa, caso exista dados ele fará a comparação de cada um deles.
Obs: comparação de valores Decimal == 0 pois ele não pode ser nulo.
Comment: eu entendo como a query funciona, eu ja testei e faço varias das mesmas em sistemas gigantescos e complexos, mas é isso amigo, se você sabe mais que eu tudo bem, estou aqui pra tentar ajudar apenas, não precisar ser rude assumindo que você sabe tudo e as pessoas são leigas.
Comment: Desta forma os nulos farão parte da consulta e não é o que ele deseja.
Comment: @Maniero não, dessa forma se um parametro vier nulo ele não fará nada, caso ele for diferente de nulo ele faz a comparação
Comment: Você não entendeu a questão, ele fará parte da consulta, ele é ineficiente, ele gera uma consulta ruim, eu já comentei na outra resposta. O AP quer que a consulta seja construída só com os dados existentes, que seja eficiente, por isso precisa gerar dinamicamente, se for assim não é uma geração dinâmica, é estática com verificação posterior em todas as linhas de algo que pode ser feito uma única vez antes e que provavelmente vai impedir o uso de um índice, e pode ficar tudo trágico.
Comment: Não concordo com seu ponto de vista, a validação é da variavel de pesquisa, caso ela for nula ela não fará parte da query, eu ja usei muitas vezes desse modo e nunca gerou consultas lentas ou algo do tipo, porém posso estar errado ou realmente não ter entendido a questão.
Comment: Não é ponto de vista, é como o EF funciona. Você entende como ele gera a *query*? E você mediu usando assim e da forma correta? Porque o que mais vejo hoje em dia é as pessoas usarem coisas piores e nem se darem conta.
Comment: Ninguém estava sendo rude, até agora, eu estou apenas discordando do que postou, não pode? Tem que aceitar o que você diz sem contestar? Só você sabe e ninguém pode dizer o contrário? Mostre onde eu assumi que eu sei tudo e você sabe nada? Eu até fiz uma pergunta para entender o seu conhecimento. Bom, eu já mostrei o problema da resposta pra outras pessoas saberem que assim não é adequado, agora é com elas entenderem se você está certo ou não, seria melhor que esse problema fosse resolvido, mas você pode deixar como achar melhor.


The bean could not be injected as a 'Type' because it is a JDK dynamic proxy that implements: reactor.fn.Consumer

Question: My Spring 4 application, which uses Reactor 2, fails to start with:
***************************
APPLICATION FAILED TO START
***************************

Description:

The bean 'orderHandlerConsumer' could not be injected as a 'fm.data.repository.OrderHandlerConsumer' because it is a JDK dynamic proxy that implements:
    reactor.fn.Consumer

Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

The OrderHandlerConsumer is really simple:
@Service
@Order(Ordered.HIGHEST_PRECEDENCE)
public class OrderHandlerConsumer implements Consumer<Event<OrderEnvelope>> {
    @Override
    public void accept(Event<OrderEnvelope> event) {
        event.getData().getLatch().countDown();
    }
}

Any ideas what might be going awry?
Comment: this link may help you: [https://stackoverflow.com/questions/39483059/transactional-annotation-error#answer-43715808](https://stackoverflow.com/questions/39483059/transactional-annotation-error#answer-43715808)
Answer: While the other answer will solve this issue, I think it will be more appropriate for me to explain why applying proxyTargetClass = true will fix this.
First of all, Spring, as a framework, utilizes proxying in order to supply the bean with some extended functionality, such as declarative transactions via @Transactional, or caching by the means of @Cacheable, etc. There are, in general, 2 ways(*) Spring can create proxy on top of your bean:

JDK dynamic proxying
CGLib proxying

Official documentation on this, in case you are interested.
Spring can create JDK dynamic proxy of the bean (in case proxying is required for this bean of course) if original class of the bean implements at least one interface. So spring basically create another implementation of this interface at runtime with some additional logic on top of original class.
What is the problem: if the bean is proxied by the means of JDK dynamic proxying , then you cannot inject this bean via its original class. Something like this:
@SpringBootApplication
@EnableTransactionManagement(proxyTargetClass = false)
public class StackoverflowApplication {

    @Autowired private SomeService service;

    public static void main(String[] args) {
        SpringApplication.run(StackoverflowApplication.class, args);
    }
}

@Service
class SomeService implements SomeInterface {

    @Override
    @Transactional
    public void handle() { }
}

interface SomeInterface {
    void handle();
}

won't work. Why? Well, because @Transactional tells Spring that it needs to create proxy of SomeService at runtime, and within @EnableTransactionManagement I specifically asked Spring to make it by the means of JDK dynamic proxy - Spring will succeed, since JDK dynamic proxy can be created, but the problem is at runtime there is not bean of type SomeService, there is only a bean of type SomeInterface (by the way, if you inject service here not by the class, but by the interface - it will work, I assume you understand the reason by reading explanation above).
Solution: by applying @EnableTransactionManagement(proxyTargetClass = true) (notice true value here) you force spring to create CGLIB proxy (this rule is applicable only for beans that utilize declarative transaction management, i.e. via annotations). In case of CGLIB proxying, Spring will try to extend the original class, and add additional functionality at runtime in the generated child class. And in this case injection by class will work - because the bean extends class SomeService, so
@Autowired
private SomeService someService;

will work perfectly fine. But, in general, if possible, inject bean by  interface, not by class. In this case both CGLIB and JDK dynamic proxy will work. So, be aware of proxying mechanisms spring can use. Hope it helped, have a nice day.
Answer: In your application class file where you define it as Spring application, add underneath it.
@SpringBootApplication
@EnableCaching(proxyTargetClass = true)

Comment: @Rohan could you explain your answer please?
Comment: It is what the tip suggests in the console: Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on '@EnableAsync' and/or '@EnableCaching.'
Comment: @RexSplode This doesn't explain the cause behind this suggestion.
Answer: You can assign a bean name to your OrderHandlerConsumer class so that Autowire resolution will be easier, Moreover, Instead of Autowiring with the concrete class, try to auto-wire with the interface. So that you can change @Service annotation to,
@Service(value="orderHandlerConsumer")

and try to Autowire with the interface type,
@Autowire
reactor.fn.Consumer orderHandlerConsumer;

Answer: Please try autowiring as below
class Test{
    @Autowired
    private Consumer orderHandlerConsumer;
}

Answer:
If the target object to be proxied implements at least one interface
then a JDK dynamic proxy will be used. All of the interfaces
implemented by the target type will be proxied. If the target object
does not implement any interfaces then a CGLIB proxy will be created.

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch08s06.html
You can call it two ways.
1st way is without mentioning the proxy [with default proxy], you can Autowire it by the interface like below.
@Autowired
private Consumer orderHandlerConsumer;

Spring AOP will create an instance for OrderHandlerConsumer.
2nd way is, mention the proxy in the bean as ScopedProxyMode.TARGET_CLASS.
then you can Autowire an instance without the interface [based on the class].
@Service
@Order(Ordered.HIGHEST_PRECEDENCE)
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class OrderHandlerConsumer implements Consumer<Event<OrderEnvelope>> {
    @Override
    public void accept(Event<OrderEnvelope> event) {
        event.getData().getLatch().countDown();
    }
}

and Autowire by the class like below.
@Autowired
private OrderHandlerConsumer orderHandlerConsumer;


JPA why OrderBy is applied to Set

Question: JPA why OrderBy is applied to Set?
https://docs.oracle.com/javaee/7/api/javax/persistence/OrderBy.html
<code>@Entity
public class Person {
     ...
   @ElementCollection
   @OrderBy("zipcode.zip, zipcode.plusFour")
   public Set<Address> getResidences() {...};
   ...
}
</code>
The Set is supposed to be not ordered. Is it meaningful to annotate @OrderBy
on attributes with Set type?
Comment: *Set is supposed to be not ordered*: that depends on the Set implementation. A LinkedHashSet has a well-defined order, for example. Either it's a documentation error, or, more reasonably, the JPA provider must make sure to use an ordered set implementation in that case.
Comment: Set is a collection that doesn't allow duplicates. It has no restrictions on ordering, so OrderBy is just as valid on a Set as it is on List or Collection.
Comment: "It has no restrictions on ordering" ? what does it mean?
Answer: I think the answer marked as checked on this question can answer also yours.
As mentioned there, the annotation "Specifies the ordering of the elements of a collection valued association or element collection at the point when the association or collection is retrieved."
From what I understand, the annotation is not necessarily connected with the order that the elements are inserted on the Collection type that we use in the entity class.

JPA why OrderBy is applied to Set


Pass constant to rails before filter exceptions

Question: I've got several before filters similar to:
before_filter :setup_plan, except: :some_action, :another_action, :yet_another_action
But I have a 3 or 4 exceptions to many before filters. At first I was going to change the logic in all of my before_filter methods, but I found myself repeating a lot of code. In a more perfect world I would have a seperate controller for the actions I want to add, but I've got to add the actions in the same controller, and work around the structure that's already in place.
What I want to do is create a constant or variable with the methods I want to skip in my before filters, such as
ACTIONS_TO_SKIP = [:some_action, :another_action, :yet_another_action]

And then simply use before_filter :setup_plan, except: ACTIONS_TO_SKIP
I get an uninitialized constant error when doing this.  I tried moving this to a method in a helper and also got an undefined method error.
I know I'm missing something, but can't figure it out.  Is there really no way to pass an method or constant that returns an array of methods I want to skip in my before filters? Just trying to make my controller a little bit cleaner and less verbose.
Comment: ok, then define constant before its used :)
Comment: Please provide a [mcve]. "I get an error" is not sufficient information for us to diagnose the problem. What code produces the error? What exactly does the error say?
Comment: where do you define the constant?
Comment: I'm declaring the constant directly after the before filters in the controller, here is the error when trying to access one of the views `uninitialized constant SubscriptionsController::ACTIONS_TO_SKIP`
Comment: @apneadiving good call, don't I feel silly
Comment: this is how we all learn you know...
Answer: You will need to declare the constant BEFORE the call to skip. The file is interpreted top down.
class FoosController
  ACTIONS_TO_SKIP = [:yes, :this, :and, :something, :more]

  before_filter :setup_plan, except: ACTIONS_TO_SKIP
end

Note that in recent Rails versions this is now called before_action:
Rails 4: before_filter vs. before_action
(perhaps you want to upgrade...)
Answer: You can try something like this:
before_filter :my_before_filter, if: :action_to_skip?

def action_to_skip?
  %w[some_action another_action yet_another_action].member?(action_name)
end

Comment: I think this will do, just unless: instead of if: , I want to NOT do the before filter if action_to_skip? is true, I'm gonna give it a go
Comment: Tried this but it execute the before filter anyway
Comment: https://apidock.com/rails/v4.0.2/AbstractController/Callbacks/ClassMethods/before_action
I tried before publishing the answer. It must work. Can you provide part of your code?


Symfony 5, Doctrine - Best Practice for Inserting a "Miscellaneous" Script

Question: The Problem: I'm looking to implement the DateTime script found in the Doctrine 2.7 docs here. I'm having trouble figuring out where this script should naturally go in Symfony 5's file structure.
The Setup: Used Composer to create a Symfony 5 website skeleton using composer create-project symfony/website-skeleton.
The Context: I don't have any real code implemented yet as I'm still trying to learn how Symfony works with Doctrine. I'm trying to do everything right with Symfony, including figuring out where files should go. From what I understand, each php script found in src is either a Controller, an Entity, or a Repository. I don't see where to reasonably put the DateTime script without making another folder.
Any guidance is much appreciated! Thank you.
EDIT: The specific script I'm referring to is this class definition of UTCDateTimeType. I was under the impression that a skeleton was made to be THE file structure you worked with to allow for easy maintainability.
<?php

namespace DoctrineExtensions\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class UTCDateTimeType extends DateTimeType
{
    /**
     * @var \DateTimeZone
     */
    private static $utc;

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value instanceof \DateTime) {
            $value->setTimezone(self::getUtc());
        }

        return parent::convertToDatabaseValue($value, $platform);
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if (null === $value || $value instanceof \DateTime) {
            return $value;
        }

        $converted = \DateTime::createFromFormat(
            $platform->getDateTimeFormatString(),
            $value,
            self::getUtc()
        );

        if (! $converted) {
            throw ConversionException::conversionFailedFormat(
                $value,
                $this->getName(),
                $platform->getDateTimeFormatString()
            );
        }

        return $converted;
    }

    private static function getUtc(): \DateTimeZone
    {
        return self::$utc ?: self::$utc = new \DateTimeZone('UTC');
    }
}

Comment: It's just a skeleton. Files can have other purposes. You're free to make your own additional folders to cover those purposes.
Comment: which DateTime script, could you please be more specific?
Comment: I was looking at the first script under the header "Handling different Timezones with the DateTime Type" which defines the class UTCDateTimeType. I haven't worked with many frameworks before so I wasn't sure if the file structure was best left as close to the skeleton as possible.
Answer: I like to put doctrine types into src/Types (yeah, new folder*) and unless you're importing UTCDateTimeType from a library, I would change the namespace to be in line with convention (namespace would be App\Types and FQCN App\Types\UTCDateTimeType).
Adding the type to doctrine is somewhat easy, if you know where - config/packages/doctrine.yaml - this probably requires setting the typename via getName as seen in here https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/cookbook/custom-mapping-types.html
doctrine:
    dbal:
        types:
            #nameOfType: fullyQualifiedClassName
            utcdatetime: App\Types\UTCDateTimeType

(this probably works if you set the name of your type to datetime and datetimetz, my short incomplete tests suggest so...)
however, the tutorial you linked said it wants to override the type. I don't know how to achieve this with config (if it's even possible - maybe you ), but you always have the chance to add the noted lines to your Kernel::configureContainer or even further up the line in your public/index.php.
*folders aren't magical. the existing ones are just the most common ones that are almost always used. adding new ones isn't unusual, so feel free to add them.


Cannot read properties of undefined (reading '0') while passing values to another component

Question: I have written the following code to pass values to infobox but i am getting an error
uncaught TypeError: Cannot read properties of undefined (reading '0').please tell where i am wrong.
import React,{useState} from 'react'
function App() {
   const [specificState, setSpecificState] = useState({});
   const jsondata1 = await fetch('https://covid-19-fastest-update.p.rapidapi.com/summary');
    const myData1 = await jsondata1.json();
    const indData = myData1.Countries[77];
   const getdata=()=>{
    const temp =[];
     temp ['Confirmed']= [indData.NewConfirmed, indData.TotalConfirmed]
     temp['Recovered'] = [indData.NewConfirmed, indData.NewConfirmed - indData.TotalDeaths]
     temp ['Deaths']= [indData.TotalDeaths, indData.NewDeaths]
    setSpecificState(temp);
   }
   useEffect(() => {
    getdata();
   }, [])

  return (

 <InfoBox title="Coranavirus cases" cases={ specificState.Confirmed[0] }
   total={ specificState.Confirmed[1] } />

  )
}

export default App

Answer: You need to make your fetch requests inside of useEffect.
update your get data function like this;

   const getdata=()=>{
  const jsondata1 = await fetch('https://covid-19-fastest-update.p.rapidapi.com/summary');
    const myData1 = await jsondata1.json();
    const indData = myData1.Countries[77];
    const temp =[];
     temp ['Confirmed']= [indData.NewConfirmed, indData.TotalConfirmed]
     temp['Recovered'] = [indData.NewConfirmed, indData.NewConfirmed - indData.TotalDeaths]
     temp ['Deaths']= [indData.TotalDeaths, indData.NewDeaths]
    setSpecificState(temp);
   }

remove the fetch and other operations from the body of the component.
then you need to wait for state to be fetched, you need to render your component conditionally.
  return (

 {spesificState.Confirmed && <InfoBox title="Coranavirus cases" cases={ specificState.Confirmed[0] }
   total={ specificState.Confirmed[1] } /> }

  )
}

maybe something like this.
Answer: When state is initially loaded, specificState is an empty object so no Confirmed property is found (undefined)
So at first render, this will throw this exception.
When useEffect runs and retrieves results, then this property is loaded and then you can use your InfoBox class.
So instead use
return (
   {specificState.Confirmed ?
 <InfoBox title="Coranavirus cases" cases={ specificState.Confirmed[0] }
   total={ specificState.Confirmed[1] } />
 : null }
  )

Answer: You can create statement using if operator in useEffect hook, because right now your fetched data is not uploaded yet when you try to use indData. Just cover your getdata function in useEffect like this:
useEffect(() => {
   if (indData) {
     getdata();
   }
}, [indData])

Also, you need to add extra values while passing cases and total attributes in InfoBox component, just pass empty array using | []


How to use variables withen the [RegularExpression] in .NET Core 2?

Question: I am working on a webapplication where'd need to validate my e-mail input field with additional regular expressions.
Model.cs ###
private string _regexOne = (@"myfirstregex")
private string _regexTwo = (@"mysecondregex");

public class InputModel
{
    [Required]
    [EmailAddress]
    [RegularExpression(((_regexOne)|(_regexTwo)), ErrorMessage = "My custom error message")] /* this line contains an error */
    [Display(Name = "Email")]
    public string Email { get; set; }

    ...
}

I'd need those regular expressions a few more times, so I want to declare them globally so I don't have to copy paste them everywhere.
However, this code above is wrong and doesn't run.
So my question(s) is/are: Can I use variable of regex in this attribute? If yes, what would the syntax be?
Comment: Why don't you code your own attribute inheriting from RegularExpressionAttribute?
Answer: Define the regular expressions as Constants and those can be used attribute declaration. See below sample :
using System;
using System.ComponentModel.DataAnnotations;

public class Program
{
    public const string Regex1 = "abc";
    public const string Regex2 = "xyz";
    public const string CompositeRegex = Regex1 + "|" + Regex2;

    public static void Main()
    {

        Console.WriteLine(Regex1);
        Console.WriteLine(Regex2);
        Console.WriteLine(CompositeRegex);
    }
}

public class TestClass
{
    [RegularExpression(Program.Regex1  + "|" + Program.Regex2)]
    public string TestProperty {get; set;}
}

You can compile and see the code in this
Live Fiddle.


How to make center align my wrapper class in HTML

Question:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

Login

Please fill in your credentials to login.

        <?php
        if(!empty($login_err)){
            echo '
' . $login_err . '
';
        }
        ?>

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">

                Username
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <?php echo $username_err; ?>

                Password
                <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                <?php echo $password_err; ?>

                <input type="submit" class="btn btn-primary" value="Login">

Don't have an account? Sign up now.

        </form>

I need to show my wrapper class at the center of the page. I have researched and find out some methods, but this only centered horizontally and the login form is at top of the page. Can someone show me how to use this code to show my login form at the center of page? I need horizontal and vertical center.
I have changed the css class as well. But no any changes.
I am getting the output as below,

I need to show as below,
Comment: There are some issues in your code. On the one hand you want a width of 500px in by inline css of your wrapper class, but on the other hand 360px in your plain css code. You should avoid mixing them up.
Comment: @Shehan Please show the rendered html, not the PHP code, unless it's significant
Answer:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

Login

Please fill in your credentials to login.

        <form action="" method="post">

                Username
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <?php echo $username_err; ?>

                Password
                <input type="password" name="password" class="form-control">

                <input type="submit" class="btn btn-primary" value="Login">

Don't have an account? Sign up now.

        </form>

This should do it. I also removed the inline css. You should avoid this in future. I took the main information from this answer.


How can I iterate over a specific dimension in an xarray Dataset and then export as a netcdf?

Question: I'm working with an xarray Dataset with four dimensions (lon, lat, lev, time) and several variables holding information on the concentration of aerial pollutants (e.g. the data variable CO has the concentration of CO at some (time, lev, lat, long) time and location). See below:
<xarray.Dataset>
Dimensions:            (lon: 1440, lat: 721, lev: 1, time: 2160)
Coordinates:
  * lon                (lon) float64 -180.0 -179.8 -179.5 ... 179.2 179.5 179.8
  * lat                (lat) float64 -90.0 -89.75 -89.5 ... 89.5 89.75 90.0
  * lev                (lev) float64 72.0
  * time               (time) datetime64[ns] 2018-01-01T00:30:00 ... 2018-01-...
Data variables:
    CO                 (time, lev, lat, lon) float32 dask.array<chunksize=(1, 1, 721, 1440), meta=np.ndarray>
    NO2                (time, lev, lat, lon) float32 dask.array<chunksize=(1, 1, 721, 1440), meta=np.ndarray>

I'm trying to do two things:

Iterate over this Dataset's time dimension and access a specific variable, NO2, at each timestep. This variable contains a set of floats with dimensions (1, 1, 721, 1440) for (time, lev, lat, long) in a single timestep. I want to determine the mean and standard deviation of all the NO2 values within that timestep and then apply a normalization formula to every NO2 value, changing the values. I then want to move to the next timestep and repeat this process.

Once all NO2 values have been appropriately modified, I want to export the Dataset as a .nc file.

At first, I used an array to hold the normalized values (see below code snippet):
norm_NO2 = []

for i in range(0, timesteps - 1):
    NO2 = data['NO2'].isel(time=i).compute().data.flatten()
    timestep_mean = np.mean(NO2)
    timestep_SD = np.std(NO2)
    timestep_normalized = (1 / timestep_SD) * (np.log(NO2 + 10 ** -32)) - timestep_mean
    norm_NO2.append(timestep_normalized)

However, I wasn't able to figure out a way to convert the array into a .nc file (either by converting array -> Dataset -> .nc, or array -> .nc).
I also tried iterating over the Dataset itself with:
for time in data.transpose("time", ...):

As my loop, but didn't get very far on that front.
I'd definitely appreciate some guidance on either of these (or a separate) approach! So long as I normalize the NO2 values at each timestep and export as a .nc, anything works. I'm brand new to working with xarray and wasn't finding anything that answered this specific question in the docs, so I've been struggling to determine the best way to go about this.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: I am not sure if I properly understood your question but I suggest some ideas. It seems that what you want to achieve could be done using xarray matrix operations instead of iterating through time.
# Compute the mean along specific dimensions:
NO2_mean = data['NO2'].mean(dim = ['lon', 'lat', 'lev'], keep_attrs = True) # NO2_mean is therefore a spatial mean, only varying along time
# Compute the STD along specific dimensions:
NO2_sd = data['NO2'].std(dim = ['lon', 'lat', 'lev'], keep_attrs = True)
# Process the full data, using spatial means and std previously obtained:
NO2_normalized = (1 / NO2_sd) * (np.log(data['NO2'] + 10 ** -32)) - NO2_mean

Note that in your case, as you are working with a lat/lon grid, you may want to do a weighted spatial mean (taking into account that cells have a different area depending on their latitude). See also this answer and this documentation.
Then you can include this xarray.Dataarray in your dataset: data['NO2_norm'] = NO2_normalized, or in a new dataset: new_ds = xr.Dataset({'NO2_norm': NO2_normalized})


One vs all SVM introduces classses imbalance

Question: For one-against-all approach, it depends on binary classifiers equal to the number of classes n. It assumes that a class is labeled as one while the rest of classes are labeled 0:
<code>model = cell(numLabels,1);
for k=1:numLabels
    model{k} = svmtrain(double(trainLabel==k), trainData, '-c 1 -g 0.2 -b 1');
end
</code>
For a large number of classes and large number of images(5000 each class). This means in the the above code one class will be 5000 vs the rest of the dataset which (n-1)*5000. Is this imbalance acceptable?. I mean one vs one would be better to avoid imbalance or is it dependent on classification problem?is it acceptable to have such situation?How to know if that is causing me a problem?
Answer: Yes, in general one vs one is a better solution in terms of balance, but it requires much higher computational and memory cost (as you need n^2 classifiers). So this is an often practise to train 1 vs all instead. To avoid this problem you can use "class weight" scheme, which ensures, that the smaller class gets more learner's focus (it is more costfull to missclassify the worse represented class).
Comment: I was wondering whether a upsampling or downsampling approach is recommended in such imbalance problem? And is "class weight" scheme equivalent to the strategy of upsampling the smaller group to alter the balance?
Comment: class weighting is recommended, not up- or downsampling. It leads to the same effect, but is more computationally feasible.
Answer: The intuitive thinking of such imbalance issue is: the minority sample may have the risk of missing TP after training. However, the one-vs-all approach includes a sum-pooling procedure that the maximum classifier will be selected among all those "TP-missing" classifiers. So a minor imbalance won't cause huge problem.


DNS Server VS DNS Record

Question: This question is to clarify a fundamental concept so that I can properly understand an error message.  My server threw a warning message that implored me to:

add 127.0.0.1 to the list of DNS servers

Would that mean that they are asking me to create a new DNS record or are they talking about something else?
If it's the former, I already have an A record for the localhost:
<code>localhost.domain.co.    IN  A   127.0.0.1
</code>
So, might it need something else?
Thanks in advance.
Comment: What was the warning message?
Comment: Which O.S. are you using?
Comment: @TeroKilkanen Thanks for the response! It was a warning message from virtualmin that stated `Virtualmin is configured to setup DNS zones, but this system is not setup to use itself as a DNS server. Either add 127.0.0.1 to the list of DNS servers, or turn off the BIND feature on the module config page.`  I obfuscated it because I wanted to clarify the likely word usage, rather than getting a whole bunch of answers to the error itself.
Comment: @Massimo Thanks for the response.  I'm using Ubuntu 12.04.
Answer: It's asking you to add localhost (127.0.0.1) as a DNS server (not a record).
So in other words, the OS will use 127.0.0.1 as a DNS server.
I don't really know what OS you're running so I can't help you further on how to fix that.
Comment: Thanks so much for the clarification.  May have been simple but that's exactly what I was looking for.
Answer: On Windows systems, this can happen if the server is running the DNS service and the user leaves the DNS server fields empty in a network adapter configuration; the message basically means "you have not configured this NIC to use any DNS server, this system is a DNS server, thus you'd probably want to use it".
Depending on your network configuration, the message can be safely ignored, unless you actually want the system to use its own DNS services for name resolution.
Case in point: one time I had to manage a server which was acting both as a perimeter firewall (using ForeFront TMG) for the company network and as the main DNS server for the company's public DNS domain. The server had two NICs, and it was a domain member; its internal NIC was configured to use two AD domain controllers as DNS servers, while the external NIC didn't have any DNS Server configured, because it only needed a public IP address. The configuration was perfectly legit, but the OS kept pestering me to configure 127.0.0.1 as the DNS server for the external NIC, because it saw there was no DNS server configured there, and the computer was running the DNS service. Needless to say, this would have been completely wrong, but there was no way to have Windows just shut up about it.

DNS Server VS DNS Record


React and Webpack: "Uncaught ReferenceError: require is not defined"

Question: I'm trying to rewrite my Webpack (5.42.0) webpack.config.js from using require() (CommonJS) to using import from (ESM). But whenever I try to load my page, I'm getting:
Uncaught ReferenceError: require is not defined
    at Module../some/path/file.js (login.bundle.js:10731)
    at Module.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Module../some/path/util.js (login.bundle.js:10564)
    at Module.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Module../some/path/module/Module.jsx (OtherFile.jsx:37)
    at Module.options.factory (react refresh:6)

I cannot figure out what causes this error. There are a lot of moving parts in the Webpack setup, but I'm guessing the reason require is not added to the bundle may be because of a Babel config issue?
I'm using hot module replacement, various plugins (Terser etc.). Excerpts from package.json and webpack.config.js are added below. I think all relevant lines are included:
// package.json excerpt:
{
  "type": "module",
  "scripts": {
    "build": "webpack --config webpack.config.js"
  },
}

// webpack.config.js excerpt:
import path from 'path';
import webpack from 'webpack';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import TerserPlugin from 'terser-webpack-plugin';

const config = () => {
  return {
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          loader: 'babel-loader',
          options: {
            presets: ['@babel/env', '@babel/react'],
            plugins: ['react-refresh/babel'],
          },
          resolve: {
            fullySpecified: false,
          }
        },
      ],
    },
    entry: {
      main: [
        `webpack-dev-server/client?http://localhost:3500/`,
        './app/App.jsx',
      ],
    },
    output: {
      filename: '[name]/[name].bundle.js',
      path: path.resolve(__dirname, 'backend/path/bundles'),
      publicPath: 'http://localhost:3500/',
    },
    // …etc…
  };
};

Answer: Does this answer your question: How can I use ES6 in webpack.config.js? ?
Long story short, webpack.config.js is parsed with Node, which doesn't supports es6 by default. You may rename your config file webpack.config.babel.js though.
This being said, using import syntax is of little importance in such a file, require looks good to me.


Probability and Cartesian Plane!

Question: Question:
(screenshot)

An injured ant named "Pipee" has got stuck at point $P\left(\frac{2}{5}, \frac{3}{5}\right)$ inside a square $A B C D$ of the Cartesian Plane where the coordinates of $A, B, C$ and $D$ are respectively $(0,0),(2,0),(2,2)$ and $(0,2)$. Pipee can only move from left to right. If the line which goes through the point $P$ and another point inside $A B C D$ denoted by $Q$ has the slope not more than $\frac{3}{4}$, only then Pipee can escape. Rafin wants to save Pipee. If he randomly chooses the point $Q$ inside $A B C D$, the probability that Pipee can get free can be written as $\frac{r}{s}$ where $r$ and $s$ are coprimes. $r+s=?$

My Approach:
My idea was finding the area of the parts dissected by the line whose slope is $0.75$. Then the probability. Alas! It went wrong.
Here's the question link
https://gonitzoggo.com/archive/problem/425/english
Comment: Please do not use pictures for critical portions of your post. Pictures may not be legible, cannot be searched and are not view-able to some, such as those who use screen readers. – For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Thanks, actually i didn't have much time to write as i had some work.. i would change it
Answer: To save the Pipee line PQ should have slope not greater than $3/4$. Line going through P and having slope $3/4$ is line $a$ with equation $y=3/5 + 3/4 \cdot (x - 2/5) = 3/4 \cdot x + 3/10$. For PQ to have slope not greater than $3/4$ point Q should lie right to P and lower than $a$ or left to P and higher than $a$. Drawing these zones and finding their area we can get that possible area for Q point is $(3/5+9/5)/2 \cdot 8/5 +$ $(17/10 + 7/5)/2 \cdot 2/5 = 127/50$. Total area of square ABCD is 4, so probability is $127/(50\cdot 4)=127/200$. Then $r+s=327$.
Answer: Firstly, lets find the eqn of line with slope 3/4 and starting at P.
The equation would be, y = $\frac{3}{4}$x + c, solving with P as a point in this line, the final equation is 20y - 15x - 6 = 0
Now,let's find the intersection between this line and the line joining line joining (2,0) and (2,2) (as we are moving right).
Substituting for x=2 in the equation we get, y=$\frac{9}{5}$.
So for Pipee to cross the y must be 0<y<$\frac{9}{5}$ and we know $\frac{2}{5}$<x<2.
Probability of random number in range of y: $\frac{9}{5}$*$\frac{1}{2}$ = $\frac{9}{10}$
Probability of random number in range of x: $\frac{8}{5}$*$\frac{1}{2}$ = $\frac{8}{10}$
so, $\frac{r}{s}$ = $\frac{9}{10}$*$\frac{8}{10}$ = $\frac{18}{25}$
r+s = 43

Probability and Cartesian Plane!


How to set the size attribute of a select field?

Question: When you use a "select" field with multiple values Drupal generates this HTML:
<select multiple="multiple" name="..." id="..." class="...">

How can I inject the size="..." attribute? This will cause the box to show more values.
Answer: You might be able to do it with the #size property of the Form API. I am not sure, but you might need to also set the #multiple property to TRUE in order for the #size to be honored.
It it also not clear from the question if you are creating your own form using the Form API, modifying an existing Form API form using a hook_form_alter(), or writing your own form HTML (which I imagine - and hope - you are not doing).
Comment: I figured it out,  $form['field_disc_topic']['und']['#size'] = 20; did the trick. Thanks again!
Comment: thanks. I'm trying to modify a term reference field in the "node add/edit" form. I'm added  $form['field_disc_topic']['#size'] = 20; with a hook_form_alter and the attribute shows up in the dpm but has no effect on the form field. I wonder if it's because the type says "container"?   http://awesomescreenshot.com/095rpiq86
Answer: Try this to modify Select list Height & width drupal Way
// Increase Height of Select list
$form['field_example1']['und']['#size'] = 15;

// Increase Height of Select list
$form['field_example2']['#size'] = 20;

Comment: This does not modify the width. Only the height of the dropdown box is adjusted.


Setting a css class for TD

Question: I am using a customized user control (that I don't have the permission to modify) which renders the HTML for a table as shown:

It lets me add any control dynamically within the  tags. My question is how would I  set the style of the cell for the table cell. Normally, I would do . Since I don't have the source code to modify it, the workaround I am using is to create a
, set the CSS class and add it to the . The code looks something like this:
  HtmlGenericControl divControl = new HtmlGenericControl("div");
  divControl.Attributes.Add("class", "myClass");
  //Add a textbox to divControl.
  //Add the divControl to the customized user control

This does not give me the same UI I am expecting.
Answer: If you can, just add a DIV before the table is generated.  The class name for the outer div will be inherited by the TD elements:

   //table code here

Then you can use CSS as follows:
.MyClassName TD { //CSS here }

Answer: Try using a SPAN instead of a DIV.  A DIV is a block-level element that carries some extra formatting baggage along with it.  The SPAN is an inline element and won't alter the presentation semantics the way a DIV will.
You might also be able to use hierarchical CSS selectors to achieve the same effect without having to wrap the contents of the table element in a container.  This would probably be true if your CSS class were to apply equally to all table elements, but wouldn't work if they were to apply to some and not others.
Answer: After your control is added to the page's control tree you can use it's "parent" property to work up the tree to the table control.
NewDynamicControl.Parent.Parent.Parent.Attributes.Add("class", "myClass")

This assumes you have good knowledge of what the usercontrol you are adding to looks like and that it won't be changed by someone else and end up breaking your code later.
Answer: Just use divs and give classes to them.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Setting a css class for TD


How to find a transversal of two lines that is also perpendicular to a plane

Question: I have this problem where I have two lines given and I have to find a transversal. However, it also has to be perpendicular to a given plane (lines are not necessarily in the given plane).
My guess was that I would have to find perpendicular lines to the plane and then see if they are also transversals of those lines. But I've been stuck. Is this the right approach? Or should I start working from the lines and then tend to the plane and transversal being perpendicular?
Answer: If $r$ and $s$ are the lines and $\vec v$ is a vector perpendicular to the plane (which shuold be easy to obtain), the plane generated by the line $r$ and the vector $\vec v$ should intersect $s$ at one point $P$. The line that passes through $P$ and is parallel to $\vec v$ should meet the conditions.
Comment: But how am I to find that generated plane with only the line and the vector? Aren't I also supposed to have a point? Or do I just choose some arbitrary point on r and use it to define that plane?


Let $f:[0,1] \to \mathbb{R}$ be continuous, differentiable on $(0,1)$ and $f(0) =0$ with $|f'(x)|\leq c|f(x)|$ for each $x \in (0,1).$ Show that $f=0$

Question: Let $f:[0,1] \to \mathbb{R}$ be continuous, differentiable on $(0,1)$ and $f(0) =0$ with $|f'(x)|\leq c|f(x)|$ ($c>0$)for each $x \in (0,1).$ Show that $f=0.$
I am aware of the several solutions to this problem on this site. My question is: Is the following attempt correct?
Let $\varepsilon>0$ be given. By uniform continuity of $f$ on $[0, 1]$ for $x, y \in [0,1],$ there exists $\delta >0$ such that $|x-y|<\delta$ implies $|f(x)-f(y)|<\frac{\varepsilon}{c}.$ Then for $x\in (0, \delta)$ we have: $|f'(x)|\leq c|f(x)|< \varepsilon.$ Since $\varepsilon$ was arbitrary, $f'(x)=0$ for $x \in (0, \delta).$ This implies that for $x\in (0, \delta)$, $f(x)= k$, for some constant $k$ but since $f(0)=0,$ by continuity we must have $k=0.$ By continuity at $x=\delta$ we also have $f(\delta)=0.$
Now choose $x\in [\delta, 2\delta).$ Since $|x-\delta|<\delta,$ once again we have $|f'(x)|\leq c|f(x)|<\varepsilon$ so by the same argument above $f(x)=0$ for $x\in [\delta, 2\delta].$ Continuing like this for $n$ steps, where $n =\lceil \frac{1}{\delta}\rceil$ we can show that $f(x)=0$ for $x \in [(i-1)\delta, i\delta]$ for $i=1,\ldots, n.$ and hence $f(x)=0$ for every $x \in [0,1].$
Is there a problem with this argument? Thanks in advance.
Answer: Yes, there is a problem with the argument. You've chosen your $\delta$ given a value of $\varepsilon > 0$. This value of $\delta$ will (in general) change depending on the value of $\varepsilon$. So, while you can always find some $\delta_\varepsilon$ such that
$$x \in (0, \delta_\varepsilon) \implies |f'(x)| \le c|f(x)| < \varepsilon,$$
the interval $(0, \delta_\varepsilon)$ will shrivel up as you make $\varepsilon$ smaller. There may be no one point $x > 0$ such that $|f'(x)| = 0$, using this argument.
Comment: Oh right right, I see what you mean by the interval for which $|f'(x)|=0$ holds, shrinking. Thanks for pointing this out. So the mistake is in the first step itself right?
Comment: There is a similar problem later on. You use the same $\delta$ again for the next paragraph. You say, "by the same argument...", but this may not give you the same $\delta$. So, you won't so much get a result for $[0, 2\delta)$ as you will get a result for $[0, \delta + \delta')$. Even if you kept iterating this and producing more $\delta$s, how do you know the sum of the $\delta$s didn't converge, and thus fail to prove the result for all reals?


Custom fonts in Objective-C Application

Question: This question isn't really asking what you might think on the surface. I already know how to use custom fonts in objective-c applications. The question is more in regards to the specifics about using custom fonts, mainly — If I use a custom font that suppose someone else may not have on their machine will it still render it properly? I haven't seen anything in pertaining to whether or not that becomes a factor if someone doesn't have the same typeface.
Also, is there any connection with my question and the object within interface builder? thanks.
Comment: @VineeshTP Please look at the tags. It is clearly for an OS X program.
Comment: No, the font will not automagically work if your users don't have it. You need to bundle it in your application (**and ensure that you have distribution rights**) and use a method similar to [this one](http://devmacosx.blogspot.ca/2012/03/nsfont-from-file.html) to load the font into your program.
Comment: do you want to use custom font in ios app /?
Comment: Let me turn that into an answer if it solved your problem.
Answer: Custom fonts only work if your users have them too. Otherwise, the font needs to be bundled with your program and loaded in a way similar to this one. Always make sure that you are allowed to distribute the font with your program.
<code>-(NSFont*)fontWithName:(NSString*)name height:(CGFloat)height
{
    NSURL* fontURL = [NSBundle.mainBundle URLForResource:name withExtension:@"ttf"];
    if (fontURL == nil)
    {
        return nil;
    }

    CGDataProviderRef dataProvider = CGDataProviderCreateWithURL((CFURLRef)fontURL);
    if (dataProvider == NULL)
    {
        return nil;
    }

    CTFontRef coreTextFont = NULL;
    CGFontRef font = CGFontCreateWithDataProvider(dataProvider);
    if (font != NULL)
    {
        coreTextFont = CTFontCreateWithGraphicsFont(font, height, NULL, NULL);
    }

    CGDataProviderRelease(dataProvider);
    CGFontRelease(font);
    return CFBridgingRelease(coreTextFont);
}
</code>

Custom fonts in Objective-C Application


How is Poisson distribution different to normal distribution?

Question: I have generated a vector which has a Poisson distribution, as follows:
x = rpois(1000,10)

If I make a histogram using hist(x), the distribution looks like a the familiar bell-shaped normal distribution. However, a the Kolmogorov-Smirnoff test using ks.test(x, 'pnorm',10,3) says the distribution is significantly different to a normal distribution, due to very small p value.
So my question is: how does the Poisson distribution differ from a normal distribution, when the histogram looks so similar to a normal distribution?
Comment: Also (as an add-in to David's answer): read this (http://stats.stackexchange.com/a/2498/603) and set your sample size to 100 and see the difference it makes.
Answer: Here's much easier way to understand it:
You can look at Binomial distribution as the "mother" of most distributions. The normal distribution is just an approximation of Binomial distribution when n becomes large enough. In fact, Abraham de Moivre essentially discovered normal distribution while trying to approximate Binomial distribution because it quickly goes out of hand to compute Binomial distribution as n grows especially when you don't have computers (reference).
Poisson distribution is also just another approximation of Binomial distribution but it holds much better than normal distribution when n is large and p is small, or more precisely when average is approximately same as variance (remember that for Binomial distribution, average = np and var = np(1-p)) (reference). Why is this particular situation so important? Apparently it surfaces a lot in real world and that's why we have this "special" approximation. Below example illustrates scenarios where Poisson approximation works really great.
Example
We have a datacenter of 100,000 computers. Probability of any given computer failing today is 0.001. So on average np=100 computers fail in data center. What is the probability that only 50 computers will fail today?
Binomial: 1.208E-8
Poisson: 1.223E-8
Normal: 1.469E-7

In fact, the approximation quality for normal distribution goes down the drain as we go in the tail of the distribution but Poisson continues to holds very nicely. In above example, let's consider what is the probability that only 5 computers will fail today?
Binomial: 2.96E-36
Poisson: 3.1E-36
Normal: 9.6E-22

Hopefully, this gives you better intuitive understanding of these 3 distributions.
Comment: Binomial IS the true probability
Comment: Example would be better if you gave the true probability of X computers failing, along with the distribution values.
Comment: @jusaca I don't get it. If Binomial is the true probability. What is Poisson or Normal distribution for? Why dont we just use Binomial distribution to find all our probabilities?
Comment: I dont get it. It seems like Binomial distribution is the most accurate here. Then why are we even using Poisson or Normal distribution?
Comment: His point is that the binomial approximates both. He demonstrates that the Poisson approximation is better in some scenarios.
Answer:
A Poisson distribution is discrete while a normal distribution is continuous, and a Poisson random variable is always >= 0. Thus, a Kolgomorov-Smirnov test will often be able to tell the difference.
When the mean of a Poisson distribution is large, it becomes similar to a normal distribution. However, rpois(1000, 10) doesn't even look that similar to a normal distribution (it stops short at 0 and the right tail is too long).
Why are you comparing it to ks.test(..., 'pnorm', 10, 3) rather than ks.test(..., 'pnorm', 10, sqrt(10))? The difference between 3 and $\sqrt{10}$ is small but will itself make a difference when comparing distributions. Even if the distribution truly were normal you would end up with an anti-conservative p-value distribution:
set.seed(1)

hist(replicate(10000, ks.test(rnorm(1000, 10, sqrt(10)), 'pnorm', 10, 3)$p.value))

Comment: Often people will see something vaguely symmetric and assume it looks "normal." I suspect that what @Ross saw.
Comment: Note that the KS test generally assumes continuous distributions, so relying on the reported p-value in this case may (also) be somewhat suspect.
Comment: True: running `hist(replicate(1000, ks.test(rpois(1000, 10), rpois(1000, 10))$p.value))` demonstrates that a test comparing two identical Poisson distributions would be too conservative.
Comment: @Fraijo: indeed. We have a more general question on this theme: [If my histogram shows a bell-shaped curve, can I say my data is normally distributed?](http://stats.stackexchange.com/questions/129417/if-my-histogram-shows-a-bell-shaped-curve-can-i-say-my-data-is-normally-distrib)
Answer: I think it is worth mentioning that a Poisson($\lambda$) pmf is the limiting pmf of a Binomial($n$,$p_n$) with $p_n = \lambda / n$.
One rather lengthy development can be found on this blog.
But, we can prove this economically here as well. If $X_n \sim \mathrm{Binomial}(n,\lambda/n)$ then for fixed $k$
$$
\begin{align}
\mathbb P(X_n = k) &= \frac{n!}{k!(n-k)!} \left(\frac{\lambda}{n}\right)^k \left(1-\frac{\lambda}{n}\right)^{n-k} \\ &= \underbrace{\frac{n! n^{-k}}{(n-k)!}}_{\to 1} \frac{\lambda^k}{k!}\underbrace{(1-\lambda/n)^n}_{\to e^{-\lambda}} \cdot \underbrace{(1-\lambda/n)^{-k}}_{\to 1} \>.
\end{align}
$$
The first and last terms are easily seen to converge to 1 as $n \to \infty$ (recalling that $k$ is fixed). So,
$$
\mathbb P(X_n = k) \to \frac{e^{-\lambda} \lambda^k}{k!} \,,
$$
as $n \to \infty$ since $(1-\lambda/n)^n \to e^{-\lambda}$.
In addition one has the normal approximation to the Binomial, i.e., Binomial($n$,$p$) $\approxeq^d \mathcal N(np, np(1-p))$. The approximation improves as $n \rightarrow \infty$ and $p$ stays away from 0 and 1. Obviously for the Poisson regime this is not the case (since there $p_n = \lambda / n \rightarrow 0$) but the larger $\lambda$ is the larger $n$ can be and still have a reasonable normal approximation.
Comment: I like the direction of this, though there may be ways to relate it a little more closely to the question at hand by making the connections between the three distributions clearer. For example (a) A binomial random variable (sequence) acts like a Poisson as long as $n p_n \approx \lambda$, (b) A binomial (sequence) acts like a normal as long as $p$ is approximately a fixed constant and (c) a Poisson (sequence) acts like a normal for large $\lambda$ essentially due to its infinite divisibility.
Comment: Nice comments @cardinal. About the last sentence, for fixed, large $n$ the larger $\lambda$ the larger $p_n$ (e.g. closer to $1/2$). Therefore the better the Normal approximation to the Binomial and in turn the Poisson.
Comment: (+1) Welcome to the site. I've made a few edits; please check that I have not introduced any errors in the process. I was not quite sure of what to make of the very last phrase in the last sentence. Some additional clarification there might be helpful.
Comment: Thanks. I see what you were trying to say now. I generally agree, with the caveat that some care needs to be taken with the relationship between the parameters, which are considered fixed and which vary with the others. :)
Comment: Hi Murat and welcome to the site! it's good to see you here and I hope you stick around. +1 for explaining _why_ the histogram of a poisson looks a lot like that of a normal when $\lambda$ is large.
Answer: It's a great question because Poisson distribution is not only different, but it is also so similar to Normal distribution. Here's how it is similar:

the sum of two normals is normal, so is the sum of two Poissons
Brownian motion (Gaussian) and Poisson process are both Levy processes
Both Poisson and Gaussian distributions can be approximations of the Binomial distribution with large N
for large $\lambda$ Gaussian distribution looks very much like Poisson, which you already noticed
Comment: I think you may mean that the sum of two Poisson generated variables is itself a Poisson distribution. May also want to clarify that the Poisson distribution approximates the Binomial distribution well when N is large and p is (very small), the Normal distribution approximates the Binomial distribution well when N is large and p is closer to .5, and neither does a good job when p is very close to 1.


View using Path

Question: I'm having an issue combining the use of taxonomy terms, URL alias patterns and views.
Here's my setup:
1) Taxonomy: A basic taxonomy, lets call it "Blog Tags". In here I have a term like Mountains. You can see the URL alias is shown here as "blog/tagged/mountains".

2) URL alias pattern: The pattern is "/blog/tagged/[term:name]".

3) View: This is a page view, that uses the path /newsroom/tagged/%. I have a contextual filter "Content: Has taxonomy term ID", that uses a specified "Blog Tags" taxonomy type.
The following does not work:

The following does work, but I cannot edit/translate my terms after applying:

Any idea what I can do differently to get this working?
Comment: Use TVI module, it should solve this.
Comment: @Kevin I was able to get the desired result using this module. Many thanks.
Answer: Poster opted to use the TVI module, which greatly simplifies trying to get Views to display over the default term page(s).

View using Path


Convergence to Riemann-Stieltjes integral of sequence of Riemann-Stieltjes-like sums with changing integrand and integrator

Question: I am considering the limiting behavior of a sequence of Riemann-Stieltjes (RS) (or at least RS-like) sums in the sense of their convergence to a Riemann-Stieltjes integral. The general term has the form
\begin{equation}
  \sum_{n=0}^N \, f_N(t_n^{(N)}) \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})] \,,
\end{equation}
where $x_{-1}^{(N)} := 0$ for every value of $N$, every partition $\{ x_n^{(N)} \}_{n=-1}^N$ is of the unit real interval $[0,1]$ with $x_N^{(N)} = 1$, the argument $t_n^{(N)}$ belongs to the subinterval $[x_{n-1}^{(N)}, x_n^{(N)}]$ of $[0,1]$ (actually, in my more specific setting it is $t_n^{(N)} = x_n^{(N)}$), and the partition for $N+1$ is a refinement of that for $N$. I think everything is as usual for an RS sum except for the particularity that there is no fixed function having the role of integrator, but rather a sequence $(F_N)_N$ thereof, and similarly for the integrand, which is defined in terms of the sequence $(f_N)_N$.
As for the functions, they are all real of a single real variable. Those in the sequence $(f_N)_N$ are continuous and bounded in $[0,1]$, and the sequence converges to a continuous function f bounded in the same interval. In turn, those in $(F_N)_N$ are monotonically increasing step functions bounded in $[0,1]$ and the sequence is uniformly convergent to a function F that is a cumulative distribution function. My overall objective is to prove that the sequence of sums converges to the RS integral $\int_0^1 \, f(x) \, \mathrm{d}F(x)$.
Any hints on how to proceed will be welcome.
Answer: Start by writing
$$\tag{*}\left| \sum_{n=0}^N \, f_N(t_n^{(N)}) \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})]- \int_0^1 f \, dF \right| \\ \leqslant \left| \sum_{n=0}^N \, f_N(t_n^{(N)}) \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})]-  \sum_{n=0}^N \, f(t_n^{(N)}) \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})] \right| \\ + \left| \sum_{n=0}^N \, f(t_n^{(N)}) \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})]-  \sum_{n=0}^N \, f(t_n^{(N)}) \, [F(x_n^{(N)}) - F(x_{n-1}^{(N)})] \right| \\+ \left| \sum_{n=0}^N \, f(t_n^{(N)}) \, [F(x_n^{(N)}) - F(x_{n-1}^{(N)})]- \int_0^1 f \, dF \right|,$$
and try to estimate each term as $N \to \infty.$
Uniform convergence of both $f_N \to f$ and $F_N \to F$ would be helpful.
For the first term on the RHS of (*) , with uniform convergence, we have  for sufficiently large $N$ and all $x \in [0,1]$,
$$|f_N(x) - f(x)| < \epsilon, \,\,\, F_N(1) < F(1) + \epsilon, \,\,\, F_N(0) > F(0) - \epsilon$$
Hence,
$$ \left| \sum_{n=0}^N \, f_N(t_n^{(N)}) \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})]-  \sum_{n=0}^N \, f(t_n^{(N)}) \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})] \right|\\ \leqslant  \sum_{n=0}^N \, |f_N(t_n^{(N)})- f(t_n^{(N)}) | \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})] \\ \leqslant \epsilon \sum_{n=0}^N \,  \, [F_N(x_n^{(N)}) - F_N(x_{n-1}^{(N)})]  \\ = \epsilon[F_N(1) - F_N(0)] \\ \leqslant \epsilon[F(1) - F(0) + 2\epsilon$$
The convergence of the last term on the RHS of (*) is not always guaranteed when $f$ is R-S integrable with respect to $F$ except under strong conditions. It seems you have that part -- both because the partitions in the sequence are refinements and $f$ is continuous.
Comment: No problem.  I just showed how the first term on the RHS is small for large $N$ when we have uniform convergence.  The third term converges as I said under your hypotheses.  All you have to do is handle the second term which should be easy because $f$ is bounded and $F_N \to F$ uniformly.
Comment: Thank you very much for your answer. I guess that you first line in the RHS is a typo to be removed, though. I'll try as you suggest and see how far I can go.
Comment: @Marco:  Where is the typo?
Comment: The entire first line.
Comment: The first line is $|S(P_N,f_N,F_N) - \int_0^1 f \, dF|$ with $S(...)$ shorthand for the sum.  This is the very thing you want to show converges to $0$.
Comment: I mean the first displayed line in the RHS of the inequality.
Comment: I am writing $|S(P_N,f_N,F_N)-\int fdF| \leqslant |S(P_N,f_N,F_N) -S(P_N,f,F_N)| + | S(P_N,f,F_N) - S(P,f,F)| + |S(P_N,f,F)- \int fdF|$.
Comment: ... and the first term on the RHS is easy to estimate if $f_N \to f$ uniformly.
Comment: Right. I had missed the "unindexed" $f$. Sorry about that.
Comment: @Marcos.  Nice question -- I think it will work out.
Comment: Thanks so much. I also think your approach will work out. I'll be back as soon as I have worked out the details.
Comment: You're welcome.  I could do it all - but it is much better for you to complete it.
Comment: Rightly so. I appreciate.


How to unzip files bigger than 4GB?

Question: I'm using RHEL 5.6 and unzip-5.52-3.el5. I'm trying to unzip a big file, but I get the error:
unzip -o test.zip -d unzip/
error:  Zip file too big (greater than 4294959102 bytes)
Archive:  test.zip
warning [test.zip]:  4294967296 extra bytes at beginning or within zipfile
Is there another program that can work with large zip files or do I have to wait until unzip 6 comes to RHEL? (might be years!)
Thanks
Answer: If you've got Java on the box, you can use
jar xf test.zip

Comment: saved me from having to bug the SAs to install unzip6. Thanks!
Comment: life saved. [ beer token ]
Comment: I had a 16+GB zip file downloaded from my wife's phone using AirDroid, and this trick saved me a lot of trouble!
Answer: You can either use javas jar, or (in my opinion) even better: 7-zip. Most distros allow for it to be installed from repos, so you can use for example (on ubuntu):
sudo apt-get install p7zip-full
7z x huge.zip

Note how the command is not p7z or p7zip, but only 7z. Also the x option has no preceding -. Best of luck!
Comment: @GeraldSchneider This answer helped me regardless of when it was answered.
Comment: This method worked for me with a 16GB `zip` — I trust the `jar` method also works but did not try that. Thanks.
Comment: This answer has already been given 6 years ago.
Answer: I've found good success with 7-zip, it appears they have a fedora core build as well that might work for you, the downloads can be found at http://www.7-zip.org/download.html.  Failing the fedora one, you can download the source and/or binary and try that.
Comment: Check if 7z isn't an alias for 7zr. Try running 7za.
Comment: The package p7zip-full ships a command 7z, which accepts the x (extract) option. So in my case, using '7z x huge.zip' worked without issue.
Comment: I played around with 7-zip (7z), but when extracting files from my zip it kept saying unrecognised format.
Comment: 7z fails for me, says the file is corrupt. The most upvoted jar answer did work though
Answer: I finally ended up rolling my own rpm's for unzip 6, they can be found here: http://www.noodles.net.nz/2011/02/15/unzip-6-for-rhel-5-6/
Comment: you can select your own answer as the one that solved the problem
Comment: I compiled the current unzip-6.0 from scratch - it didn't fix the problem.
Comment: rpm at http://www.noodles.net.nz/2011/02/15/unzip-6-for-rhel-5-6/ worked for me
Answer: I tried all the steps mentioned above to unzip the file, but failed miserably.
My last resort was to copy my zip file (11.1GB) into a hard drive and unzip it using 7 zip on Windows 8 OS.
Worked like a charm :D
Comment: That is not an answer to this question.
Comment: `jar xf file.zip` or `7z x file.zip` and others are fine
Comment: I tried in more ways than one to get it running on Linux... None of the solutions worked... So I'm giving a better alternative... Much more easier and hassle-free alternative..
Comment: Beyond 4 GB, linux is unable to unzip files... Windows I'm afraid has a much better mechanism to unzip huge zip files... So just giving out that info...
Comment: jar xf file.zip worked for me, but 7z x file.zip failed (Ubuntu, 4.4GB file)
Comment: No it's not, silly.   Read above.  Just don't use `/bin/unzip`

How to unzip files bigger than 4GB?


What is the preimage of a function

Question: Is it the domain of the inverse or the defined domain of the inverse (in the case the function is not invertible)? The concept is very confusing for some reason I cannot grasp.
Answer: I would not use the terminology preimage of a function at all. If $f:X\to Y$ is a function, and $A\subseteq Y$, the preimage of $A$ under $f$ is $$f^{-1}[A]=\big\{x\in X:f(x)\in A\big\}\;.$$ That is, in my terminology subsets of the codomain of $f$ have preimages under $f$, and these preimages are subsets of the domain of $f$.
You can, if you wish, define a function $$f^{\leftarrow}:\wp(Y)\to\wp(X):A\mapsto f^{-1}[A]$$ that takes each subset of $Y$ to its preimage in $X$ under the function $f$, but I would never call this function the preimage of $f$..
Comment: Is your point that the phrase '_preimage of a function_' directly ignores and implies the opposite of the fact that the preimage requires a **set** for the argument of a function?
Comment: I don't quite understand. In layman's terms, how would you define it?
Comment: @Limitless: Not really. My point is that it isn't the function that has a preimage; the function is the mechanism by which preimages of subsets of the codomain are constructed.
Comment: @BrianM.Scott I misphrased what I was trying to say, sorry. In my comment, I meant $f^{-1}$ by 'function'. That is, $A$ is the argument in $f^{-1}[A]$.
Comment: @xeonphi: As I said, I wouldn't: given a function $f:X\to Y$, I don't consider the expression *the preimage of* $f$ meaningful. Subsets of $Y$ have preimages under $f$.
Comment: @Limitless: You can always view $f^{-1}$ as a function from $\wp(Y)$ to $\wp(X)$; from that point of view it's the $f^{\leftarrow}$ of my answer. For each $A\subseteq Y$ it gives you the preimage of $A$ under $f$. None of that is problematic. What I'm saying is that at least as I (was taught to) use the words, 'the preimage of $f$' is meaningless: $f$ doesn't have a preimage. Subsets of $Y$ have preimages, and specifically preimages under $f$.
Comment: @BrianM.Scott Yes, I understand perfectly now. You've made a very good point.
Answer: Let $f:X\to Y$ be a function. Let $A\subset X$ and $B\subset Y$. Then $f(A)=\{f(x)\in Y:x\in A\}$ is called the image of $A$ under $f$ and $f^{-1}(B)=\{x\in X:f(x)\in B\}$ is called the preimage of $B$ under $f$.
Answer: If $f\colon A\to B$ is a function (any function) then the preimage is actually a function $\tilde f\colon P(B)\to P(A)$ (where $P$ indicates the power set) defined as follows: $$\tilde f(X)=\{a\in A\mid f(a)\in X\}$$
Note that the domain of $f$ is $A$ so $A$ itself is $\tilde f(B)$, however it is possible that $\tilde f$ is neither surjective nor injective in cases where $f$ fails to satisfy some of these properties.

What is the preimage of a function


Drush cache-rebuild breaking menus

Question: We have had an issue with an expanding menu on a drupal 8 website that stops working when the command
drush cache-rebuild

is used.
MORE INFO ON ERROR:
When triggered, the error causes menus set to expand some sub-menu portion when active to stop expanding. That is to say the menu stops expanding at all, just stays in the inactive state.
The menus where this occurred were generated with the core menu module.
Logging into the site and using the clear all found in admin->config->performance->"clear all caches" fixes the issue.
Can anyone suggest an alternative drush/command line command we can use or how we can fix this problem?
drush clear-cache

does not seem to fix the issue.
I also tried executing as apache:
sudo -u www-data drush cache-rebuild

this also broke my menus.
What exactly is the difference between the UI cache clear and the drush one?
MORE INFO
Ok after some digging - and please correct me if I am wrong here - it seems that when Drush rebuilds all caches it invokes:
drupal_rebuild(ClassLoader $class_loader, Request $request)

which is found in utility.inc, see drush github repo, while the admin command in Drupal calls:
drupal_flush_all_caches()

found in common.inc, see drupal docs.
I have always been under the impression drush either called the same cache function as the internal performance button or at least they had the same behaviour, but they seem not to - at least in regards to my issue with the menu.
Can anyone suggest a way to have drush - or some other tool - invoke drupal_flush_all_caches()?
A further question, is the behaviour I am observing intended or should drush cache-rebuild work the same as drupal_flush_all_caches()?
MORE INFO AGAIN
Further experiments lead me to believe that it is specifically the clearing of the views cache that is causing some expanding menus to break.
drush cache-clear views

Will also trigger the behaviour. Again, clearing with the drupal_flush_all_caches() via the performance admin page fixes the issue.
Comment: It would help to know the drush version.
Comment: What's not working?
Comment: Drush 8.1.0. Expanding manus are breaking. Simply put, they no longer expand.
Answer: EDIT: I take it back. The problem has started again in drush 8.1.8 when Drush cr is used in a script - we have it in a back up script to reduce the size of the DB before pilling a copy of it - the application of the is-Active tag is getting broken on menu elements and any styling - say turning on or off visibility to expand the menu - seems to to totally break.
Manually clearing the cache through the UI fixes the issue but is not ideal
Drush 8.1.8 seems to have fixed the problem. I have looked through the change log though and cannot see what got changed in regards to the cache-rebuild that would fix the problem but it seems to have gone away so...
Comment: https://github.com/drush-ops/drush/pull/2393 did fix this. And https://github.com/drush-ops/drush/issues/2511 is another related issue that was fixed too
Comment: ah exactly what I was looking for. That explains a lot. I feel better about the issue be actually resolved now.
Answer: The following snippet works for me on Drupal 8.7
drush ev '\Drupal::service("router.builder")->rebuild();'

Drush cache-rebuild breaking menus


What is the compound interest if the money put in the bank, with the required compound interest in $a$ years increases by $b%$

Question: The task is to write a program which for given $a$ and $b$ returns what is the compound interest if the money put in the bank with the required compound interest in $a$ years increases by $b\%$.
I do not see how can I find the compound interest if I do not know the starting amount of money?
Could it be $(1+\frac{b}{100})^{a}$?
Answer: You are correct in your presumption. Compound Interest depends on the principal and thus you will need it to find the compound interest as the formula dictates $$\text{Amount} = P\left ( 1 + \frac {\text{rate}}{100} \right )^a$$ $$\implies \text{C.I} = P\left\{\left(1 + \frac {\text{rate}}{100}\right)^a - 1\right\}$$
Answer: Increasing by $b\%$ means:
$$b=\frac{\text{Final Amount – Initial amount}}{\text{Initial amount}} \cdot 100\% \tag{1}$$
Now let final amount be $M_f$ and intial amount be $M_i$. substituiting this in $(1)$, we rewrite as
$$b=\frac{M_f-M_i}{M_i} \cdot 100\% $$
$$\implies \frac{M_i(100+b)}{100}= M_f \tag{2}$$
Now for a compound interest $r\%$ per year, for $a$ years, we get $M_f$ as:
$$M_f=M_i\left(1+\frac{r}{100}\right)^a$$
Substituting this in $(2)$, we get
$$\left(1+\frac{b}{100}\right)=\left(1+\frac{r}{100}\right)^a$$
$$\therefore r=100\left(\left(1+\frac{b}{100}\right)^{1/a}-1\right)$$
However you are correct in the fact you can't find the value of $M_f$ if you do not know $M_i$. You get $r$ only.


How to generate a unique ID and then make that the URL?

Question: This is the etherPad workflow:
load http://ietherpad.com
click 'new pad' which takes you here: http://ietherpad.com/ep/pad/newpad

That then redirects to something like this:
http://ietherpad.com/1vcs1YUf1Z

How can I do this in rails?

Have my rails controller new method generate a UID, and then redirect
Have my rails routes somehow use that uID after the first / to find the right record and route to the right Pad Show method in the controller?

Thanks
Comment: I really just need help with the routes. I can figure out the UID part.
Answer: The absolute easiest way is to do this:
In the model, have a callback
class Thing < AR::Base
   # assuming you have a slug field
   before_create :generate_slug

   private
   def generate_slug
     self.slug = some_uid_algorithm
   end

end

Then in the controller, use the edit action. Use the dynamic finder find_by_slug and take in the id parameter. This returns the record if found, and returns nil if not found. If it's not found, call create to get a new one, which invokes your slug callback.
def edit
  @thing = Thing.find_by_slug(params[:id]) || Thing.create!
end

Direct your routes for this to the edit action of your controller. You may want a more robust way of determining what a valid slug is before you start creating records, but this is essentially how a "wiki" might work.
This might end up creating a bunch of junk records, so you'll want a way to sweep those. Some sort of state like "pending" or "unsaved" would take care of that - when the user updates the record, change the state from "unsaved" to "saved" and then sweep any "unsaved" docs that are 30 days old or something.
How does that sound?


Is this a correct way to prove $\partial A = \overline{A} \cap \overline{A^c}$?

Question: My book has two adjacent exercises, in which $\partial A$ is the set of boundary points of $A$ (a subset of some metric space $X$) and $\overline{A}$ is the closure of $A$. The first asks me to prove that $\overline{A} = A \cup \partial A$, which was simple and is discussed in this question.
The second exercise asks me to prove that $\partial A = \overline{A} \cap \overline{A^c}$. I proved this one way that matches the book's solution, but I also have another proof that uses the first exercise, the fact that $\partial A = \partial A^c$, and DeMorgan's Laws.
\begin{align*}
\overline{A} \cap \overline{A^c}
&= \left(A \cup \partial A\right) \cap \left(A^c \cup \partial A^c\right) \\
&= \left(A \cup \partial A\right) \cap \left(A^c \cup \partial A\right) \\
&= \partial A \cup \left(A \cap A^c\right) \\
&= \partial A \cup \varnothing \\
&= \partial A
\end{align*}
Is this a correct proof?
Comment: Sounds perfectly correct
Comment: @HennoBrandsma I used the fact that $A \cup (B \cap C) = (A \cup B) \cap (A \cup C)$ (see the [Wikipedia article in union and intersection](https://en.wikipedia.org/wiki/Union_%28set_theory%29#Union_and_intersection)).
Comment: What law is used to go from the second to the third line?
Comment: See also http://math.stackexchange.com/q/668831/4280 for basically the same idea.
Answer: For the second,
$\bar{{A}}$ $\cap$ $A^\mathrm{o}$ = ($A^\mathrm{o}\cup\partial{A}$) $\cap$($(A^c)^\mathrm{o}\cup\partial{A^c}$) = $\bar{{A}} \cap ((A)^\mathrm{o})^c$ = $\partial A$
Answer: I don't quite see how you go from $(A \cup \partial A) \cap (A^c \cup \partial A)$ to the line below it in one step.
I would expand to 4 terms: $(A \cap A^c) \cup (\partial A \cap A^c) \cup (A \cap \partial A) \cup (\partial A \cap \partial A)$, where the first term equals $\emptyset$, the final one $\partial A$ and the middle terms $(\partial A \cap A) \cup (\partial A \cap A^c)$ can be regrouped as $\partial A \cap (A \cup A^c) = \partial A \cap X = \partial A$ as well, so the total group becomes indeed $\partial A$.
Of course the definition of the boundary already gives the formula almost directly: $x \in \partial A$ iff every open neighbourhood of $x$ intersects $A$ (i.e. $x \in \overline{A})$ and every open neighbourhood of $x$ intersects $X \setminus A = A^c$ (i.e. $x \in \overline{A^c}$. So $\partial A = \overline{A} \cap \overline{A^c}$, almost by definitions of boundary and closure.


How do i show/hide page content depending on the users role?

Question: I am creating a site that has several roles.  When some one who is logged in goes to a certain page I want the page to determine what content needs to be displayed depending on what roll they are.
Example.  If the user is attached to the "teacher" role then they will see "Hello teacher thank you for visiting our site" then it might have two buttons that leads them to certain pages.  If they are attached to the "student" role they will see "Hello student thank you for visiting our site" then the two buttons would be different and lead them some where else.
Is there a module that could help with this?
Answer: There are two good ways you could go about this.

Install Panels and
enable Page manager. Panels has a huge collection of what are called
'visibility rules' for individual panes. These allow you extremely
fine grained control over who sees what portion of the page. Panels
offers a lot of power, but brings a lot of complexity along with it.
Put your messages each in their own block. Blocks come with the ability to show and hide for certain roles.
This method is much simpler, but if you have a lot more content than just
the welcome message you want to show and hide panels
will end up being a more customizable solution.


NullPointerException with Android SQLiteAssetHelper

Question: In the development of Android applications I use Android SQLiteAssetHelper.
The problem is that occasionally when accessing the database I get an error to the object  NullPointerException in object DBQuery
public class DBQuery extends MyDatabase {
  private static MyDatabase dataBaseHelper;

  public DBQuery(Context context) {
        super(context);
        dataBaseHelper = new MyDatabase(context);
  }

  public static void closed() {
        dataBaseHelper.close();
  }

  public static int getFDay(int year) {
    Cursor cursor = database.rawQuery("SELECT offset FROM china_years WHERE year = ?",
        new String[] { Integer.toString(year) });

    cursor.moveToFirst();
    String yearS;
    try {
      yearS = cursor.getString(0);
    } catch (Exception e) {
      yearS = "0";
      e.printStackTrace();
    }
    cursor.close();

    return Integer.parseInt(yearS);
  }

  /* other queries... */
}

MyDatabase class:
public class MyDatabase extends SQLiteAssetHelper {

   private static final String DATABASE_NAME = "db.sqlite";
   private static final int DATABASE_VERSION = 2;
   public static SQLiteDatabase database;

   public MyDatabase(Context context) {
     super(context, DATABASE_NAME, null, DATABASE_VERSION);

     database = getReadableDatabase();
   }
}

UDP:
Sorry, null object is 'database' in DBQuery class.
Comment: have u open Database before execute getFDay(int year);
Comment: I open db with database = getReadableDatabase();
Answer: Add Database name Like this & check that database is create or not
 private static final String DATABASE_NAME = "Test";

data/data/YOUR_APP_PACKAGE_NAME Location
Comment: Database is created normally, but works with it is not stable, it is often the object DBQuery is null.
Answer: You have to open your data base first. Than only you can perform operation on that.
Comment: SQLiteAssetHelper.getReadableDatabase() already takes care of opening the database.