Drupal 7 db_query how to return regular array from varchar field

Question: I am attempting to combine two arrays - one is stored in the database in a varchar field. Something like this.
["0","1","2","68","69","95","96","97","98","99","100"]

I am bringing in a similar array that comes from the front end.
["0","1","2","45","66","95","97","98","99","100"]

I need merging the two and remove duplicates.
   //merge post data and stored data
      $merge = array_merge($arr1, $arr2);
      //remove duplicates
      $merge = array_unique($merge);

My problem is that when retrieving the varchar field, I am not getting a normal array but an associative. Here is my code.
$arr2 = db_query('SELECT stats FROM {my_db} WHERE uid = :uid AND nid = :nid', array(':uid' => $usid, ':nid' => $noid))->fetchAll(PDO::FETCH_ASSOC);

I need this to return a regular array, not an associative to combine the two and remove duplicates. Does anyone know how?
When I do a print_r() on $arr2 it returns the following.
Array
(
    [0] => Array
        (
            [stats] => ["0","1","2","68","69","95","96","97","98","99","100"]
        )

)

I can't seem to be able to merge it and pass it to array_unique() on.
Answer: https://www.drupal.org/node/1251174
$arr2 = db_query('SELECT stats FROM {my_db} WHERE uid = :uid AND nid = :nid', array(':uid' => $usid, ':nid' => $noid))->fetchCol();

print_r($arr2[0]);


Populate a field with the sum of two fields while content creation

Question: I have a content type named "ABC". Which has three fields

field_half(widget type list(text)),
field_full(widget type list(text)),
field_total(widget type float).

During content creation I want the field_total to be populated with the sum of two fields field_half and field_full.
E.g.
`field_total` = `field_half` + `field_full`

How can I do this.
Comment: You can make use of `AHAH` API or just do it with some jQuery tricks. http://drupal.org/node/348475
Answer: Sounds liks a job for Computed Field

Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it.

You should just be able to set the field value literally as in your example (i.e. field = fieldA + fieldB)
Comment: while content creation ,does the computed field is not displayed
Comment: I see - let me expand my answer :)
Comment: I've added an answer to your [other question](http://drupal.stackexchange.com/questions/49158/why-computed-field-is-not-getting-displayed-while-creating-content/49159#49159).


Modular congruence, divisibility

Question: Show that, if $7$ $\nmid$ $n$, $7 \nmid n-1$ and $7 \nmid n^{3}+1$ then $7 \mid n^{2}+n+1$.
I tried for modular congruence, but i could not.
Answer: Using Fermat's little theorem, $7$
divides $$n^7-n=n(n-1)(n^2+n+1)(n^3+1)$$ for any integer $n$

Modular congruence, divisibility


Is there exactly one Mobius transformation f such that f(4) = 3 and f(3) = 4?

Question: Is there exactly one Mobius transformation $f$ such that $f(4) = 3$ and $f(3) = 4$?
Comment: If $f(z) = \frac{az+b}{cz+d},$ what can we say about the constants $a,b,c,d$ once we have $f(3) = 4$ and $f(4) = 3 \;?$
Answer: Möbius transformations are triply transitive: there is a unique transformation taking a, b, c to A, B, C.  In general you should expect anything other than three points to three points to have infinitely-many possibilities.  In particular, you could have a transformation taking (3, 4, 0) to (4, 3, 1), or to (4, 3, 2), or to (4, 3, 3), ...
As Will Jagy points out in his comment, if $f(z) = \frac{az + b}{cz + d}$, $f(3) = 4$, and $f(4) = 3$, this gives you a system of equations:
$$
\frac{3a + b}{3c + d} = 4 \\
\frac{4a + b}{4c + d} = 3
$$
which becomes
$$
3a + b = 12c + 4d \\
4a + b = 12c + 3d
$$
or, as a homogeneous system,
$$
3a + b - 12c - 4d = 0 \\
4a + b - 12c - 3d = 0
$$
This system is solved by $a = -d$ and $b = 12c + 7d$; note $c$ and $d$ are free variables, so any choice of $c$ and $d$ will give you one of the infinitely-many possibilities.  (You also need to $ad - bc \neq 0$, but this is a non-linear condition, so it's probably easiest to plug in the above for $a$ and $b$ to get $-d^2 - 12c^2 - 7c \neq 0$ and then consider all the $(d, c)$ that don't satisfy this condition.  Intuitively "most" choices of $d$ and $c$ won't satisfy that quadratic equation.  More rigorously, this is some hypersurface in $\mathbb{C}^2$ and so it has zero Lebesgue measure.)


Numerical approximation of function of high dimensional vector

Question: I have a function which has as an input a vector of $\mathbb{R}^{18}$. The output of this function is a vector of $\mathbb{R}^{2}$. How can I numerically approximate the differentiation of the function? I know how to do it if the function just delivers a single value, but not for two.
Answer: In this case you have got a function $f$ s.t.
$$
f \, : \, \mathbb{R}^{18} \longrightarrow \, \mathbb{R}^2
$$
When you derivate $f$, you obtain the Jacobian that for $f$ it is a matrix $2 \times 18$ where the general entry is:
$$
\mathbf{J}_{i,j} = \frac{\partial f_i}{\partial x_j}
$$
For a numerical approximation of the Jacobian, i.e the approximation of   first order derivates, we can use the finite difference method.
At this link at slide 3.7 there is a matlab code which use the function jacobian.
At this link, from [1], at pag 157 see the jacobian function in python.

[1] Kiusalaas, Jaan. Numerical methods in engineering with Python 3. Cambridge university press, 2013.


Usage of class in CSS

Question: can someone please explain the difference in the following:
div.main
{
font-family:Arial, sans-serif;
}

.main div
{
font-family:Arial, sans-serif;
}

I'm not sure when to use each one.
Comment: The first matches all `div`s with class `main`, the second matches all `div`s _contained in_ any element with class `main`.
Answer: I'll give a sample HTML code for each css style:
First example - Targets all div that has a class of main

div.main {
  color:red;
}

SAMPLE

Second example - Targets all div that is a child of an element that has the class of main

.main div {
  color: red;
}

NOT AFFECTED

AFFECTED

AFFECTED

AFFECTED

AFFECTED

Answer: I think you should learn all this by implemeting it or by reading css selectors and css specificity.
For more info css selector
div.main { font-family:Arial, sans-serif;}

Above code will target all div which having main as class.
.main div { font-family:Arial, sans-serif; }

Above code will target all div which is child of main class.
Answer: Your first rule says:
Find all div elements having main class
Your second rule says:
Find all divs that are placed inside all elements having main class.
Please read about basic concepts of CSS

Usage of class in CSS


Upper and lower quantiles

Question: I have a question regarding upper and lower quantiles.
In my lecture notes these are defined as:
$Q_p[X] = \inf\{x \mid P(X \leq x) \geq p\}$
is the lower p-quantile
$Q^p[X] = \inf\{x \mid P(X \leq x) > p\}$
is the upper p-quantile
For which distributions does $Q_p[X] = Q^p[X]$?
I can see that for continuous distributions with strictly increasing cdf the equality holds. But is it true for general continous r.v. $X$? If not, are there well known continous distributions where $Q_p[X] \neq Q^p[X]$
Answer: Here is a continuous but not strictly increasing CDF on the unit interval, defined in the obvious way:

We have
$$ Q_\frac{1}{2}[X] = \frac{1}{3} \quad\text{and}\quad Q^\frac{1}{2}[X] = \frac{2}{3}. $$
Whether this toy example is "well known" enough is of course debatable, but it can easily arise as the empirical CDF of a sample from a (hypothesized) continuous distribution.
Comment: Thanks for your answer Stephan Kolassa. With "well known" I meant a distribution that has a name like normal/exponential/lognormal/(...)-distribution.

Upper and lower quantiles


ASP.NET MVC Web Api Get Not Mapping QueryString To Strongly Typed Parameter

Question: The parameter request is always null using Web API.  Am I missing something with using a strongly typed object as a parameter instead of simple types as the parameters.
Url
http://localhost:2222/api/v1/divisions?EventId=30

Controller Action
public virtual ApiDivisionsResponse Get(ApiDivisionsRequest request)
        {
            return _apiDivisionsService.GetDivisions(request);
        }

Object
public class ApiDivisionsRequest : ApiAuthorizedRequest
    {
        public ApiDivisionsRequest()
        {
            Page = 1;
            PageSize = 10;
        }

        public int EventId { get; set; }
        public int PageSize { get; set; }
        public int Page { get; set; }
        public string[] Includes { get; set; }
    }

Answer: I very strongly invite you to read the following article to better understand how parameter binding works in the Web API. After reading it you will understand that by default the Web API binds query string parameters to primitive types and request body content to complex types.
So if you need to bind query string parameters to complex types you will need to override this default behavior by decorating your parameter with the [FromUri] parameter:
public virtual ApiDivisionsResponse  Get([FromUri] ApiDivisionsRequest request)
{
    ...
}

And yeah, I agree with you - that's a hell of a mess - model binding was so easy in plain ASP.NET MVC and they created a nightmare in the Web API. But once you know how it works you will avoid the gotchas.
Comment: Created a nightmare isn't the half of it.  Seems that just about everything the ASP.Net crew touches becomes the poster child for "The Stupid, It Burns!".  AjaxControlToolkit, and now this abortion...
Comment: @jerhewet Realize that there were driving factors at the time of creating some of these ridiculous web forms components. Customer demand and  Microsoft was competing with offerings from the Java world. This great ecosystem that we have today might not have existed if it wasn't for the stepping stones of ASP.NET Webforms and others.


Inequality containing $x^2-2x^2e^{-ax}$

Question: Assuming there is an inequality in the form of
$x^2-2x^2e^{-ax}\leq \frac{b}{a^2}$
for $x,a,b>0$. Is it possible to find a bound for $x$?
I have difficulty obtaining the bound on $x$ because of the exponential term.
Comment: Try expanding $e^{-ax}$ as a Taylor series.
Answer: $f_a(x)=x^2(1-2e^{-ax})$ is quite obviously an unbounded function on $\mathbb{R}^+$, with a unique stationary point located at the positive root of $f_a'(x) = 2x((ax-2) e^{-ax}+1)$, which in terms of the Lambert W function is given by $$x_a=\frac{2-W(e^2)}{a}\approx \frac{31}{70a}.$$
$f_a(x_a)$ is an absolute minimum for $f_a(x)$ over $\mathbb{R}^+$ and $f_a(x)=0$ at $z_a=\frac{\log 2}{a}>x_a$. In particular $x\leq z_a$ clearly ensures $f_a(x)<0$, hence $f_a(x)\leq\frac{b}{a^2}$ for any positive $b$. In order to refine this inequality we may consider the Taylor series of $f_a(x)$ centered at $x=z_a$:
$$ f_a(x) = \frac{\log^2 2}{a}(x-z_a)+\left(2\log 2-\frac{\log^2 2}{2}\right)(x-z_a)^2 +\left(a-a\log 2+\frac{a}{6}\log^2 2\right)(x-z_a)^3+\ldots$$
and get that $f_a(x)\leq\frac{b}{a^2}$ as soon as $x\leq z_a+K\frac{b}{a}$.

Inequality containing $x^2-2x^2e^{-ax}$


What if I don't want node pages for content type?

Question: I am creating a node type that I don't want to have a separate node page for. I am going to use a page view to pull them into a list. And they will link to a URL that is stored in a field for the content type.
These are simple content types and there is no need for them to have a node page. I know I can avoid having a page for them just by having no way to get there, but is there anything else to think about.
Maybe they should be something else besides a content type? Or is there a better way to not have node pages for a content type?
Edit:
I'm not really trying to prevent people from viewing these nodes. If they want to get to the node with the URL then that's fine. The nodes are just very simple(title, short blurb, link) and the node page would be pretty useless. I am just wondering if I shouldn't use some other Drupal construct for something like this.
Answer: You are looking for Internal Nodes

Some content/nodes should never be viewed directly; only visible be
  through something else such as Views or Panels. This module denies
  access to node/[nid] URLs while allowing the content to stay published
  and otherwise viewable. Try the demo!
Answer: Try to redirect when trying to see a node view
<code>/**
 * Implement hook_entity_view().
 */
function custom_entity_view($entity, $type, $view_mode, $langcode) {

  list($id, $rev, $bundle) = entity_extract_ids($type, $entity);
  switch ($bundle) {

    case 'your_content_type':
      drupal_goto('another_url'); //or access_denied
      break;

  }
}
</code>
And check with the permissions to denied edit and delete access for these kind of nodes
Answer: My choice would be using them as nodes as you are doing right now.
Reason being

Building a custom solutions would be again writing codes to interact
with database,a custom form so to keep it dynamic.
This is already been handled by drupal in very efficient way.
Also using node entities you have various options open for scaling later,you can add fields to it, enjoy no-custom code
interaction with views.
According to me,we as a developer or content editor,site admin have better hold on entities rather than any custom solution.


Can any statement of a consistent formal system be proven by changing the formal system itself while maintaining consistentcy?

Question: I'm not a mathematician but recently came across Godel's Incompleteness theorems. I have read some of the dumbed down online versions explaining the broad structure of the proof and found the argument quite fascinating. I'm sure the answer to my question is probably explained away in an undergraduate course in logic, however I have searched online for days and can't seem to find the answer - I'm probably not framing the question or search properly.
I do understand that the interpretation/meaning of a logical statement may change if the formal system changes. However I was wondering if it would be possible to gently massage the axioms/rules of the formal system to prove a particular sequence of symbols, that comprise of any logical statement?
Comment: "Unfortunately" G's Th is a "technical" result and the details can be discussed only "on top" of it. :-)
Comment: You should also search for the many, many, great many great answers on this site regarding the usage of "true" in the context of Godel's theorems, and what is the difference between "true" and "provable".
Comment: Good "general introductions" : Torkel Franzén, [Gödel's Theorem: An Incomplete Guide to Its Use and Abuse](https://books.google.it/books?id=71pK8Zz9Dd8C), Francesco Berto, [There's Something About Gödel](https://books.google.it/books?id=jmDneXkHxm4C&printsec=frontcover), Peter Smith, [An Introduction to Gödel's Theorems](https://books.google.it/books?id=sCkgAwAAQBAJ&printsec=frontcover).
Comment: If you want a formal system to be able to prove something that it can not already prove, simply add it as an axiom.
Comment: See [Gödel's Incompleteness Theorems](https://plato.stanford.edu/entries/goedel-incompleteness/) for a good general overview.
Comment: If axioms are added randomly, couldn't it make the formal system inconsistent. I should edit question to specify to maintain consistentcy
Comment: Thanks Mauro. I did read through the Stanford site but need to do a lot of background learning to get a better grasp - which I'm working on.
Comment: Thanks Asaf, I'm going through the resources on stack exchange. I think i understand the difference between true vs provable. My question is only about 'provability', I have slightly edited the grammar to make that clear.
Answer: In the comments to Rob Arthan's answer, the OP elaborated on their question:

Is there a similar Forcing type technique (that mostly keeps the interpretation of symbols same) that generates models of formal systems such that a particular statement is true in one model and the negation true in another model while maintaining internal consistency of both models?

It's this clarification which I want to address.
It's a little unclear - in particular, the phrase "that mostly keeps the interpretation of symbols same" doesn't really make sense to me - but I interpret the whole comment as asking:

Suppose $T$ is a theory and $\varphi$ is a sentence independent of $T$. Is there a method for building models of $T\cup\{\varphi\}$ and $T\cup\{\neg\varphi\}$? In particular, is there one which is similar to forcing, in that you start with a model of $T$ and "extend" it in certain ways? And finally, are there further similarities between that method and forcing?

Note that since this is a question about building models as opposed to the consistency of theories, there's a bit of extra subtlety here. (And that aspect is completely missing from the title and body question, so if this is what you're asking you should definitely edit those, and if it's not what you're asking then you need to clarify your question further.)
The answer to your question, interpreted in this way, is yes. Before I leap into the details, let me give a tl;dr: you should look into Goedel's completeness theorem (that's not a typo!) and its proof via Henkinization.

OK, now (some) details:
First of all, let's forget the "base structure" and just look at the process of building a model of a consistent theory. It turns out that this can always be done, and in fact there is a specific method for doing this, called "Henkinization"! While not equivalent to forcing, it (and more advanced ideas along the same lines) do share a family resemblance to forcing: roughly speaking, they build the desired object in "stages," meeting various "requirements" along the way, and relying on a sufficiently "generic" behavior to ensure that they work as desired. (Pinning down what all this means takes a lot of work, and forcing in particular is really really hard; but you might be interested in these takes on forcing from an intuitive perspective.)
So Henkinization lets us explicitly build a model $M$ of any consistent theory $T$. In particular, if $\varphi$ is independent of $T$ then both $T\cup\{\varphi\}$ and $T\cup\{\neg\varphi\}$ are consistent, so we have a method (Henkinization) which can build models of each. Now, what if we try to extend a given structure, rather than build one ex nihilo? That is, suppose $T$ is some theory and $\varphi$ is independent of $T$; and $M$ is a model of $T$. Can I produce models $M_0$, $M_1$ which are "bigger" than $M$, in which $\varphi$ is true and false respectively? (In particular, this process should be guaranteed to work for all $M$ - it shouldn't rely on $M$ having some specific form.)
The answer depends on exactly what you mean by "bigger" (there are lots of ways to compare mathematical structures), but under one interpretation the answer is yes for a wide class of theories. Namely, under pretty reasonable hypotheses about $T$ (it's enough for $T$ to be complete for quantifier-free sentences, which amounts to $T$ deciding exactly what kinds of "local" behavior occur in its models - e.g. the theory of groups isn't complete for quantifier-free sentences, because some groups are non-abelian (= they have the configuration "$a*b\not=b*a$") while others are abelian (= they don't have that configuration)), each of the theories $$T_0=T\cup AtDiag(M)\cup\{\varphi\}$$ and $$T_1=T\cup AtDiag(M)\cup\{\neg\varphi\}$$ is consistent; here "$AtDiag(M)$" is the atomic diagram of $M$, which describes at a very basic level how elements of $M$ relate to each other. Applying Henkinization yields models $M_0$ and $M_1$ of $T_0$ and $T_1$, respectively; and since each of $T_0$ and $T_1$ satisfy the atomic diagram of $M$, $M$ "embeds" in a precise sense into $M_0$ and $M_1$.

EDIT: One can reasonably ask:

How complicated is Henkinization?

This is a bit of a vague question, but one way to make it precise is via computability theory: we can ask, given a computable theory $T$, how easy is it to compute (= build completely explicitly) a model of $T$ by Henkinization? And, how easy is it to compute a model of $T$ via any method (that is, is Henkinization optimal)?
It turns out that Henkinization is optimal, and produces models in an "almost computable" way. Specifically, we can always find a model of $T$ which is low - that is, whose halting problem is no more complicated than the classical halting problem. More precisely, any PA degree computes a model of $T$ (and there are low PA degrees). Such a model can be built via Henkinization, and this result is optimal - there are computable theories, every model of which computes a PA degree.
And in fact, if $T$ is decidable, then the Henkinization process can be made computable! So what complexity there is comes from the technical step of completing the theory, not the model-building part of Henkinization itself. So the takeaway to my mind is that Goedel's completeness theorem is very very close to constructively true.
Comment: Although I slightly quibble with your interpretation of the completeness theorem - I would say *satisfied within*, rather than *proved within*. The point is that we don't know if $\varphi$ is *always* true, or true in the "intended model" if there is one of those; we just know that it is *sometimes* true, or better yet *possibly true given what we know* (what we know = our theory).
Comment: I'd like to know about the downvote to my answer too. However, I don't think our curiosity will ever be satisfied: giving all users the power to deprecate the contribution of others anonymously and  with no explanation seems to be enshrined as an indisputable good in the stack exchange ethos. I have tried to do my bit to counterattack in this case by upvoting your and usr21820's answers.
Comment: @NoahSchweber: I think you have hit the nail on the head. I need a little time to digest and do more reading up on your answer - will start to rephrase my question subsequently. Just to clarify regarding "that mostly keeps the interpretation of symbols same", I was trying to avoid the situation in Rob Arthan's answer where interpretation of equal symbol completely changed. Godel's Completeness theorems seem way more counter intuitive to me than the Incompleteness theorems, as they/you seem to suggest that any statement can be proven within a carefully constructed model.
Comment: @AliquidExNihilo "Godel's Completeness theorem *[there's only one]* seems way more counter intuitive to me than the Incompleteness theorems" [**Emphatically yes**](https://math.stackexchange.com/questions/2099531/how-to-verify-satisfialibility-in-a-model-confusions-with-g%C3%B6dels-completeness). I think the completeness theorem is one of the most counterintuitive results in logic, and we often forget how surprising it is. Also, see my edit re: the Henkinization process: we can even show that this construction is "simple" in a precise sense!
Comment: Finally, as a step towards understanding completeness, it may be easier to start with [compactness](). This is often proved as a corollary to completeness, but doesn't need to be; and in my mind it should come first. Compactness doesn't talk about proofs, but only about model existence: it says that if $T$ is a theory such that *every finite subset* of $T$ has a model, then $T$ itself has a model. The connection to provability is this: any proof in $T$ can only use finitely many axioms in $T$, so is really a proof from a finite subset of $T$. (cont'd)
Comment: The compactness theorem is still really surprising and hard to fully grasp (in my opinion), but it doesn't mix *semantic* notions (models) and *syntactic* notions (proofs) in the same way that completeness does. So you might find it a nice stepping stone towards really "getting" the completeness theorem.
Comment: @RobArthan: Thanks for your upvote. In my time on Math SE, I too have gotten a few downvotes on mathematically correct posts with no comments, not just here. I usually ask for my errors to be pointed out so that I can fix them, but it's mostly futile; I never got any response as far as I recall...
Comment: @NoahSchweber: Can Henkinization apply to any statement that is not independent of the theory? If yes, then in your comment regarding my interpretation of the completeness theorem, would you still state satisfied within instead of proved within?
Answer: The question in your title doesn't have much to do with the subtleties of the incompleteness theorems: you cannot prove $x = x \Rightarrow x \neq x$ in any consistent first-order logic. A change to first-order logic that allowed this (e.g., by decreeing that $x = x$ is always false) would probably not be considered as an acceptable interpretation of equality. If you allow such things, a consistent formal system can be designed to make a specific sentence provable, e.g., by giving it as an axiom but disallowing any inferences from that axiom. (The notion of a formal system is a very general one.)
Comment: The question in your comment is much clearer. In any first-order theory, $T$, if $\phi$ is a sentence such that $T$ does not prove $\phi$ and does not prove  $\lnot\phi$, then you can consistently extend $T$ with either $\phi$ or $\lnot\phi$. The extensions will both have models by the completeness theorem.  An example would be $T = PA$ and $\phi$ a sentence asserting that $T$ is consistent.  Then if you add $\phi$, $\Bbb{N}$ is still a model, but a model of $\lnot\phi$ will be a non-standard model.
Comment: @user21820: There is no reason to get riled up, if you think I'm wasting your time then don't respond. I will stop asking you and responding to your comments from now on. BTW you are the one that is making hasty and faulty statements. I NEVER said that you said that physical universe exists, read my comment carefully again, I merely gave that as an example of evidence towards something exists. You have repeatedly misstated (or misinterpreted) my comments and other users like Rob Arthan and Noah Schweber have pointed that out in their comments.
Comment: @user21820: You are the one that felt the need to justify that "I never said the physical universe exists". My comments didn't imply anything about your thoughts on physical existence - yet you felt the need to include that in your response and it was completely irrelevant like your answer and other comments. Evidence of something is not a guaranty (its not a typo, google it) of anything. My comment on self-verifying formal systems has nothing to do with PA yet you want to interject into the conversation. My question has nothing to do with incompleteness yet you keep bring that up.
Comment: Thanks for reading my question literally & carefully. I probably need to reframe the question and perhaps you can help me. Since my original post, I have done a lot more reading and didn't realize the flexibility of formal systems as pointed out by you. I came across the following talk by Joel David Hamkins: https://youtu.be/WndanxPlDFk where he mentions using Forcing to come up with different set-theoretic world's with CH and its negation. Most of the talk was beyond me and I barely understand Forcing - reading through http://www-math.mit.edu/~tchow/mathstuff/forcingdum.
Comment: I guess what I'm trying to now ask is: if there are different models of set theory where the interpretation of symbols comprising of the CH statement largely stays the same such that CH is true in one model and it's negation is true in the other; then is there a similar Forcing type technique (that mostly keeps the interpretation of symbols same) that generates models of formal systems such that a particular statement is true in one model and the negation true in another model while maintaining internal consistentcy of both models?
Comment: @AliquidExNihilo: Did you even read my post? If you look at the linked computability-based proof, it defines a very general notion of formal systems that is even more general than the kind Rob is talking about. Secondly, if your question is about CH, ask a new question. Don't keep changing the goalposts.
Comment: @user21820 I don't fully see the relevance of your answer to the question. And as for CH, the OP's comment is merely using that as an example: they frame their main question as "then is there a similar Forcing type technique (that mostly keeps the interpretation of symbols same) that generates models of formal systems such that a particular statement is true in one model and the negation true in another model while maintaining internal consistentcy of both models?", which is indeed a general statement about (un)provability. It could definitely be clearer but I disagree with your objections.
Comment: @user21820: I did read your post, you are again misunderstanding my comment to your answer - in it I actually agree with your assertion that 'there is no such thing as absolute arithmetic truth'. One doesn't need Godel for philosophical musings like absolute truths or self-consistency-proving systems, good old intuition is sufficient for that (though I'm now learning intuition can be misleading especially without well grounded framework); otherwise you are getting something from nothing. Also as pointed out by Noah Schweber my question is not about CH either.
Comment: Wait, why on earth did this answer get a downvote?
Comment: @user21820: Also, if the answer to my question  (as phrased) is in the affirmative then one could find the model that proves sentences negating or skirting Godel's theorems. However that is not thenough motivation for my question, I'm looking for general assertion as explained in Noah Schweber answer.
Comment: @AliquidExNihilo: As Noah already pointed out to you, you do not grasp the distinction between semantic truth and syntactic proof. A model does **not** prove anything whatsoever. Any sentence over the same language will either be **true** or **false** in the (first-order) model from the perspective of the meta-system, and **not** provable (it's totally meaningless to say "provable in the model"). At the same time, the completeness theorem tells you that every sentence that can neither be proven nor disproven must have two models disagreeing on (the truth value of) that very sentence.
Comment: @AliquidExNihilo: By the way, intuition is misleading, and both your implicit claims about absolute truths and self-consistency-proving systems can be considered false. Here is an absolute truth that I guarantee you cannot deny: **Something exists.** Also, there are in fact [self-verifying formal systems](https://en.wikipedia.org/wiki/Self-verifying_theories) that are consistency and yet can prove their own consistency. You're going to have to get down into the details of the incompleteness theorems if you really want to know them properly; philosophy alone is simply inadequate.
Comment: @user21820: Can you please illustrate distinction between semantic truth and syntactic proof? From the perspective of the meta-system, if statement is true and provable isn't it proved within (using model dependent rules/axioms) the model? I disagree with your claim "Something exists". I'm not sure if the physical universe(s) really exists. Just because there are humans (who may or may not really exist) in an universe (that may or may not really exist) who can think up things like logic doesn't guaranty something exists. Its just evidence towards "Something exists" but doesn't guaranty it
Comment: @user21820: Also in the wiki link of self-verifying formal systems it states "Provability of consistency can then simply be added as an axiom". That is a cop out, we can assume anything and say it's proved since it was assumed.
Comment: @AliquidExNihilo: Stop making hasty and faulty assumptions. I never said the physical universe exists; I just said "something exists". If you disagree, your disagreement exists. So you're wrong. And **you don't understand the incompleteness theorems**; you cannot add an axiom for self-consistency to any formal system that interprets arithmetic, like PA. So you're wrong, again.
Comment: @AliquidExNihilo: As for semantic truth and syntactic proof, go and read the resources I recommended, as all this is very basic logic and it's a waste of time for me to explain to you what someone else already wrote up in detail. Try Stephen Simpson's notes first, and come to [the logic chat-room](http://chat.stackexchange.com/rooms/44058/logic) if you have questions about it. If you wish to continue any discussion with me, I expect you to put in the effort to learn logic first. All the best.
Comment: @AliquidExNihilo: Ironic that you're the one judging my claims as hasty and faulty when yours are. You disagreed with my claim and gave the physical universe as "just evidence towards [the claim] but doesn't guaranty (sic) it". In my response I **never said** that you claimed that I said the physical universe exists. I just emphasized the difference, and that the reason it is guaranteed has nothing to do with the physical universe. The reason is rather that your very self (with your thoughts) constitute **absolute evidence** that something exists.
Comment: @AliquidExNihilo: Also, you have the cheek to call Dan Willard's work a cop out when it is not. If you knew even a modicum of logic, I could make it clear for you, but I doubt you would understand what I'm going to say. For the sake of future readers, here it is. There is no formal system $S$ that interprets PA and proves $Con(S)$. However, there **is in fact** a formal system $T$ that interprets only part of PA and proves $Con(T)$. You can't just "add an axiom to cop out" as I stated **already** in my answer; $S'=S+Con(S)$ does **not** prove $Con(S')$. Just go and learn logic.......
Answer: Firstly, you must realize that the incompleteness theorems have the general form:

For every formal system $S$ satisfying certain conditions, there exists a sentence that $S$ cannot prove.

They do not say something like :

There exists a sentence that every formal system satisfying certain conditions cannot prove.

So, you cannot go and change $S$ without also expecting the unprovable sentence given by the incompleteness theorem not to change!
In particular, taking any formal system $S$ satisfying the "certain conditions", it is trivial to let $S' = S + \text{Con}(S)$. Then $S'$ certainly proves $\text{Con}(S)$ even though $S$ does not, but by the same incompleteness theorem $S'$ does not prove $\text{Con}(S')$.
Since you say you do not know where to look, I recommend these resources, which you can go through in order and skip those that are too easy for you. (These are so far the best free online resources I have found.) However, there are alternative perspectives not found in any of these books, including resolving logic paradoxes and computability-based proof of the incompleteness theorems.
Note that there is no shortcut to full understanding of these theorems of logic. If you know both programming and basic first-order logic, you can jump straight to the computability-based proof to get a high-level grasp of it, before you get into the details of coding everything into arithmetic. But either way it will take time to work through the details.
Comment: @User21820: The question has nothing to do with proving self consistency. You are correct that question doesn't have much to do with Godel except that I thought about it while reading the proof. I understand you are piqued with newbies trying to skirt Godel's theorem (which I'm not). Even before I learned about Godel's theorem, I always wondered about what 'metrics' could be used to label something as 'true' (other than proving or assuming it). If something is true in the absolute sense then we are getting something from nothing. Sorry for the digression - just wanted to minimize mind reading.
Comment: OK. I'll leave the mind-reading to you. Read literally the title of the question has nothing to do with a system proving its own consistency. It's just saying given $\phi$, can I change some consistent system so it proves $\phi$. To which the answer is "not in general, unless you don't care about the intended meaning of $\phi$ in the original system". No lecture on the incompleteness theorem is required to see this.
Comment: I think you have misunderstood the question. The OP is asking if you can find a consistent formal system that proves some given statement.
Comment: @RobArthan: Well I think I have understood the question, since I've seen enough such questions about the incompleteness theorems to know what the askers are after. A few examples of this kind [here](http://math.stackexchange.com/q/1888042/21820) and [here](http://math.stackexchange.com/q/1894926/21820) and [here](http://math.stackexchange.com/q/485343/21820). Besides, the title of this question says it all: Can we **change** the formal system itself to prove its own consistency while maintaining its consistency? Which I have hence answered. =)
Comment: The title of the question does not mention the system proving its own consistency.
Comment: @RobArthan: You don't get my point. People who do not understand the incompleteness theorem always think they can get around it. It is clear enough why the asker asks "can ... **be proven by changing**..."...
Comment: @RobArthan: Yes I agree that as stated the titular question has nothing to do with the incompleteness theorem, and I'm doing mind-reading to guess the real question. =)
Comment: @AliquidExNihilo: Okay. But you may be interested to know that the answer to your question is still the same. Namely, there is no such thing as absolute arithmetic truth. Ultimately, the meta-system MS must have some collection that is a model of PA. From its viewpoint **MS believes that that model is the true collection of natural numbers**, and measures truth against that. But MS itself could have other axioms that make its understanding of natural numbers **wrong to a different meta-system**. Worse still, it is entirely possible for MS to think that MS proves some wrong arithmetic sentence!
Comment: Even if MS is consistent. There's no digression for you to be sorry about anyway. And if you're already familiar with basic logic and computability, you would certainly benefit from the computability perspective because it shows the same issue; in MS we define what is a program, but every program is a finite string, which can be coded and manipulated as a natural number. So MS believes that there is no program (based on **its understanding of natural numbers**) that can compute the truth value of every arithmetical sentence (which is also defined based on **the same 'natural numbers'**).
Comment: @AliquidExNihilo: In other words, there is no possible absolute notion of natural numbers! =)


What is meant by URL routing?

Question: Can any one explain me what URL routing is meant by? And try to give me small example also so that I can understand more.
Comment: Try to do a research before asking questions.
Comment: http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
Answer: If you write http://www.example.com/sample
and the browser opens
http://www.example.com/sample.aspx
or
http://www.example.com/sample.php
page then it would be called as URL Routing Rewriting
for example you can visit this link
http://intelliscence.co.uk/fd/
http://intelliscence.co.uk/fd/default.aspx
both link open the same page
Answer:
The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.

I can give lot more explanation here, but you will benefit more from reading this article from Asp.net website :- ASP.NET MVC Routing

What is meant by URL routing?


How to extract output values from piecewise linear regression in segmented package

Question: I am using the segmented package to run a piecewise linear regression.  My regression model is called fmod, and I use:
fmod$psi[1]

to extract the first breakpoint from the summary. To view the slopes of each piece of the regression, I use:
slope(fmod)

and to view the intercepts of each piece, I use:
intercept(fmod)

However, I am unable to extract a single slope estimate or intercept estimate from the output. Does anyone know how to do this?
Comment: This question appears to be off-topic because it is about how to use R, not statistics.
Comment: This question appears to be off-topic because it is about how to use R without a reproducible example.
Answer: Looking at the help, in general it is supposed to return a list of matrices
For a simple segmented regression, it looks like slope appears to return a single element list, which itself contains a matrix.
So slope(fmod)[[1]][i,j] will return the i,j element of the first matrix in the list. You can pull out whole rows or columns of the matrix as you would normally.
intercept works similarly.
Use str to examine objects and see what they consist of and help to see what they're supposed to contain.


Como transformar este array?

Question: Tenho um formulário que em certos campos me retorna várias possibilidades de dados em um único índice quando faço print do array. Esta situação pode ser vista nos índices 3, 4, 5 e 7.
Array
(
    [0] => APARTAMENTO
    [1] => CASA
    [2] => CASA EM CONDOMINIO
    [3] => COBERTURA/COBERTURA HORIZONTAL
    [4] => CONJUNTO/SALA/LOJA
    [5] => FLAT/LOFT
    [6] => PREDIO COMERCIAL
    [7] => TERRENO/AREAS
)

Eu preciso chegar a este resultado em PHP para que então eu possa começar as minhas consultas no banco de dados:
Array
(
    [0] => APARTAMENTO
    [1] => CASA
    [2] => CASA EM CONDOMINIO
    [3] => COBERTURA
    [4] => COBERTURA HORIZONTAL
    [5] => CONJUNTO
    [6] => SALA
    [7] => LOJA
    [8] => FLAT
    [9] => LOFT
    [10] => PREDIO COMERCIAL
    [11] => TERRENO
    [12] => AREAS
)

Cheguei a este resultado com este formulário:
<input type="checkbox" name="tipo[]" value="APARTAMENTO" id="tp1">
Apartamento

<input type="checkbox" name="tipo[]" value="CASA" id="tp2">
Casa

<input type="checkbox" name="tipo[]" value="CASA EM CONDOMINIO" id="tp3">
Casa Condomínio

<input type="checkbox" name="tipo[]" value="COBERTURA/COBERTURA HORIZONTAL" id="tp4">
Cobertura

<input type="checkbox" name="tipo[]" value="CONJUNTO/SALA/LOJA" id="tp5">
Conjunto/Sala/Loja

<input type="checkbox" name="tipo[]" value="FLAT/LOFT" id="tp6">
Flat/Loft

<input type="checkbox" name="tipo[]" value="PREDIO COMERCIAL" id="tp7">
Prédio Comercial

<input type="checkbox" name="tipo[]" value="TERRENO/AREAS" id="tp8">
Terreno/Área

Passando somente isso como instrução:
$tipo = $_GET['tipo'];

Por questões de layout, não posso fazer com que estes campos sejam diferentes, tipo um tipo por input. Alguma ideia??
Comment: Você precisa mostrar o código/consulta que gera `item1/item2`, como é esse formulário? Como chegou a essa array?. . . .
 Se me permite um pequena critica, noto que geralmente falta esse tipo de informação nas suas perguntas.
Comment: Depende de como você está agrupando. Talvez um loop + explode na / resolva, mas acho que está agrupando errado.
Comment: Já que está agrupando no campo `value="OPÇÃO 1/OPÇÃO 2"`, um loop resolve. Outra solução seria montar via JS com cmapos ocultos.
Comment: Não sei como fazer tratamento de `arrays`, podem me dar um caminho??
Answer: Uma forma simples seria usando implode na array usando '/' e depois transformando em array com explode '/'. Joguei agora no ideone.
$array = array(
0 => 'APARTAMENTO',
1 => 'CASA',
2 => 'CASA EM CONDOMINIO',
3 => 'COBERTURA/COBERTURA HORIZONTAL',
4 => 'CONJUNTO/SALA/LOJA',
5 => 'FLAT/LOFT',
6 => 'PREDIO COMERCIAL',
7 => 'TERRENO/AREAS',
);

print_r( explode( '/' , implode( '/' , $array ) ) );
// output abaixo
Array
(
    [0] => APARTAMENTO
    [1] => CASA
    [2] => CASA EM CONDOMINIO
    [3] => COBERTURA
    [4] => COBERTURA HORIZONTAL
    [5] => CONJUNTO
    [6] => SALA
    [7] => LOJA
    [8] => FLAT
    [9] => LOFT
    [10] => PREDIO COMERCIAL
    [11] => TERRENO
    [12] => AREAS
)

Comment: Agora que eu tenho a `array` posso fazer uma consulta SQL usando ela certo?? Obrigado pela ajuda.
Comment: Os poderes de implode() as vezes me assusta. Eu estava aqui pensando em algo com array_walk_recursive() e tal daí veio esse corte rápido feito ninja e... Vish...
Comment: Primeiro teste foi loop, depois vi que ia explodir a `/`, então resolvi implodir com ela para resolver os 2 problemas. E a sequencia fica pequenininha :)

Como transformar este array?


How to Find Confidence Level of Results

Question: I am curious to find out the confidence level of results. It's best to give an example of what I mean cause I struggle to speak in the technical terms.
Example:
Jack runs an advertisement that 1000 people see. 10 of those people convert and actually purchase something. Jack is sure his conversion rate is 1%.
Sally disagrees. She thinks Jack doesn't have enough of a statistical confidence level in this result. What is the confidence level of 1% being the result.
A formula to get that would be great.
EDIT:
I'm trying to add a statistical element to my marketing for my business. I plan to run a lot of advertisements so am trying to find a way to understand how many results I need to collect before I can prove or disprove a hypothesis I am testing.
Let's say for example my hypothesis is that running a certain ad will result in a conversion rate of 3% of people clicking the ad overtime.
For now, let's say I have just started the experiment and out of 1000 people, 30 did click it. So it seems that the the conversion rate (or probability of a person click the ad) is 3% (0.03 in probability).
However, I shouldn't trust these results because the sample size is too small. Instead I want to know what is probability that 3% (+ or - a margin of error) is indeed the conversion rate?
I thought I'd have to use a confidence intervals but now I'm thinking I should probably something that involves variance. I'll do some more research and update this when I find more. If you have any thoughts in the mean time on how to solve this problem, please let me know. Much obliged.
Comment: A confidence level has to do with [confidence intervals](https://en.wikipedia.org/wiki/Confidence_interval), not point estimates/point forecasts. You might have some measure of uncertainty (standard error, root-mean-square prediction error etc etc) about the estimate or forecast, or indeed, you might perhaps generate a confidence interval (among other possibilities), but you'll have to help us understand more about what kind of thing you're talking about. What did you mean by 'confidence level'? NB with continuous variables the probability that a point forecast is exactly correct will be zero
Comment: "Instead I want to know what is probability that 3% (+ or - a margin of error) is indeed the conversion rate?" This sounds like you want a Bayesian posterior probability for an interval 3% + or - a margin of error. For this you need to specify a prior distribution and then run standard Bayesian calculus.
Comment: How about a numeric tool?  Is this homework?
Comment: My apologies for my incompetence. I'll give so more detail in the original question.
Comment: @JackRobson How did you solve this if I may ask?
Comment: I never did. I've just opened a bounty for 100 points. Hopefully this will get some attention.
Comment: (+1) If this is related to A/B tests or evolution of conversion rate over time, you may want to take a look at sequential testing, and [How Not To Run an A/B Test](https://www.evanmiller.org/how-not-to-run-an-ab-test.html), for instance.
Answer: Since you are uncertain about what may be the true conversion rate of the ad, you should consider using bayesian approach:
Let $X$ be an r.v such that $X=1$ if the ad is successful. So $X \sim Be(p)$, where $p$ is the conversion rate of the ad and let's assume further that $p \sim U(0,1)$. So basically you have a no prior belief about how efficient the ad might be (this of course can be changed by changing the prior distribution).
Further for $n$ independent $X_i$, $Y \equiv {\sum_n X_i} \sim Bin(n,p)$
From Bayes' theorem:
$$f(p| Y=y) = \frac{Pr(Y=y|p)f(p)}{Pr(Y=y)}$$
From distribution of $Y$, we know that  $Pr(Y=y|p) = {n\choose y} p^y(1-p)^{n-y}$ and $f(p)=1$
Unconditional probability of $Y=y$:
\begin{align}
Pr(Y=y)&={n\choose y}\int_0^1 p^y(1-p)^{n-y} f(p)dp \\
&= {n\choose y}\int_0^1 p^y(1-p)^{n-y}dp \\
&= {n\choose y}\frac{y!(n-y)!}{(n+1)!} \\
&= \frac{1}{n+1}
\end{align}
See this for the proof of above integral.
So we have:
$$f(p| Y=y) = {n\choose y}(n+1)p^y(1-p)^{n-y}$$
So you now have a full posterior distribution of conversion rate. You can simulate this distribution and/or sample from it to construct your credible interval, preferably a highest posterior density interval, to get an estimate of upper and lower bounds of your estimate for a given level of confidence.
EDIT: Embarrassingly, didn't notice that the posterior is beta distribution.
So, $$f(p| Y=y) \sim Beta(\alpha, \beta)$$
where $\alpha = y+1$ and $\beta=n-y+1$
Therefore for credible interval at 5% significance can be calculated using R:
<code>> n=1000
> y=10
> a=y+1; b=n-y+1
> qbeta(0.025,shape1 = a,shape2 = b) # p_lower
[1] 0.005498084
> qbeta((1-0.025),shape1 = a, shape2 = b) # p_upper
[1] 0.01829503
</code>
So for your sample:
$$Pr(0.0055 \leq p \leq 0.0183 | Y=10)=0.95$$
Answer: The classical parametric approach in frequentist statistics would be to model the situation as follows. Suppose all the people who see a certain advertisement are all independent of each other and have the same probability $p$ of clicking on the advertisement. We say these people form a Bernoulli population, i.e. a member $X$ of this population either reacts ($X=1$) to the advertisement or does not ($X=0$) with probabilities $p$ and $1-p$ respectively. Suppose you now take a sample of size $n$ ($n=1000$ in your case) of the population, so you observe $X_1, \ldots, X_n$ and see how many of them have clicked. In other words, we observe the sample average
$$
  \bar{X} = \frac{1}{n} \sum_{i=1}^n X_i
$$
In your case, you observe $\bar{X}=0.01$ and you are using this sample average as an estimate of the unknown population parameter $p$, i.e. $\hat{p}=\bar{X}$.
The statistical exercise we have to make now is deciding how 'reliable' or how 'precise' this estimate is. The central question here is: assuming the population fraction is indeed $p$, then what values of our estimator $\bar{X}$ are we likely to observe in a sample of size $n$? This brings probabilities into to the story. Specifically, we know (possibly to be explained further) that the sample sum $n\bar{X}$ is binomially distributed:
$$
   \text{Prob}[n\bar{X} = i] = \binom{n}{i} p^i(1-p)^{n-i}\,,\qquad i=0,\ldots,n
$$
This is the point now where most people will suggest the approximation $\bar{X}\sim \text{N}(p,\frac{p(1-p)}{n})$ which works fine if $n$ is large compared to $np$. So instead of the discrete binomial distribution, we now use the continuous normal distribution which is somewhat easier to work with. For example, it follows (could also be explained further) that
$$
   \frac{\bar{X} - p}{\sqrt{\frac{p(1-p)}{n}}} \sim \text{N}(0,1)
$$
has the standard normal distribution. Note that this distribution now no longer depends on $p$ or any other population parameter and for that reason, we call this quantity a pivot. Pivots are extremely useful to construct hypothesis tests and/or confidence intervals from. In our case, let $z_{\alpha/2}$ and $z_{1-\alpha/2}$ be the left and right quantiles of the standard normal distribution (in case $\alpha=0.05$ then these are the familiar values -1.96 and 1.96 respectively), then using the known distribution of the pivot:
$$
   1-\alpha = \text{Prob}[ z_{\alpha/2} < \frac{\bar{X} - p}{\sqrt{\frac{p(1-p)}{n}}} < z_{1-\alpha/2} ]
$$
which after some manipulations becomes
$$
   1-\alpha = \text{Prob}[ \bar{X} - z_{1-\alpha/2} \sqrt{\frac{p(1-p)}{n}} < p < \bar{X} - z_{\alpha/2} \sqrt{\frac{p(1-p)}{n}} ]
$$
These bounds form an (unobserved) confidence interval. Note that the left and right bound  are not proper statistics. That means that strictly speaking, these left and right bounds can not be computed from a sample because we don't know what $p$ is! Yet another pragmatic approximation is to use the estimate $\hat{p}=\bar{X}$ instead of $p$ in these bounds. That brings us finally to:
$$
 \text{a } (1-\alpha)\text{-CI for }p\text{ is }[\bar{X} - z_{1-\alpha/2} \sqrt{\frac{\bar{X}(1-\bar{X})}{n}} , \bar{X} - z_{\alpha/2} \sqrt{\frac{\bar{X}(1-\bar{X})}{n}}]
$$
This often used way of constructing a CI is the culmination of two approximations: First we use CLT to apprimate the binomial distribution by a normal distribution and then we estimate the standard error by using $\hat{p}=\bar{X}$. In most cases however, the resulting CI is useful. Sometimes however, the lower bound can be negative or the upper bound larger than 1 which makes no practical sense for a parameter like $p$.
For $\alpha=0.05$, $n=1000$ and $\bar{X}=0.01$ we have the CI $[0.0038,0.0162]$.
Answer: Assuming that all people make independent choices, we can model the experiment as draws $X_i$ from a Bernoulli($p$) distribution with $E(X_i) = p$ and $\sigma^2(X_i) = p(1-p)$. For large $n$ ($n = 1000$ in your case) the independent draws from the Bernoulli distribution can be modelled as a Normal distribution according to the Central Limit Theorem. We then have for our Maximum Likelihood Estimate $\hat{p}$ ($\hat{p} = 1\%$ in your first example and $\hat{p} = 3\%$ in your second one)
$$ \frac{\hat{p} - p}{\sigma_p/\sqrt{n}} \sim N(0,1)$$
From this, we can construct the 'Confidence Interval'
$$ \hat{p} \pm \frac{z_{\alpha/2}}{\sqrt{n}}\sigma(p) $$
where $ z_{\alpha/2}$ is the required z-score for the interval to contain the true value with probability $1-\alpha$. In order to make this a true Confidence Interval we need an estimation for $\sigma_p$ and could for example use $\sigma_p \approx \sigma_\hat{p} = \sqrt{\hat{p}(1-\hat{p})}$.
In your first example we then obtain the 95% Confidence Interval [0.38, 1.62] (in percent) and in your second example [1.94 4.06].
Note that the second Confidence Interval is larger, despite the same number of people that participated in the experiment. This is due to the fact that $\sigma_\hat{p} = \sqrt{\hat{p}(1-\hat{p})}$ has its maximum for $\hat{p} = 0.5$. This fact is often used in opinion polls (for example for elections) that can be modelled as draws from a Bernoulli distribution as well. You will notice that the number of people that are being asked is often at around 1000, which leads to a margin of error $\pm 3\%$ at the 95% confidence level using the same calculation as above (under the assumption that $p=0.5$).

How to Find Confidence Level of Results


How to combine JUnit4 @RunWith(Parameterized.class) and JUnit5 @ParameterizedTest

Question: I am trying to combine the concept of a Parameterized runner from JUnit4 with the JUnit5 Parameterized Test. Essentially I want to test two separate functions on the same set of data.
I know I could just add the function as another argument to the parameterized test itself but I am trying to make changing or adding new functions to test easy.
Would I be able to leverage nested test classes to achieve this? I am not sure the best way to approach.
@RunWith(Parameterized::class)
class RomanNumeralTest(val func: (Int) -> String) {

    @ParameterizedTest(name = "{index} - Expect [{0}] should return [{1}]")
    @MethodSource("testData")
    fun `Test roman numeral from integer values`(num: Int, expected: String) =
            assertEquals(expected, func(num))

    companion object {

        @JvmStatic
        @Parameterized.Parameters
        fun data(): Collection<Array<(Int) -> String>> {
            return listOf(
                    arrayOf({num -> roman(num)}),
                    arrayOf({num -> num.toRomanNumeral()})
            )
        }

        @JvmStatic
        private fun testData() = sequenceOf(
                arrayOf(1, "I"),
                arrayOf(2, "II"),
                arrayOf(3, "III"),
                arrayOf(4, "IV"),
                arrayOf(5, "V")
        ).asStream()
    }
}

Comment: Dont mix junit4 and junit5 in same test class. You can use same @MethhodSource on multiple test easily.
Comment: Hey Imre, can you provide an example of what you mean?
Answer:
I tried the same but in the end I came to the conclusion that: you can't.

There is no way you can use the JUnit 4 Parameterized test runner using the annotations which came with JUnit 5.
You need to move to JUnit 5 to use the latest features like TestFactory or all the powerful annotations of parameterized tests described here


Does the absolute value of MAPE or sMAPE have meanings?

Question: Let say I have a forecasting system compared with a naive forecast that just use the today's value as forecast. If the naive forecast have a MAPE of 200%, and my system have a MPAE of 100%, could I say my system is useful?
On one hand, my system halved the MAPE, but on the other hand, my system still have a 100% MAPE, while many text book, guideline suggested that MAPE should be <10%. but some guideline say it is still depending on the performance of baseline model.
Other metric like RMSE and MAE also was halved by my system.
Any comments and suggestions are appreciated.
Answer:
Let say I have a forecasting system compared with a naive forecast that just use the today's value as forecast. If the naive forecast have a MAPE of 200%, and my system have a MAPE of 100%, could I say my system is useful?

That can be useful, or not. On the one hand, smaller errors are always more impressive. On the other hand, the relationship between forecast accuracy and value is absolutely not straightforward (Kolassa, 2023). On the third hand, the MAPE especially has major issues: What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? A flat zero forecast will give you a MAPE of 100%, but whether this is in any way more useful than a non-zero forecast with a MAPE of 200% is still very doubtful.
Assess the value of your forecast, not the error.

many text book, guideline suggested that MAPE should be <10%.

It makes no sense whatsoever to give a hard number as to what an error "should" be (other than a MAPE greater than 100% can always be beaten by a flat zero forecast). The possible forecast accuracy is always context dependent. If you forecast a coin toss with equally probable outcomes of zero and one, then you will not be able to get a better weighted MAPE than 100%. the score to hope for when evaluating model by MAE, MSE or RMSE and Kolassa (2008).
If your textbook tells you that the MAPE "should" be less than 10% without reference to a very specific dataset, then you should get rid of that textbook. There are better books out there, many of them online for free: Resources/books for project on forecasting models
Comment: I think the RMSE and MAE also halved suggesting that in term of forecast value, my system is also better. I do see that many forecasting paper in my field did not give MAPE instead, so is it something that we should always use?
Comment: Reductions in other metrics also sounds good. I don't quite understand your second question, are you asking whether you should use the MAPE more? I would *not* say so, I believe the MAPE is dangerous and misleading. [See the special feature in here](https://forecasters.org/product/foresight-issue-69/), ping me via ResearchGate for my simulation article if you are interested, and I can send you the entire special feature.


Prove that if $12a+6b+4c+3d=0$, then $a+bx+cx^2+dx^3=0$ has a real solution in $(0,1)$

Question: Assume that $a,b,c,d$ are real numbers such that $12a+6b+4c+3d=0$.
Prove that $a+bx+cx^2+dx^3=0$ has a real solution in $(0,1)$.
Note : I have no idea ! How is the assumption even related to the statement that the question wants us to prove? I don't understand.
Second Note ( Edited ) : I know that if $x$ is too large, the equation goes to $+\infty$ and when $x$ is so much below $0$, the equation goes to $-\infty$. Then we can apply mean value theorem and say there exists some point such that on that point, the equation becomes zero. It's ok. But how to show that the root is in $(0,1)$ and what is the use of knowing $12a+6b+4c+3d=0$?
Thanks in advance.
Comment: A cubic with real coefficients always has at least one real solution, so you need only about the case where $d=0$ (and $c\not=0$).
Comment: @BarryCipra i don't know about the theorem you're using
Comment: @TinaAshtiani I believe the theorem is called the leading coefficient test
Comment: The intermediate value theorem is used on the continuous function $f(x) = a + bx + cx^2 + dx^3$.
Comment: @GFauxPas well, we didn't learn it on the class ... so i can't use it
Comment: Every cubic equation (1), $ax^3 + bx^2 + cx +d = 0$, with real coefficients and $a$ ≠ 0, has three solutions (some of which may equal each other if they are real, and two of which may be complex non-real numbers) and at least one real solution r1 : Wikipedia
Comment: So you just set $|x|$ sufficiently large, say $$x = \frac{|a|+|b|+|c|}{|d|+1}$$ to conclude the leading coefficient test.
Comment: Now put $d=0$ and solve it.
Comment: @S.H.W i truely appreciate your help. But can u please say that how is knowing the first assumption useful ?
Comment: @TinaAshtiani The condition is strange and unnecessary, which is why you're not getting a useful answer. Can you tell us where the problem came from? Is there any missing context? Are you sure you copied it correctly?
Comment: @EthanBolker real analysis a first course russell gordon . Questions of section 4.4 ... the first question
Comment: @TinaAshtiani Please read my answer.
Comment: Use Rolle's Theorem.
Answer: It turns out that $12a+6b+4c+3d=0$ is the condition that makes Rolle's Theorem applicable. Let
$$ f(x)=\int_0^x(a+bt+ct^2+dt^3)dt=ax+\frac b2x^2+\frac b3x^3+\frac d4x^4.$$
Then clearly $f(x)$ is continuous in $[0,1]$, differentiable in $(0,1)$, $f(0)=0$, and
$$f(1)=a+\frac b2+\frac b3+\frac d4=\frac{1}{12}(12a+6b+4c+3d)=0.$$ By Rolle's Theorem, there is $\xi\in(0,1)$ such that $f'(\xi)=0$, namely $a+bx+cx^2+dx^3=0$ has a root in $(0,1)$.
Answer: We know Every cubic equation $dx^3+cx^2+bx+a=0$
with real coefficients and $d\not= 0$ has three solutions (some of which may equal each other if they are real, and two of which may be complex non-real numbers) and at least one real solution. So now we put $d=0$ and we get :
$$cx^2+bx+a=0$$
and
 $$12a + 6b+ 4c =0 \to 6a+3b+2c = 0 \to b = \frac{6a+2c}{-3}$$
 Now we want to $\Delta_1 \ge0$ ( to has real root).
$\Delta_1 = b^2-4ac = \frac{36a^2+4c^2+24ac}{9} - 4ac = \frac{36a^2+4c^2-12ac}{9}\ge0\iff 9a^2-3ac+c^2\ge0$
Which it is obvious because $\Delta_2 = -27a^2c^2\le0$
Note : When $\Delta \lt 0 $ quadratic polynomial has same sign as coefficient of $x^2$.(In this case 9) and if $\Delta = 0$ value of quadratic polynomial will be zero at one point and in other points has same sign as coefficient of $x^2$.
Answer: Here are a few things that might help guide you in the right direction:
Let $f(x)$ = $a+bx+cx^2+dx^3$
If $d\neq 0$ :
1) Is $f$ continuous?
2) What is $\lim_{x\to \infty}$$f(x)$? What is $\lim_{x\to -\infty}$$f(x)$?
3) What do we know about the signs of the above two limits, and what can this tell us about the existence of a zero/root?
If $d=0$ , $f$ has degree $\leq2$
How can we show a quadratic (or linear) function has a zero/root?
Comment: I understand what you're saying ... but doesn't it seem so simple ? what's the use of $12a+6b+4c+3d=0$ ?
Comment: Read my comment.
Comment: If you are asking whether the consequence of the Intermediate Value Theorem seems so simple/obvious, then you are not alone in thinking that.  It does seem intuitive that if you have a continuous function that is at some point negative and at another point positive, that there must be a point in between the two such that f is 0 at that point.
Comment: The additional constraint essentially says that perhaps d=0 (and maybe the other coefficients are zero as well).  In the case that d is 0 but c is not 0, we cannot guarantee the existence of a zero using the argument we did for the cubic.  This is because the end behavior of a quadratic has the same sign for both ends.
Comment: If $d=0$, then $12f(\pm\frac1{\sqrt 3})=12a\pm 4\sqrt 3 b+4c=(\pm 4\sqrt 3-6)b$, one is $>0$, one is $<0$ (or both are $=0$)


Flutter better_player Package Stop and Play Video using Controller

Question: I'm new with flutter and currently using better_player: ^0.0.81 package.
Is there anyway to stop the video using a controller? Here is my code below
late BetterPlayerController _betterPlayerController;

Function
_betterPlayerController = BetterPlayerController(
  const BetterPlayerConfiguration(
    autoPlay: true,
    fit: BoxFit.contain,
    controlsConfiguration: BetterPlayerControlsConfiguration(
      enableOverflowMenu: false,
      showControlsOnInitialize: false,
      enableRetry: true,
      showControls: true,
    ),
  ),
  betterPlayerDataSource: BetterPlayerDataSource.file(videoPath),
);

Widget
  AspectRatio(
       aspectRatio: 16 / 9,
       child: BetterPlayer(
                controller: _betterPlayerController,
       ),
   )

Answer: If you mean pause and play, then just call it by using the controller.
eg: _betterPlayerController.pause();  or  _betterPlayerController.play();


Show $f(z)=2u\left( \frac z2, \frac{-iz}{2}\right ) + \text{constant} $ if $f(z)=u(x,y)+iv(x,y)$ is an analytic function

Question: Suppose  $f(z)=u(x,y)+iv(x,y)$  be an analytic function. Show that
$ \displaystyle (a)\;  f(z)=2u\left(\frac z2,\frac{-iz}{2} \right ) +\text{ constant} \\(b) \; f(z)=2iv\left(\frac z2,\frac{iz}{2} \right )+\text{ constant}$
Comment: The question as stated makes no sense. $u$ and $v$ are functions of two real variables, you can't feed them complex numbers.
Comment: My complaint still stands. $u$ and $v$ are functions from $\mathbb{R}^2$ to $\mathbb{R}$, you can't give them complex numbers as arguments.
Comment: Sry but why you say "If $f(z)=u(x+y)+i v(x,y)$", using $z=x+iy$ one can always express as $f(z)=\Re(f(z))+\Im(f(z))=\Re(f(x+iy)) + \Im(f(x+iy))$
Comment: @DominicMichaelis the question was written that way, "Let $f(z) = u(x,y) + i v(x,y) $  ..." any idea on the problem part??
Comment: It reminds me a bit of the equivalent definition of complex differentiable ...
Comment: @JavierBadia sorry, i have forgotten something.
Comment: Yes, there is a real theorem here.  (But Mula has not stated it yet.)  Try $f(z) = z^2$, $u(x,y) = x^2-y^2$, and $v(x,y)=2xy$.  Then it makes sense to plug in complex numbers in $u$ and $v$, and the claimed formula works!
Comment: One way to make sense of this is: If $f$ is complex analytic, then $u$, $v$ are real analytic and if you extend $u$ and $v$'s definition to the complex plane in the obvious manner, does $f$  and the extended $u$, $v$ satisfy the stated conditions?
Answer: Part (a) of your question is discussed in Ahlfors' "Complex Analysis" text on page 27. He warns ahead of the discussion that it is purely formal and shouldn't be used to prove anything.
First of all, you need to consider the formal derivatives:
$$\frac{\partial f}{\partial z}=\frac{1}{2} \left(\frac{\partial f}{\partial x}-i \frac{\partial f}{\partial y} \right), \frac{\partial f}{\partial \bar{z}}=\frac{1}{2} \left(\frac{\partial f}{\partial x}+i \frac{\partial f}{\partial y} \right). $$
Note that the Cauchy-Riemann equations are simply $\frac{\partial f}{\partial \bar{z}}=0$.
Take any analytic function $f(z)=u(x,y)+iv(x,y)$, Its conjugate $\overline{f(z)}$ satisfies $\frac{\partial \overline{f(z)}}{\partial z}=0$. Formally this means that $\overline{f(z)}$ is a function of $\bar{z}$ only; Denote this function by $\bar{f}(\bar{z})$. Thus we have
$$u(x,y)=\frac{1}{2} \left( f(x+iy)+\bar{f}(x-iy) \right).$$
Once again, we formally interpret this identity for complex $x,y$. We can therefore plug in $x=\frac{z}{2},y=\frac{z}{2i}$, and obtain:
$$u \left(\frac{z}{2},\frac{z}{2i} \right)=\frac{1}{2} \left( f(z)+\bar{f}(0) \right), $$ which is upon rearrangement $$f(z)=2u \left(\frac{z}{2},\frac{z}{2i} \right)+\text{const}. $$
Part (b) can be done similarly.
The greatest issue here is plugging in complex values for $x,y$. In general it cannot be done, but for simple functions, such as polynomials, everything is OK.
Answer: Perhaps you need some hypotheses?  For example
$$
|z| = \sqrt{x^2+y^2} + i\cdot 0;\quad f(z):=|z|, u(x,y) := \sqrt{x^2+y^2}, v(x,y):=0
$$
but
$$
2u(z/2,-iz/2) = 2\sqrt{\left(\frac{z}{2}\right)^2+\left(\frac{-iz}{2}\right)^2}
=2\sqrt{\frac{z^2-z^2}{4}}=0
$$
Comment: The condition "analytic" was added just 4 hours ago.  That is what I meant by "perhaps you need some hypotheses".
Comment: could you recheck, I had been missing something
+ c o n s t a n t  was at the end
Comment: @GEdgar, the function you defined is not holomorphic so it doesn't even apply.


Angular 2 - Is it possible to use the new router while upgrading with the "Upgrade Adapter"

Question: I am upgrading my application progressively using the Upgrade Adapter. My app uses ui-router (+ has child routes).
I read this great article about routing in Angular 2. My question is:
Is it possible to use new router while still in Angular 1.X app + Upgrade adapter?
For example:
I have an angular 1.X template with

. When I upgrade it to be Angular 2.0 component I must use the new component router with it, because Angular 2.0 is rendering this component now. But, in order to use it I should do:
bootstrap(App, [provide(LocationStrategy, { useClass: PathLocationStrategy })])

Which I do not have when bootstraping with the Upgrade Adater!
Should I first move the bootstrap to be Angular 2 and only then move to the Component router?
Thanks
Comment: I don't know about UpgradeAdapter, but the code line you posted seems quite outdated. It's <= 2.0.0-RC.5. Now we are at 2.4.6.
Comment: Yep, this question is almost one and a half years old...
Comment: Sorry, the question popped up in the stream because of the edit. I didn't check the date.
Comment: Possible duplicate of [angular ui-router login authentication](https://stackoverflow.com/questions/22537311/angular-ui-router-login-authentication)
Answer: Absolutely! Your component containing ui-view should be changed to a router-outlet, but otherwise, you should be able to convert your routes to AngularJS components and use them with the new RouterModule.


Posso chamar um metodo especifico no spring security sem está logado?

Question: Tenho uma aplicação feita em Spring Boot 2.7, estou usando spring security, gostaria de chamar um método no Back-end sem precisar estar autenticado, no entanto, ao clicar no botão "Chamar" ele me redireciona para a pagina de LOGIN sem chegar no método chamado:
Front:
<h:form autocomplete="off">

</h:form>

Back:
public void teste()
{
    System.out.println("Back-end");
}

Gostaria de chamar o método "teste()" sem precisar logar no spring security
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Para permitir que um método seja acessado sem autenticação no Spring Security, você pode configurar o acesso não autenticado para esse caminho específico na sua classe de configuração de segurança.
Por exemplo, se você tiver uma classe de configuração de segurança, como a seguinte:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .httpBasic();
    }
}

Aqui, o método configure(HttpSecurity http) configura as regras de autorização. A regra antMatchers("/public/").permitAll()** permite acesso não autenticado a qualquer caminho que comece com "/public/".
Para permitir que o método teste() seja acessado sem autenticação, você pode adicioná-lo a um novo caminho em sua classe de configuração de segurança:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/teste").permitAll() // Novo caminho para o método teste()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .httpBasic();
    }
}

Agora, o método teste() pode ser acessado sem autenticação no caminho "/teste". Então, em seu código Front-end, você pode atualizar o actionListener do botão para chamar o caminho "/teste":
<h:form autocomplete="off">

</h:form>

Note que também atualizei o atributo actionListener para action para indicar que estamos chamando um endpoint em vez de ouvir um evento.


A method for propagating labels to unlabelled data

Question: I have a large set of data and a small subset is labelled as being in class 'A' and the rest is unlabelled. I know that some of the unlabelled data should also be labelled 'A'.  In order to label some more of the data my idea is to do the following:

Build a classifier on the whole data set separating the class 'A from the unlabelled data.
Run the classifier on the  unlabelled data.
Add the unlabelled items classified as being in class 'A' to class 'A'.
Repeat.

There are lots of parts that are unclear and/or problematic such as when to stop and how exactly to set the thresholds for when to accept something as being in class 'A'.
Is a method like this known already in the literature so that I can gain some ideas for how to do it properly?
Comment: @Tim one-class SVM is a poor choice for this task, since it doesn't use the unlabeled data at all. PU learning techniques yield *far* better results.
Comment: @Tim I think the problem is there's only one label: "A".  There's no "Not - A" data to learn from.  You're learning from a dataset of "definitely A" and "may or may not be A, who knows."
Comment: Why not just: (1) run the algorithm on labeled data, (2) use the result for labeling unlabeled data?
Comment: There are many classification algorithms out there: classification trees, k-Means, ...
It would be easier to know what your data exactly looks like. But I can refer you to this book http://www-bcf.usc.edu/~gareth/ISL/. You can find a well written introduction to some of the concepts in there.
Comment: @Zach ok, but there are classification algorithms for such cases, e.g. one-class SVM.
Answer: Learning from positive and unlabeled data is often referred to as PU learning. what you describe is a common approach to these kinds of problems, though I personally dislike such iterative approaches because they are highly sensitive to false positives (if you have any).
You might want to check out two of my papers and references therein for an up-to-date overview on current research for these problems:

A Robust Ensemble Approach to Learn From Positive and Unlabeled Data Using SVM Base Models http://arxiv.org/abs/1402.3144 (published in Neurocomputing)
Assessing binary classifiers using only positive and unlabeled data:  http://arxiv.org/abs/1504.06837

The first paper describes a state-of-the-art method to learn classifiers and the second is the only approach that allows you to estimate any performance metric based on contingency tables from test sets without known negatives (you read that right).
Both papers also provide a good overview of the existing literature on this subject.
Comment: +1 it's interesting. Your answer would be even more helpful if you provided a short summary of those methods - how do they work? why are they better?
Answer: What you describe is very sound idea. It is called Semi-Supervised Expectation-Maximization and is oftenly used in text classification. Here is some literature:
http://research.microsoft.com/en-us/um/people/xiaohe/nips08/paperaccepted/nips2008wsl1_02.pdf
http://ciitresearch.org/dl/index.php/aiml/article/view/AIML052012012
http://www.cs.cmu.edu/~tom/pubs/NigamEtAl-bookChapter.pdf


Is it possible to make JDBC connection with PDO?

Question: Is it possible to do something like
Class.forName("com.mysql.jdbc.Driver");

to
$pdo = new PDO("java:com/PakageName/jdbc/Driver");

by adding some .jar files in php project library?
I have made a simple PHP project and want to connect a database remotely which is providing JDBC driver.  Java program works fine but PDO will allow this ?
Answer: JDBC is only for JAVA database connectivity. Here PHP can use ODBC Connection with PDO_ODBC. ( Go through with the documentation )
PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers.
Example:
<?php

  $dbh= new PDO('odbc:SOURCENAME', 'username', 'password');
  $stmt = $dbh->prepare("$query");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
      print_r($row);
  }
  unset($dbh); unset($stmt);
?>

Useful link: http://php.net/manual/en/pdo.drivers.php
Comment: Thanks SHAZ for find time to answer. PHP-Java bridge will do the work like pass a query to java function and java function returns result or something like that.?


Replace some characters explicitly given in XSLT

Question: I saw many answers to this question (like this one) who match a (little) pool of alloweded characters with translate(input, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', '') instead of matching directly unhallowed characters.
I need to proceed by the reverse way because the characters I want to remain are, basically wool Unicode, when the ones I want to replace with dash are just : !$&'*+,-./:;=?@_~.
So, how to match the characters bellow and only these ones, to replace them by dash?
Comment: I'm not sure I understand your question. What you mean is that if you have a string like "abc!def$gh", you would want it to become "abc-def-gh"?
Comment: Does this answer your question:
https://stackoverflow.com/a/1267981/3710053
Comment: What exactly is "dash"? Your list of characters to replace includes `-` (HYPHEN-MINUS).
Answer: If I understand your question correctly, you want to do:
<xsl:value-of select='translate(input, "!$&'*+,-./:;=?@_~", "-----------------")'/>


Print the first item in list, wrong output

Question: code:
 # open some file
    for line in fp:
        list = line.strip().split();
        list = str(data_list);
        print(list[0]);

My output:
[

Expected Output: 2,500,000.00
                  some other number, only first item in every list
In my list:
['2,500,000.00', '—', '2,999,999.99', '6,871', '158,164,946', '99.98619', '18,747,446,313.27', '2,728,488.77']
and more......

Comment: Why are you converting your list to a string?  The first item in a string is the first character; the first item of the list is probably what you want.
Comment: What is the output of `print(data_list[0])`?
Comment: You could start by printing out your whole array with "print(list)". Then you will see, whether it's a problem with the array itself or with the index.
Comment: @zondo sorry, wasn't think straight
Answer: That's because it's not a list. You are converting list into a string:
    list = str(data_list);
    print(list[0]);

, remove it and it should work fine.
Comment: Thank you. I wasn't thinking straight.
Comment: Sure, no problem. Just make sure you accept the answer if it solves your problem.


Django boolean annotate returning duplicates

Question: I have the following models:
class Institution(models.Model):
    pass

class Headquarter(models.Model):
    institution = models.ForeignKey(Institution, related_name='headquarters')

class Audit(models.Model):
    headquarter = models.ForeignKey(Headquarter, related_name='audits')

And the following query (basically, if an institution has at least one audit then has_visits must be true:
Institution.objects.annotate(
    has_visits=models.Case(
        models.When(headquarters__audits=None, then=False),
        default=True,
        output_field=models.BooleanField()
    )
 )

The problem is that if an institution has 2 audits then the queryset returns duplicate rows. I imagine it has something to do with the joins at the SQL level but I'm not sure how to correct it. I found this answer but I don't think OuterRef is what I'm looking for in my situation. What's the right way to accomplish this?
Answer: You can work with an Exists subquery [Django-doc]:
from django.db.models import Exists, OuterRef

Institution.objects.annotate(
    has_visits=Exists(
        Audit.objects.filter(headquarter__institution=OuterRef('pk'))
    )
)
Something else that could help is to let the duplicates "collapse", for example with a Max:
from django.db.models import Max, Value
from django.db.models.functions import Coalesce

Institution.objects.annotate(
    has_visits=Coalesce(Max(models.Case(
        models.When(headquarters__audits=None, then=False),
        default=True,
        output_field=models.BooleanField()
    )), Value(False))
)
but that likely makes it less readable and less efficient.
Answer: For some extra context: I think this is related to a known and documented limitation (though the docs are easy to miss). The docs on aggreation have this section (copied from Django 4.2 docs):

Combining multiple aggregations
Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries:
>>> book = Book.objects.first()
>>> book.authors.count()
2
>>> book.store_set.count()
3
>>> q = Book.objects.annotate(Count('authors'), Count('store'))
>>> q[0].authors__count
6
>>> q[0].store__count
6

For most aggregates, there is no way to avoid this problem, however, the Count aggregate has a distinct parameter that may help:
>>> q = Book.objects.annotate(Count('authors', distinct=True), Count('store', distinct=True))
>>> q[0].authors__count
2
>>> q[0].store__count
3

This documentation is about aggregates that produce joins in an annotation, but I suspect essentially the same happens for annotations that produce a join by themselves, like the OP's example.
Another way to circumvent the limitation (though it might not be applicable to the OP's problem) is to put the aggregate in a subquery. I previously explained how to use the django-sql-utils package for this:

For anyone else running into this, a reasonable workaround seems to be to use subqueries for aggregating annotations. This is a bit verbose/hacky in Django currently, as shown by the multitude of approaches in the stackoverflow link from Antoine's comment. However, I've successfully used the django-sql-utils package for this just now. That sounds a bit bulky, but it just has two utilities, one of which is a SubqueryAggregate class (with derived SubqueryCount, SubquerySum, etc.) that make converting a regular joining aggregate into a subquery aggregate easy and concise, without changing the structure much.
For example taking the example from comment 66 and converting the second annotation to a subquery with django-sql-utils, you'd get:
Branch.objects.annotate(
    total=Sum('center__client__loan__amount'),
    repaid=SubquerySum('center__client__loan__payment_schedule__payments__principal'),
)

There is also a bug report tracking this limitation. The OP's code is a bit more like this bug, which was closed as a duplicate of the first one.


Which symbol should I use to indicate "transpose"?

Question: I'm making an online chord database, and I want symbols instead of words to label everything, so it can be used by non English speakers. E.g. instead of "Home" I have a picture of a house.
I have a feature to transpose chords up or down, and I'm just wondering if there's a standard symbol for "transpose"?
Comment: Are these guitar chords or piano chords or something else? I only ask because on a guitar you **can** sometimes slide a chord position up and down the neck, but you can't do that on a piano. And don't the note names change with the language too, e.g. Do vs C
Comment: @BrianTHOMAS they are written chords like "C   Am   F" etc, so applicable to piano and guitar. About the language, yea I know German swaps B for H, so it wont be perfect, but the aim is the least amount of english knowledge needed
Answer: How about something like ⬆ and ⬇ ? I just did this with emojis to demonstrate. I don't know any standard symbols for transpose.
Answer: I'm not aware of an existing symbol. How about some variation on the following?


Find the mass of a solid bounded by the surfaces (triple integral)

Question:
Find the mass of a solid bounded by the surfaces: $z=4-x$, $z=0$, $y=0$, $y=4$ & $x=0$ with density x at $(x,y,z)$

I'm not sure how to find the limits of integration for $x$.
I know this is a triple integral that is set up like this:
$$\int^?_?\int^{4}_{0}\int^{4-x}_{0}x\;dz\;dy\;dx$$
Hints?
After looking at it further, I assume it would be:
$$\int^4_0\int^{4}_{0}\int^{4-x}_{0}x\;dz\;dy\;dx$$
Answer: You're correct. The volume is just the box [0,4][0,4] bounded above by $z=4-x$.
Another way to think of it is: You are given the $y$ and $z$ bounds, and one of the $x$ bounds. To get the other $x$ bound, plug $z=0$ (lower $z$ bound) in $z=4-x$ and solve for $x$.


How to make a range of points on a graph i n r a different colour

Question: I have made a graph with the year on the x-axis and sea level rise on  the y-axis.
I am trying to make the data from 2025 (predictions) a different colour to that before 2025.
I have grouped and labeled the predicted data using this code and have also included the code for my graph

predictions=data[which(data$Year>2024 & data$Year<2121),]
plot(data$Sea.Level..cm.~data$Year,xlab="Year",ylab="Sea Level (cm)",pch=21,col=c("Blue"))

How do I go from here in making the predictions red but the previous data blue?
Thanks in advance
Comment: Add a command `points(predictions$.., ...., col="red")`. It will add points to the previous `plot`.
Comment: thank you so much
Answer: You can try something like this. Toy data used.
vec <- c( rep(2001,10), rep(2002, 3) )

tf <- (vec < 2002) + 1

barplot( 1:length(vec), vec, col=c("red","blue")[tf], names=vec )

Answer: You can provide a vector of colours to plot in the col argument. For example, following your existing syntax:
predictions <- rep("red", nrow(data))
predictions[which(data$Year>2024 & data$Year<2121)] <- "blue"
plot(data$Sea.Level..cm.~data$Year,xlab="Year",ylab="Sea Level (cm)",pch=21,col=predictions)


Find the asymptotic joint distribution of the MLE of $\alpha, \beta$ and $\sigma^2$

Question: $X_1,\ldots,X_n$ are non-random constants. We observe random variables $Y_i,\ldots,Y_n$
that are independent but not identically distributed
$Y_i\sim N(\alpha+\beta X_i,\sigma^2)$  where $\alpha,\beta$ and $\sigma^2$ are unknown parameters

Question: Find the asymptotic joint distribution of the MLE.

The asymptotic distribution of the MLE estimator should be:
$$\sqrt n (\hat{\theta}-\theta)\sim N(0,\frac{1}{I_{\theta}})$$
and the MLE of $\alpha,\beta$ and $\sigma^2$ should be:
$$\hat{\alpha}=(\bar{y}-\hat{\beta} \bar{X})$$
$$\hat{\beta}=\frac{\sum_i^n(y_i(x-\bar{x}))}{\sum_i^n(x-\bar{x})^2}$$
$$\widehat{\sigma^2}=\frac{\sum_i^n(y_i-\hat{\alpha}-\hat{\beta} x_i)^2)}{n}$$
But how do I calculate the asymptotic joint distribution of the MLE?
Answer: There is a multivariate version of the convergence in distribution that you mentioned.
With parameter $\theta = (\alpha, \beta, \sigma^2)$ and MLE $\hat{\theta} = (\hat{\alpha}, \hat{\beta}, \hat{\sigma^2})$, under certain conditions we have
$$\sqrt{n}(\hat{\theta} - \theta) \overset{d}{\to} N(0, I^{-1})$$
where $I$ is the Fisher information matrix.
Comment: This omits to mention that $\widehat\alpha,\widehat\beta$ are correlated, and does not explain why $\widehat{\sigma^2}$ is independent of $(\widehat\alpha,\widehat\beta). \qquad$


Views UI affected due to multiple modules

Question: jquery.once is perfectly working, I placed console.log inside it, but I still get this error especially when I load the Views UI without even before I press any button
When I press any button, a progress animation appears and again this error appears
views-admin.js?op2hqg:164 Uncaught TypeError: $form.once is not a function
    at Object.Drupal.behaviors.addItemForm.attach (views-admin.js?op2hqg:164)

When I investigates I found that the following jquery select returns 0 objects
var $form = $(context).find('form[id^="views-ui-add-item-form"]').first();

How to solve this, should I disable any modules?
Answer: This might happen when you use jQuery Update, I faced the same and solved using CDN providers
Use jQuery CDN Provider in your jQuery Update Settings should solve this issue
Load your settings as yoursite.com/admin/config/development/jquery_update, You will see the option jQuery and jQuery UI CDN with None in the dropdown list.
Choose jQuery and Save Configuration


SQL insert into, where not exists (select 1... what this "1" stands for?

Question: INSERT INTO table1
SELECT * FROM table2
WHERE NOT EXISTS
    (SELECT 1 FROM table1
    WHERE table2.id = table1.id)

What is the role of that 1 in the forth line of code? I want to make an incremental update of table1 with records from table2. A friendly soul advised me to use the above query, which I find very common on the web in case of incremental update of a table. Can someone please explain how this mechanism works?
Comment: First it checks if the id is found in both tables. If it is TRUE then it returns 1. Then it checks if 1 not exists. Lets assume we have both tables the same. Then the 3rd line would be `WHERE NOT EXISTS 1`. How this line is processed?
Answer: Exists checks for the presence of rows in the sub-select, not for the data returned by those rows.
So we are only interested if there is a row or not.
But as you can't have a select without selecting something, you need to put an expression into the select list.
That could be any expression. The actual expression is of no interest You could use select some_column or select * or select null or select 42 - that would all be the same.
Comment: @PrzemyslawRemin: it does not return `'NOT EXISTS'`, it returns _nothing_ (=no rows) if the value does not exist
Comment: Is it the speediest way for incremental update of a table? My suspicion arises from the fact that probably every row is checked. Since we have a unique sorted key maybe condition like `WHERE table2.id > MAX(table1.id)` would be faster?
Comment: @PrzemyslawRemin: that is a totally different question. If you want to optimize that statement, please ask a **new** question.
Comment: Finally I got the logic. For anyone who wonders on that, it is like this. The subquery in brackets returns either '1' or 'NOT EXISTS'. If it does return 'NOT EXISTS' then it SELECT everything from table2. Thanks to everyone who contributed!
Comment: Is `nothing` the same as `NULL`? Isn't it TRUE for the query NOT EXISTS?
Comment: @PrzemyslawRemin: "no rows at all" is something different that one row containing a `null` value.
Answer: You can select whatever in the case of EXISTS (sub-select, the only thing that matters are if a row is found (EXISTS true), or no rows found (EXISTS false).
Answer: The EXISTS keyword, as the name suggests, is used to determine whether or not any rows exist in a table that meet the specified condition. Since we only need to filter out those rows which meet the condition, but do not need to actually retrieve the values of individual columns, we use select 1 instead. For what it's worth, you can also write it as
INSERT INTO table1
SELECT * FROM table2
WHERE NOT EXISTS
(SELECT id FROM table1
WHERE table2.id = table1.id)

without affecting the filtering logic.


Triangular inequality extended

Question: Let $a,b,c,d,e,f\in\mathbb{R}$ all positive or zero, such that $a\leq c+d$ and $b\leq e+f$ show that:
$$\sqrt{a^2+b^2}\leq\sqrt{c^2+e^2}+\sqrt{d^2+f^2}$$
Some hint or auxiliar inequality that would help? I've done many attempts but write them will take a lot of time, I tried to use the artihmetic and geometric mean, minkowski but no one works (or fits) can you help me?
Answer: Just $$\sqrt{c^2+e^2}+\sqrt{d^2+f^2}\geq\sqrt{(c+d)^2+(e+f)^2}\geq\sqrt{a^2+b^2}$$
If I don't see the triangle inequality I can make the following.
By C-S
$$\sqrt{c^2+e^2}+\sqrt{d^2+f^2}=\sqrt{c^2+e^2+d^2+f^2+2\sqrt{(c^2+e^2)(d^2+f^2)}}\geq$$
$$\geq\sqrt{c^2+e^2+d^2+f^2+2(cd+ef)}=\sqrt{(c+d)^2+(e+f)^2}\geq\sqrt{a^2+b^2}$$
Comment: Sorry if this is a little off topic here, but I see you are very good at solving inequalities and I would like to ask you something. I am 2-3 year math undergraduate student. Do you have any fun books to reccomend on inequalities for somebody with zero experience in inequalities like me?
Comment: @Ovi I think the best book to learn inequalities is the following forum:https://www.artofproblemsolving.com/community/c6t243f6_inequalities  Just read it!
Comment: I've tried to show that $D(x,y)=d_1(x,y)+d_2(x,y)$ with both $d_1$ and $d_2$ metrics, are also a metric
Answer: Denote vectors $X = (a,b), Y_1 = (c,e), Y_2 = (d,f)$. Then we have $X \le Y_1+Y_2$. It follows with $\|X\| \le \|Y_1+Y_2\| \le \|Y_1\|+\|Y_2\|$
Edit
Thanks to the comment from dxiv. Of course, it should be noted that the components of $X$ and $Y_i$ are positive. Otherwise we do not have the implication $\|X\| \le \|Y_1+Y_2\|$ from $X \le Y_1+Y_2$. For example, it is false for $X = (-2,-2), Y_1  = (1,1)~\textrm{and}~Y_2 = (-1,-1)$.
To be more precise on my proof, $X \le Y_1+Y_2$ means only componentwise order on vectors (i.e. partial order). So that each component of $X$ is smaller than the corresponding component of $Y_1+Y_2$.
Why do we have $\|X\| \le \|Y_1+Y_2\|$ in this case? It could be verified by hands from
$$\sqrt{x_1^2+x_2^2} \le \sqrt{y_1^2+y_2^2},$$
for $y_i = \left(Y_1+Y_2\right)_i$ as an implication from componentwise order. It remains then to apply triangle inequality for the Euclidean norm and get
$$\|X\| \le \|Y_1+Y_2\| \le \|Y_1\|+\|Y_2\|$$
Comment: You are using that $(\mathbb{R}^2,||•||)$ are a metric space right?
Comment: @Ragnar1204, in fact $(\mathbb{R}^2,||•||)$
Comment: @Ragnar1204, the inequality is componentwise. It means that each coordinate of one vector is less than of the other.
Comment: @AndreiKulunchakov Maybe you should make that more clear in the answer, since it's not too common a notation ($\le$ is generally used for total order relations, while component-wise inequality is only a partial order). It should also be noted that the conclusion only follows when $0 \le X$.
Comment: Yes, my fault...
Comment: Sorry by my question. But... There's an order in the euclidean plane? Cuz I can't follow the inequality between vectors... Right?

Triangular inequality extended


Send Label result to a file

Question: I have a simple calculator which display the results in a label, I want to export the results to a pdf, email, or text file. Any clue how could I make it?
Thanks in advance.
Answer: Just get the value of your UILabel.text. After that saving it to a file should be pretty easy.
<code>let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
    let dir = dirs[0] //documents directory
    let path = dir.stringByAppendingPathComponent(file);
    let text = myLabel.text

//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
</code>
Copied the code from this answer here.
Comment: Just what I need :) Thank you iosDev82 :)
Comment: @Manolo Glad to be of help. Have a great day. :)

Send Label result to a file


Show that dim$ V$=dim $W$.

Question:
Let $T:V\longrightarrow W$ be a linear transformation, where $V(F)$ and $W(F)$ are finite dimensional vector spaces. Show that dim $V$=dim $W$ iff $T$ is non singular.

A textbook has the following solution:

We know that dim $V$=dim $ R(T)$+dim $N(T)$. Therefore,  dim $V$=dim $ R(T)$=dim $W$. If and only if dim $N(T)=0$, i.e., if and only if $N(T)=\lbrace 0 \rbrace$, i.e. , if and only if $T$ in non singular.

The above proof is very unsatisfactory. How can we write  dim $R(T)$= dim $W$? Converse part is also not clear.
Comment: $T$ nonsingular implies that $T$ is surjective and injective. Hence $\dim R(T)=\dim W$.
Comment: It seems that there is a stop that it should not be. Does "Therefore,  dim $V$=dim $ R(T)$=dim $W$, if and only if dim $N(T)=0$, i.e., if and only if $N(T)=\lbrace 0 \rbrace$, i.e. , if and only if $T$ in non singular." make more sense to you?
Comment: @ajotatxe You have pointed right. That full stop in the textbook made me more confused.
Comment: @Dietrich Burde Thanks, i am not very much familiar with the notion of non singular transformations. Does $T$ being non singular imply that $T$ is invertible?
Comment: @DietrichBurde T non singular means $kerT=(0)$ as per standard definition,for a linear operator i.e. transformation on the same set,it is equivalent to saying bijective.
Answer: The question is wrong,perhaps the term non singular that means $kerT=\{0\}$ should be replaced by the term invertible.For example take the inclusion map $(x,y)\to (x,y,0)$ from $2D$ space to $3D$ space which is nonsingular,but $dim(V)\neq dim(W)$.
Addendum
$Ker(T)=(0)$ iff $T$ is injective.You can easily check $T$ is injective,but $T$ is not surjective.So $T$ is not an isomorphism.You probably know that $T$ is isomorphic means $T$ is bijective linear transformation(definition).
Comment: this problem was taken from a textbook entitled  Linear Algebra by K. P Gupta, page no. 126. To my knowledge, the same problem are also available in some other literatures though i couldn't recall the exact title of the literatures.
Comment: @gete You must see the definition of non singular,I have used standard definition.
Comment: Yes that is true and you seem to have pointed right. However, i am not that good at this topic. So, i couldn't understand how did you claim that your counter example is a non singular map? I am bit unfamiliar with such notation of mappings.
Comment: Let me add something to make you understand,see the edit.
Comment: Got it, but in the text book which i referred, $T$ being non singular seems to imply that $T$ is isomorphism also.
Comment: Then the statement is true,what you wrote.
Comment: @gete See https://math.stackexchange.com/questions/679558/proving-v-is-isomorphic-to-w-iff-dim-v-dim-w

Show that dim$ V$=dim $W$.