Finitary Proofs in Mathematical Logic

Question: I have been reading the famous Joseph Schoenfield's text "Mathematical Logic" and this may sound naïve but I can't make sense of his comments about finitary proofs. Can someone please explain to me what a "finitary" proof is?
To quote from Schoenfield's text:

"Proofs which deal with concrete objects in a constructive manner are
  said to be finitary. Another description, suggested by Kreisel, is
  this: a proof is finitary if we can visualize the proof. Of course
  neither description is very precise;"

What exactly is this supposed to mean? I can't think of a proof in mathematics that deals with concrete objects. All objects that are dealt with in mathematical proofs are abstract in nature. We're not talking about the notion of proof as used in a court room, where the objects in question are actual events and/or tangible evidence.
There is another question here which asks the same thing but the answers don't seem to help me. Instead, the answers suggest that if I can't think of a proof as an object in itself, then the above-quoted paragraph will not make sense. Again, I don't know how I'm supposed to look at a written proof as an "object in itself", and what exactly that is to accomplish.
If this suggests that my experience with proofs is lacking, that's a suggestion I absolutely reject. I hold a Master's of Science degree in pure mathematics and I've seen hundreds of proofs in lectures and textbooks. I know what a proof is, say, in analysis, but I couldn't tell you whether it's finitary according to Schoenfield's notion, or whether I'm looking at a written proof as an "object in itself" and what that is supposed to accomplish. Can someone shed light?
Comment: The [wiki](https://en.wikipedia.org/wiki/Finitary) sheds some light.
Comment: I don't know Schoenfield's book and I can't justify his statements out of context. However, the whole idea behind mathematical logic is to model mathematical proofs and the formulas that appear in them as mathematical objects in their own right (as strings of symbols, or what are called "syntax trees" in computer science) so that we can reason about them. In the vast majority of the literature (but not all), proofs are expected to be finite objects. In that sense, we expect proofs and the syntactic objects in them (not the mathematical abstractions those objects represent) to be very concrete.
Comment: @Rob Arthan:  I totally get the notion of the language of a formal system as a purely syntactical object, with a set of rules that can determine for each expression whether it is a formula. And yes, we formalize the rules of deduction in this formal (syntactical) system so that they apply to all theories, regardless of particular meanings given to them in particular models. When we prove a theorem in Topology, or Analysis, everyone knows the rules of deduction (most of the time) and the syntactical objects you talk about take on particular meanings depending on the theory and model.
Comment: @ Rob Arthan:  What I still don't get is what makes a proof finitary when I look at it, say if I'm looking at a proof of Liouville's Theorem in Analysis.
Comment: The proof of Liouville's theorem involves a finite number of symbols. You'd spot an infinitary proof straight away if one was presented to you.
Comment: @ Rob Arthan:  So what you're saying is that finitary proofs are precisely those that involve a finite number of symbols. If this is what you're saying and if it's true then it's a step forward in answering my question. Infinitary proofs (by which I assume you mean proofs that are NOT finitary?) would be those involving an infinite number of symbols? Can you give me an example of this?
Comment: See [Constructive Mathematics](https://plato.stanford.edu/entries/mathematics-constructive/) and [Hilbert's Program](https://plato.stanford.edu/entries/hilbert-program/).
Comment: See also W.W. Tait, [Remarks on finitism](http://home.uchicago.edu/wwtx/finitism.pdf).
Comment: @marcus66502 As Rob suggested, to discuss proofs in the context of mathematical logic, first we formalize them in some language. Finitary proofs require finitely many symbols of this language and satisfy fairly stringent requirements. They do not quite look like standard proofs in natural language, but the point is that just about any proof in the natural sense of the word "can (at least in theory) be rewritten as one of these formal counterparts. On the other hand, there may be infinitary proofs that do not adhere to these patterns. For instance:
Comment: To be concrete, consider a theory of natural numbers (such as first-order Peano arithmetic). It could be that, working in your favorite (reasonable, decently strong) theory, you can prove of some statement $P(x)$ that $P(0)$ holds, $P(1)$ holds, $P(2)$ holds, etc. These are infinitely many different proofs, one for each natural $n$. However, it may well be that your theory is not strong enough to prove $\forall x\,P(x)$. Nevertheless, if you proved each $P(n)$, it would be reasonable to conclude this sentence as well. An example of an infinitary system allows this $\omega$-rule:
Comment: From the infinitely many statements $P(n)$, $n\in\mathbb N$, it follows that $\forall x\,P(x)$. Proofs with this rule are not quite finitary objects. Of course, it could be that any such proof can be reformatted as a finitary one, but this is in general not the case, at least with our current notion of finitary proof. There are many other possibilities. For instance, the completeness theorem tells us that a statement $\phi$ is provable (in the strict finitary sense) in a theory $T$ if and only if any model of $T$ (in the sense of model theory) is also a model of $\phi$. Ok. Now, ...
Comment: It may well be that one is not interested in *all* models of $T$ but only in certain "well-behaved" ones. We could then introduce a new rule, that says that $\phi$ is "provable" from $T$ if it holds in all well-behaved models of $T$. These are usually infinitary proofs in he sense that do not have any reasonable finitary counterpart. These "proofs" are actually used in practice, by the way. In set theory, for example, many times we only care about so-called transitive models of set theory rather than all models, and there are many properties that hold in all these models but are not ...
Comment: provable in set theory (in the finitary sense). Now, you could object that these are (or at least might be) finitary proofs, only not in set theory but in some variant theory. Sure. But you see how these examples open the door to many other options: Proofs of variable infinite length (say, indexed by ordinals), proofs involving arbitrary collections of models (for which there may not be a reasonable finitary description) and so on.
Comment: (Nice question, by the way.)
Comment: @ Andres E. Caicedo :  Thank you for your comments. They certainly helped elucidate the concept. Since you were talking about proofs in natural languages, I just wanted to add that when we state a proof in a natural language in, say Fourier Analysis, we do so for pure convenience, with the clear understanding that we can rewrite any such proof in a formal language (although first we'd have to agree on the formal language and the logical and nonlogical axioms of the ambient theory). Just like defined symbols are NOT symbols of the formal language. They're symbols added for convenience.
Comment: @ Andres E. Caicedo : …. and any formula written with these defined symbols can be rewritten using only the symbols of the formal language. Anyway my point is that ALL mathematics can be done within formal systems, no matter what the theory is, because we only follow formal rules of deduction. A proof that fails to do so is no proof at all. And so this is what I was trying to get at with my original question, how can we determine when we look at a proof whether it's finitary or not.
Comment: @marcus66502: Rob's wrong about what "finitary" means. It is a philosophical notion that different logicians have different views on. A common view is that any arithmetical statement (i.e. sentence over PA) is finitary, and that any finitary proof can be translated to a proof over ACA. See [this post about ACA](http://math.stackexchange.com/a/1808558/21820).
Answer: The context is the debate about the Foundations of mathematics of the 1930s.
Some lines above, the author says :

An axiom (or theorem) may be viewed in two ways. It may be viewed as a sentence, i.e., as the object which appears on paper when we write down the axiom, or as the meaning of a sentence, i.e., the fact which is expressed by the axiom.

The distinction between "sentence" and its "meaning" is at the core of the well-known Gödel's Incompleteness Theorems :

(under suitable conditions) there are true [this is the "meaning" side] formulas of formal arithmetic that are not provable (from the axioms of the system).

Thus, mathematical logic studies formal systems (the concrete objects) whose meaning are very abstract : number, sets, etc.
The statement :

there is no value in studying concrete (rather than abstract) objects unless we approach them in a concrete or constructive manner. For example, when we wish to prove that a concrete object with a certain property exists, we should actually construct such an object, not merely show that the nonexistence of such an object would lead to a contradiction.

refers to of Hilbert's Program :

In the early 1920s, the German mathematician David Hilbert (1862–1943) put forward a new proposal for the foundation of classical mathematics which has come to be known as Hilbert's Program. It calls for a formalization of all of mathematics in axiomatic form, together with a proof that this axiomatization of mathematics is consistent. The consistency proof itself was to be carried out using only what Hilbert called "finitary" methods.

See also page 3 : "Hilbert, who first instituted this study, felt that only finitary mathematics was immediately justified by our intuition."
In a nutshell, in meta-mathematics [the mathematical study of the properties of "concrete" objects : formal theories], we have to restrict the allowed methods of proof to constructive existence proofs, avoiding non-constructive ones [i.e. existence proofs based on reductio ad absurdum.

Finitary Proofs in Mathematical Logic


Git ignore changes without removing file from repository

Question: We have a few config files in our repository, that need to be configured in a certain way locally to be able to start the application. However, these configurations are not supposed to be pushed into the remote repository. Furthermore, when switching branches, cherry picking etc. these changes should always persist.
An obvious way to achieve this would be to add the files to the .gitignore and remove them from the repository, but we need to have them in the repository - just without our local changes.
This is somewhat possible without any further doing, by stashing and unstashing the changes frequently (e.g. when cherry picking), but that's fairly annoying.
For example: We have a C# project with an app.config, in which we have placeholders for the properties (e.g. $SECURITY_PROTOCOL_TYPE$) that is replaced upon installation. However, for testing etc. we don't install the application, we just start it - but therefore (locally) $SECURITY_PROTOCOL_TYPE$ has to be replaced with TLS12. When we cherry pick however, these local changes need to be stashed and unstashed, which is annoying. Furthermore, sometimes it happens that someone accidently commits & pushes those config files, which is just as annoying to fix.
The problem gets even more complicated, because sometimes we do need to make changes to those config files that need to be checked in - without our local configurations of course.
The only idea I have for solving this situation is to somehow use a hook that replaces the configs with the placeholders upon commit (and the other way round upon merge), but that'd be kind of awkward too.
Is there an elegant way of solving this with git?
Just to avoid misunderstandings: I don't want to know that the way our repository is set up is bad or anything like that, I just want a solution to this problem: I somehow need to lock files for git, so that git pretends they didn't change, unless I explicitly say so.
Comment: To instruct git to ignore changes in a tracked file, try `git update-index --assume-unchanged $path`, and `--no-assume-unchanged` to cancel the effect. To avoid stash/unstash for cherrypick, merge or rebase, there could be some methods to manipulate the index without touching the files in the working tree. To avoid committing sensitive content, try the clean filter, https://git-scm.com/docs/gitattributes#_filter. You can use `sed` or write your own script, in which it  reads contents from stdin and writes updated contents to stdout.
Comment: All Git solutions to this setup are inelegant. You already know that Git doesn't "like" this kind of setup, so no point mentioning that again. :-) The least-inelegant of the inelegant solutions is the skip-worktree method in Kaus Untwale's answer. Note that you can use either skip-worktree or assume-unchanged, but each has a different *intended* purpose in Git, and this isn't either of those.
Answer: I run into this all the time. I achieved this by adding three shortcuts to my global git config.
alias.ignore=update-index --skip-worktree
alias.unignore=update-index --no-skip-worktree
alias.ignored=!git ls-files -v | grep "^S"

Now when I want to ignore a file I just run:
$git ignore <file-path>

Conversely if I want to include it:
$git unignore <file-path>

Third command just lists the currently ignored files
$git ignored

Comment: No I sometimes get the message `error: Your local changes to the following files would be overwritten by checkout:` for some of the ignored files when trying to switch branches.
Comment: @MetaColon This happens when you try to switch to a base branch that does not have the ignored changes from a temporary branch which has the ignored files. To resolve this, first unignore the files then run `git stash` then switch your branch. Now you can run `git stash apply` to bring the changes back and ignore the files again. Going forward, from this base branch, any new branch you create will carry over the ignore changes with it.
Comment: This is exactly what I needed! Thanks! Here is the 1liner to add these to a gitconfig: `git config --global alias.ignore 'update-index --skip-worktree' && git config --global alias.unignore 'update-index --no-skip-worktree' && git config --global alias.ignored '!git ls-files -v | grep "^S"'`


The correct way to change the name of the language in the language switch

Question: I try to change the name of language in language switcher from Chinese, Simplified(简体中文) to 中文. Changing name in admin/config/regional/language/edit/zh-hans affects only English. So the language switcher looks like this:

en/Chinese, Simplified(简体中文)

I created a function, but on some pages (e.g. node/1), it causes errors.
function theme_preprocess_block(&$variables) {
   $variables['content']['#links']['zh-hans']['title'] = '中文';
}

The error I get is the following one.

Fatal error: Call to a member function getText() on array in /var/www/mysite/core/includes/theme.inc on line 1697

How can I fix this?
Answer: Check, if the variable is set, to avoid the error:
function theme_preprocess_block(&$variables) {
  if (isset($variables['content']['#links']['zh-hans']['title'])) {
    $variables['content']['#links']['zh-hans']['title'] = '中文';
  }
}

Comment: Of course, I changed. I described it in 2 nd line
Comment: Did you use admin/config/regional/language/edit/zh-hans/**translate**?
Comment: I tryed `/admin/config/regional/language/edit/en/translate` and `/admin/config/regional/language/edit/zh-hans/translate`
Comment: OK, if this does not help, then you need the preprocess. You only have to check, if the variable is set, to avoid the error. I change my answer.
Comment: thanx, a tryed this, errors doesn't appear until now
Answer: Use this code for language switcher block with Language Icons module:
function THEMENAME_preprocess_block(&$variables) {
  if (isset($variables['content']['#links']['zh-hans']['title'])) {
    $variables['content']['#links']['zh-hans']['title']['#text'] = '中文';
    $variables['content']['#links']['zh-hans']['title']['#title'] = '中文';
  }
}

It just replaces language name and saves country flag. Insert this code in .theme file of your theme and change THEMENAME with name of your theme.


jQuery - extract class name that 'starts with' prefix

Question: My items have the following classes:

I'm wondering if there is an easy way to:

Grab only all classes with some-class- prefix.
Remove them from each element.
Have their names (not corresponding DOM elements) in a variable?

I can easily select such elements with jQuery( "div[class^='some-class-'], div[class*=' some-class-']" ) but how its class name could be extracted with the shortest and the most readable code to a variable (can be some global object)?
Comment: See answers to: [Get Class List for Element with jQuery](http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery).
Comment: @Trylks Great! That actually solves my problem with even better method! Thanks! (however, it's a long way to extract this name)
Answer: Like this?
var arrClasses = [];
$("div[class*='some-class-']").removeClass(function () { // Select the element divs which has class that starts with some-class-
    var className = this.className.match(/some-class-\d+/); //get a match to match the pattern some-class-somenumber and extract that classname
    if (className) {
        arrClasses.push(className[0]); //if it is the one then push it to array
        return className[0]; //return it for removal
    }
});
console.log(arrClasses);

Fiddle
.removeClass() accepts a callback function to do some operation and return the className to be removed, if nothing to be removed return nothing.
Comment: Worked great! Clean and elegant!
Comment: Genius solution.
Answer: You could loop through all the elements, pull the class name using a regular expression, and store them in an array:

var classNames = [];
$('div[class*="some-class-"]').each(function(i, el){
    var name = (el.className.match(/(^|\s)(some\-class\-[^\s]*)/) || [,,''])[2];
    if(name){
        classNames.push(name);
        $(el).removeClass(name);
    }
});
console.log(classNames);

Comment: Demo is a dead link
Comment: @VulgoAlias The link was not dead, but I've moved the code from it into the answer anyway :)
Answer: You can iterate over each found node and iterate over the classes to find a match; if found, remove the class and log it:
var found = [];

$('div[class*="some-class-"]').each(function() {
  var classes = this.className.split(/\s+/),
  $this = $(this);

  $.each(classes, function(i, name) {
      if (name.indexOf('some-class-') === 0) {
          $this.removeClass(name);
          found.push(name);
      }
  });
});

Note that a selector like div[class*="some-class-"] is pretty expensive and since you need to perform extra processing anyway, it would be easier to just iterate over all div tags and process them:
var elements = document.getElementsByTagName('div'),
found = [];

$.each(elements, function(i, element) {
    var classes = element.className.split(/\s+/);

    $.each(classes, function(i, name) {
        if (name.indexOf('some-class-') === 0) {
            $(element).removeClass(name);
            found.push(name);
        }
    });
});

Modern browsers expose Element.classList which you can use to manipulate class names and Array.forEach for iteration:
var found = [];

[].forEach.call(document.getElementsByTagName('div'), function(element) {
    (function(names, i) {
        while (i < names.length) {
            var name = names[i];
            if (name.indexOf('some-class-') === 0) {
                names.remove(name);
                found.push(name);
            } else {
                ++i;
            }
        }
    }(element.classList, 0));
});

Answer: The easy way
You clould create your own filter :
$.fn.hasClassStartsWith = function(className) {
    return this.filter('[class^=\''+className+'\'], [class*=\''+className+'\']');
}

var divs = $('div').hasClassStartsWith("some-class-");
console.log(divs.get());

See fiddle


The functional equation $f(xy)=f(x)+f(y)+\frac{x+y-1}{xy}$ with a hint of differentiability

Question: Okay so I got this question in a rehearsal test today, and got completely stumped.
Let $f$ be a differentiable function satisfying the functional rule $f(xy)=f(x)+f(y)+\frac{x+y-1}{xy}$, $\forall$ $x,y>0$ and $f'(1)=2$.The question asked some more questions regarding $f(x)$,but I am unable to find $f(x)$.
My try:I tried to treat $y$ as a constant and then differentiated both sides of the equation,making use of the fact that $f'(1)=2$ ; but that got me nowhere.Someone kindly help.
Thanks in advance.
Comment: try substituting y=1/x and the differentiate
Comment: How does that help ?
Answer: Your try gives
$$yf'(xy) = f'(x) -\frac{1}{x^2} + \frac{1}{x^2y},\tag{1}$$
for all $x,y > 0$. Choosing $x = 1$ in $(1)$, we obtain
$$yf'(y) = 2 - 1 + \frac{1}{y},$$
or
$$f'(y) = \frac{1}{y} + \frac{1}{y^2}.\tag{2}$$
From that, we can easily determine $f$ up to addition of a constant, and we can determine the constant from the rule e.g. by setting $x = y = 1$ there.
An alternative way to find the function is to rewrite the functional equation as
$$f(xy) + \frac{1}{xy} = \biggl(f(x) + \frac{1}{x}\biggr) + \biggl(f(y) + \frac{1}{y}\biggr),$$
and if one knows the continuous functions satisfying the functional equation $g(xy) = g(x) + g(y)$, $f$ is easily determined.
Comment: Sorry , Thanks for your effort into this , but like a noob I am ,Im not getting anything.How do i get $f(x)$ from this ? And how do I tackle similar problems?Isnt there a thumb rule?
Comment: We have a nice form for the derivative of $f$. One can read the primitives of $f'$ off that if one knows the derivatives of the most famous functions. If $g'(y) = y^{\alpha}$, what is $g(y)$?
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\mrm{f}}$ is differentiable.
  $\ds{\mrm{f}\pars{xy} = \,\mrm{f}\pars{x} + \,\mrm{f}\pars{y} + {1 \over y} +
{1 \over x} - {1 \over xy}\,,\quad
x, y \in \mathbb{R}_{\ >\ 0}\quad\mbox{and}\quad\mrm{f}'\pars{1} = 2}$.

$$
\bbx{\quad\mbox{Note that}\quad\mrm{f}\pars{1} = -1\quad
\pars{~\mbox{from the 'original functional equation'}~}\quad}
$$

Derive both members, of the above functional equation, respect of $\ds{x}$:
\begin{equation}
\mrm{f}'\pars{xy}y =
\,\mrm{f}'\pars{x} - {1 \over x^{2}} + {1 \over x^{2}y}
\implies
\mrm{f}'\pars{xy}xy =
\,\mrm{f}'\pars{x}x - {1 \over x} + {1 \over xy}
\label{1}\tag{1}
\end{equation}
Derive both members, of the above functional equation, respect of $\ds{y}$:
\begin{equation}
\mrm{f}'\pars{xy}x =
\,\mrm{f}'\pars{y} - {1 \over y^{2}} + {1 \over xy^{2}}
\implies
\mrm{f}'\pars{xy}xy =
\,\mrm{f}'\pars{y}y - {1 \over y} + {1 \over xy}
\label{2}\tag{2}
\end{equation}
\eqref{1} and \eqref{2} lead to:
\begin{align}
&\,\mrm{f}'\pars{x}x - {1 \over x} = \,\mrm{f}'\pars{y}y - {1 \over y} = \alpha\,,
\qquad\pars{~\alpha:\ \mbox{a}\ x\ \mbox{and}\ y\ \mbox{independent constant}~}
\end{align}

$\ds{\alpha = \,\mrm{f}'\pars{1} \times 1 - {1 \over 1} = 1}$.

Now, you are left with
$$
\,\mrm{f}'\pars{x} = {1 \over x} + {1 \over x^{2}}\,,\quad\mrm{f}\pars{1} = -1
\implies \bbox[#ffe,10px,border:1px dotted navy]{\ds{\mrm{f}\pars{x} = \ln\pars{x} - {1 \over x}}}
$$


Changing Page Title of Access Denied Page

Question: I have an odd request that appears to only be "solved" (aka not really) through changing the includes/common.inc file.
The instructions are something like...

1 Go to INCLUDES Folder
  2. and make a copy of the file common.inc
  3. use copy to make change.
  4. edit the file with a text editor (not WORDPAD)
  5. and go to "function drupal_access_denied()"
  6. go to the 3th "IF" instruction
and if you want change the TITLE of the "ACCESS DENIED" page
change default (t('Access denied')) to something like: (t('Welcome
  Visitor'))

Obviously it's a stupid and wasteful move to just go through changing a core file, so I was wondering... another answer mentioned adding something to the theme template.php file or the local.module file. If I wanted to change just the text for the page title of the default "Access Denied" references, how would I go about doing that without going into editing the core files?
And due to an odd way a module around the site was built, the custom 404 page idea just won't work, which is why I need the workaround the way I described it.
Thanks ahead of time!
Matt
Answer: In Drupal 7 You can use GUI.

Step 1:  First create a page and add whatever message you want.
Step 2:  Customize the page alias as you see fit. Copy that URL.
Step 3:  Go to admin/config/system/site-information and then go to
the field    set for "Error Pages" and put in your custom page alias
for the 403    page.


Another version of PP

Question: Prove the following version of the pigeonhole principle. Let $m$ and $n$ be
positive integers. If $m$ objects are distributed in some way among $n$ containers,
then at least one container must hold at least $1 + \left\lfloor\frac {m − 1}{n}\right\rfloor$
objects.
Comment: Setting $m=4; n=2$ we have that one of the two containers must hold $1+\frac{4-1}2=1+\frac32=2\frac12$ objects. But what is $\frac12$ an object? And why can't I just put two objects in each container? Last I checked, two pints of beer were less than two pints and half a pint of beer.
Comment: Did you perhaps mean $$\left\lfloor 1+\frac{m-1}{n}\right\rfloor$$ instead? (That may also be false, but it avoids the problem that Asaf pointed out.)
Comment: Cameron's version is correct, and the original post (before editing) did in fact have brackets indicating the floor function. Unfortunately someone saw fit to delete them.
Comment: I believe you can do it by using a generalized PP, If more than mn+1 objects are distributed among n boxes, then at least one box has at least m+1 objects.
Comment: As for the proof, it's easy to do by contradiction. Have you tried that?
Answer: HINT: Suppose that each container holds at most $\left\lfloor\dfrac{m-1}n\right\rfloor$ objects. Then it's certainly true that each container holds at most $\dfrac{m-1}n$ objects. (Why?) What does that tell you about the maximum possible total number of objects in all $n$ containers?

Another version of PP


how to align tableview column to the largest value text value in adjecent column

Question: I apologise if this is a duplicate question but I cant seem to find anything relevant on here.
My problem is that I have a TableView:

Is it possible to align the second column to that of the longest string value in the first one?
EDIT* The layout design code
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Actvities.AddItemActivity">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TableRow>

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:paddingTop="16dp"
                android:text="Overview"
                android:textColor="#ff9933" />

            <EditText
                android:id="@+id/edit_item_name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="Item Name"
                android:inputType="textCapWords"
                android:textAppearance="?android:textAppearanceSmall" />
        </TableRow>

        <TableRow>

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:paddingTop="16dp"
                android:text="Image"
                android:textColor="#ff9933" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/image"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:scaleType="fitCenter" />

                <ImageView
                    android:id="@+id/retake_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@id/image"

                    android:adjustViewBounds="true"
                    android:paddingTop="12dp"
                    android:scaleType="fitXY"
                    android:src="@drawable/ic_add_a_photo_black_24dp" />
            </LinearLayout>

        </TableRow>

        <TableRow>

            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:paddingTop="16dp"
                android:text="Quantity"
                android:textColor="#ff9933" />

            <EditText
                android:id="@+id/edit_quantity"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:hint="Number of units"
                android:inputType="number"
                android:textAppearance="?android:textAppearanceSmall" />

        </TableRow>

        <TableRow>
            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:paddingTop="16dp"
                android:text="Price"
                android:textColor="#ff9933" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <EditText
                        android:id="@+id/edit_price"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="Price"
                        android:inputType="numberDecimal"
                        android:paddingLeft="12dp"
                        android:textAppearance="?android:textAppearanceSmall" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:paddingRight="16dp"
                        android:paddingTop="10dp"
                        android:text="$" />
                </RelativeLayout>
            </LinearLayout>
        </TableRow>

        <TableRow>

            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:paddingTop="16dp"
                android:text="Supplier"
                android:textColor="#ff9933" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/edit_supplier"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Supplier Name"
                    android:inputType="text"
                    android:textAppearance="?android:textAppearanceSmall" />

            </LinearLayout>
        </TableRow>

            <TextView
                android:layout_marginLeft="24dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="24dp"
                android:text="*date will be saved when adding item"
                android:textSize="12sp" />
    </TableLayout>
</ScrollView>

Comment: Share you layout code .
Comment: Added the layout code.
Answer: if i get your question clearly , then you need to increase the size of the ExitText view so that you can write large string.
you need to change the android:layout_weight="1" to android:layout_weight="2" . The number actually represent the percentage(weight) of the View. like :
<EditText
    android:id="@+id/edit_quantity"
    android:layout_width="0dp"
    android:layout_weight="2"
    android:layout_height="wrap_content"
    android:hint="Number of units"
    android:inputType="number"
    android:textAppearance="?android:textAppearanceSmall" />

Comment: Thank you very much! I completely missed that!


What is a real world phenomena that exhibits a projective plane topology?

Question: The earth's orbit around the sun exhibits a torus topology with the revolution as one axis and rotaion around earths axis as the other. But I cannot think of any examples where the topology is a projective plane. Does anyone have a good real world example?
Comment: What do you mean by "real world phenomena"? The projective plane is nonorientable, so it can't be embedded into 3-d space (see https://math.stackexchange.com/questions/2745135/how-to-visualize-the-real-projective-plane-mathbb-rp2-in-three-dimensions-i). On the other hand, if you think of objects doing something in Euclidian space, the objects you tend to think of (like a planet orbiting in space) tend to be implicitly embedded. Probably the projective plane can appear as embedded in spacetime as a 4d manifold, but that won't be visualisable anyway.
Comment: What I mean by real world phenomena is some phenomena that is easily relatable to layman that exhibits a configuration space that is a projective plane. It doesn't have to be physical objects embedded in 3D space. The earth's rotation around the sun is not actually a  torus but its configuration space has a torus topology.
Comment: Would you count the set of straight lines through a given point in space as a "real world phenomenon"? That's often taken as the *definition* of the projective plane.
Comment: I really don't get it when people want someone to precisely define something that is not mathematical or purely logic. You kill CREATIVITY, because CREATIVITY does not have a precise mathematical definition!!!
Comment: That is exactly what I wasnt looking for. Haha Abstract and geometric examples are common but remain elusive to the layman…
Comment: You need to define *layman*
Comment: What I mean by layman is normal people who are not math or physics majors.
Answer: A version of this question came up awhile ago on MathOverflow and there was a great answer given there: the configuration space of a nematic liquid crystal is $\mathbb{RP}^2$, because a nematic liquid crystal is basically a rod. This is relevant to classifying what are called topological defects of materials made out of nematic liquid crystals. You can check out the link for more details and some nice pictures.


How to choose the alias used in a menu

Question: I'm having a bit of a problem when using multiple aliases regarding which alias appears on a menu.
For example, I have create a page /node/1, give it an alias /page1 and add it into the navigation menu.
Browsing to the index page I can see the page in the navigation at /page1.
I also want the page to be available at another alias /page2 so I add this through the URL aliases functionality. Unfortunately this updates my menu so the link in the menu now points to the URL /page2 instead of /page1.
If I have multiple aliases to a node, how does Drupal decide which is used in a menu and how can I change this
Answer: When multiple aliases are available, Drupal uses the most recently created (as determined by the pid column in the url_alias table).
I don't know an easy way to change this behavior.  You could try manually altering the pid value in the database.  Also consider if using a redirect is a better solution than aliasing.
Comment: This helps. So if you want your *original* alias to keep on being the main alias, delete it first. Add your alternative aliases. Then add your original alias again (fe by editing the node and changing it there). Clear your menu cache et voila. Tried this.
Answer: When I faced the same problem, the only I solution I found was to use absolute (starting from http://) menu paths (i.e www.example.com/page-1), which are stored in Drupal's menu system as is, not as internal paths
Answer: To avoid these multiple aliases issue, you can directly give the node/[nid] path in menu items which will be static always.
Comment: If you want to add a link to your website, do it in the "About" section of your profile, not in questions/answers.  Please read the [FAQ](http://drupal.stackexchange.com/faq)
Comment: This is wrong and should be downvoted! Drupal ALWAYS stores the internal path in the menu, even if you provide an alias it will still store node/nid
Answer: You could use :Nodesymlinks. The answer of @Valery Lourie also is looking valid.

How to choose the alias used in a menu


More about Weierstrass theorem

Question: I just fix the previous question, but now I have another one
$\text{Let }f:[0,1]\to \Bbb R\text{ be a continuous function}$
Evaluate the function
$$\lim_{n\to \infty}n\int_{0}^{1}x^nf(x)\,dx$$
My idea is to do just like what I've done in the previous question, only to multiply $n$ in the integral, becomes
$$
\begin{align}
0\le n\int_{0}^{1}x^n\,|f(x)|\,dx & \le n\int_{0}^{1}x^n|f(x)-p(x)|\,dx+n\int_{0}^{1}x^n|p(x)|\,dx\\
& \le n\int_{0}^{1}x^n|f(x)-p(x)|\,dx+n\int_{0}^{1}x^n\sum_{i=0}^{m}\lvert a_ix^i\rvert\,dx
\end{align}
$$
and $$n\int_{0}^{1}x^np(x)\,dx=\frac{na_0}{n+1}+\frac{na_1}{n+2}+\frac{na_2}{n+3}+\cdots+\frac{na_m}{n+m+1}
 \to p(1)$$
as $n\to\infty$.
But I stuck because first, I'm doing $|f(x)|$ not $f(x)$
and second, I just know it's upper bound, and I can't use pinching because the lower bound is $0$
I want to compute its lower bound but how?
Comment: @VitoChou You have just proved a $\limsup$ statement, not worked out the limit.
Comment: Weren't you **already** given *how* to evaluate that limit?? Why are you asking about it again and using a big, and unnecessary, cannon as Weierstrass' Approximation Theorem... **again** ?
Comment: @VitoChou you don't need to know what $M$ is, you just need to know that such an $M$ exists.
Comment: @VitoChou In your approach, you don't "know what $p(x)$ is" by the exact same token
Comment: because I don't know how to use that method.
Comment: f is boounded by M and nM/n+1 -> M as n is big, but I don't know what M is.
Comment: @Omnomnomnom the existence of $M$ here does not give anything useful - only that if the limit exists, then it is bounded by $M$.
Comment: uh, the previous one $\left|\int_0^1 x^nf(x)\,dx\right|\le\int_0^1 x^n|f(x)|dx\le M\int_0^1x^ndx=\frac M{n+1}\xrightarrow[n\to\infty]{}0$

but now become$\left|n\int_0^1 x^nf(x)\,dx\right|\le n\int_0^1 x^n|f(x)|dx\le Mn\int_0^1x^ndx=\frac {nM}{n+1}\xrightarrow[n\to\infty]{}M$
Comment: @TZakrevskiy I had misread, I thought it was the same question as last time
Comment: @Frank hence "I want to compute its lower bound but how?"
Comment: @Omnomnomnom he proves an upper bound
Comment: I also read exactly the same limit as in the other question before, so either that was typo corrected later, or else I misread...
Comment: @frank ,I don't really need worked out that? did I misunderstanding the problem...
Comment: @VitoChou I'm not sure what's going on in these comments, but I hope my answer below helps you.
Answer: Let us suppose that in addition $f$ is $C^1$. We already know (your previous question) that $\lim_{n\to\infty}\int_0^1x^nf(x)dx=0$, therefore we can study $$\int_0^1(n+1)x^nf(x)dx$$instead.
We integrate by parts to obtain
$$x^{n+1}f(x)\big|_{x=0}^{x=1} - \int_0^1 x^{n+1}f'(x)dx \to f(1)\quad \text{as}\quad n\to\infty$$
by your previous question.
Now in the case where $f$ is not necessarily differentiable, we can find a $C^1$ uniform approximation (use Weierstrass-Stone theorem if you want):
$$\forall \varepsilon>0\exists g\in C^1[0,1]\quad \text{such that}\quad \|f-g\|_\infty<\varepsilon.$$ Moreover, we can choose $g$ such that $g(1)=f(1)$.
Therefore $$ n\int_0^1x^nf(x)dx= \int_0^1nx^n(f(x)-g(x))dx + \int_0^1nx^n g(x)dx.$$
The first term can be made arbitrarily small by a choice of $g$:
$$\int_0^1|nx^n(f(x)-g(x))|dx\le \varepsilon \int_0^1nx^n = \varepsilon \frac{n}{n+1}$$
and the second one converges to $g(1)=f(1)$ by the first part of this answer.
Therefore, we can conclude that
$$\lim_{n\to\infty}n\int_0^1x^nf(x)dx=f(1).$$
Comment: I just has the idea but don't know how to write it down, thank you
Answer: Define
$$
\psi_n(x)=(n+1)x^n
$$
We have that $\psi_n(x)\ge0$ and $\int_0^1\psi_n(x)\,\mathrm{d}x=1$. Furthermore, on $[0,1-\delta]$
$$
\|\psi_n(x)\|_\infty\le(n+1)(1-\delta)^n
$$
and, for any $0\lt\delta\lt1$, $\lim\limits_{n\to\infty}(n+1)(1-\delta)^n=0$.
Since $f$ is continuous, given $\epsilon\gt0$, there is a $0\lt\delta\lt1$ so that for all $1-\delta\le x\le1$, we have $|f(x)-f(1)|\le\epsilon$.
$$
\begin{align}
\left|\,\int_0^1\psi_n(x)f(x)\,\mathrm{d}x-f(1)\,\right|
&=\left|\,\int_0^1\psi_n(x)(f(x)-f(1))\,\mathrm{d}x\,\right|\\
&\le\int_0^1\psi_n(x)\left|f(x)-f(1)\right|\,\mathrm{d}x\\
&=\int_0^{1-\delta}\color{#C00000}{\psi_n(x)}\color{#00A000}{\left|f(x)-f(1)\right|}\,\mathrm{d}x\\
&+\int_{1-\delta}^1\color{#0000F0}{\psi_n(x)}\color{#C08000}{\left|f(x)-f(1)\right|}\,\mathrm{d}x\\[9pt]
&\le\color{#C00000}{(n+1)(1-\delta)^n}\color{#00A000}{(\|f\|_1+|f(1)|)}\\[12pt]
&+\color{#0000F0}{1}\cdot\color{#C08000}{\epsilon}
\end{align}
$$
Thus,
$$
\lim_{n\to\infty}\left|\,\int_0^1\psi_n(x)f(x)\,\mathrm{d}x-f(1)\,\right|\le\epsilon
$$
and since $\epsilon\gt0$ was arbitrary, we have
$$
\lim_{n\to\infty}\left|\,\int_0^1\psi_n(x)f(x)\,\mathrm{d}x-f(1)\,\right|=0
$$
Therefore,
$$
\begin{align}
\lim_{n\to\infty}\int_0^1nx^nf(x)\,\mathrm{d}x
&=\lim_{n\to\infty}\frac{n}{n+1}\int_0^1\psi_n(x)f(x)\,\mathrm{d}x\\[6pt]
&=f(1)
\end{align}
$$
Answer: You can approximate any such $f$ by a continuously differentiable function. For such a function it is easy to prove using integration by parts:
$$n\int_0^1 x^n f(x) dx = \frac{n}{n+1} x^{n+1}f(x) \bigg{\vert}_0^1 - \frac{n}{n+1} \int_0^1 x^{n+1} f(x)dx. $$
The first term goes to $f(1)$. The second one goes to $0$ by your previous question.
I was going to use an $L^2$ approximation $g$ to $f$, so that $g \in C^2$ and $||f-g||_{L^2}< \epsilon$, and such that $g(1)=f(1)$. Then I can write
$$\bigg{\vert} n\int x^n(f(x)-g(x)dx \bigg{\vert} \leq \epsilon n \bigg{\vert}\int x^{2n} dx \bigg{\vert} \leq \epsilon \frac{n}{2n+1.}$$
Comment: So if $f_k$ is the $k$th approximation (i.e. $f_k \to f$ uniformly with $f_k$ smooth), you'll have that the limit we want to compute is equal to
$$
\lim_{n \to \infty} \lim_{k \to \infty} n \int_0^1 x^n f_k(x) \,dx
$$
how do you justify an interchange of these limits?
Comment: oh I forget the integration by part....
Comment: @Omnomnomnom There is no such problem. I was about to add to my answer, by the other answer beat me to it.
Comment: @Frank Shouldn't the last integrand in the first equation be $x^{n+1}f'(x)dx$

More about Weierstrass theorem


Decorator with arguments

Question: def Decorator(*pos, **kwargs):
    def innerFunc(arg, num):
        arg()
        print('Inner function')
        print(kwargs['name'])
    return innerFunc

@Decorator(name = 'Michael')
def inputFunc():
    print('Input Function')

Why does applying the Decorator to inputFunc automatically call it?
I would like to pass in some arguments to the decorated function but cannot because the Decorator already calls it
Comment: That's just the way Python decorators work, if you want to pass arguments, you need to add a 2nd wrapper between `inner_func` and `decorator`, call it `outer_func`. Google around and you'll find it.
Comment: `@decorator def f(): ...` is equivalent to `def f(): ...` and then `f = decorator(f)`, so that's why the `decorator` function is called immediately.
Comment: It doesnt call the innerFunc when i dont pass in arguments to the decorator
Answer: In your example, remove the arg() call:
def Decorator(*pos, **kwargs):
    def innerFunc(arg, num):
        # arg()  <-- this is calling the function
        print('Inner function')
        print(kwargs['name'])
    return innerFunc

@Decorator(name = 'Michael')
def inputFunc():
    print('Input Function')

Comment: This isn't really right; if you run the OP's code, it gives a `TypeError` on calling `innerFunc` so `arg` never actually gets called. This also isn't a correct way to write a decorator which takes arguments, and if you don't use `arg` then it's not really a proper decorator at all. You need two levels of nested functions, one returning a decorator, which returns a wrapped function.
Comment: But your answer doesn't answer it; the OP's code never actually calls `arg` because there is a `TypeError` first. Your code raises the same `TypeError` for the same reason. The OP's code calls `innerFunc`, and your answer doesn't explain why.
Comment: I answered to the "Why does applying the Decorator to inputFunc automatically call it?" question. You are right, this is not a good example nor the good way to create a decorator.

Decorator with arguments


Drop zeroes from xarray DataArray

Question: I have a DataArray with three coordinates and I wanted to drop arrays containing all zeroes from one of the dimensions, but I can't seem to get it right. The data array (old_array) looks as follows, and as you can see there are quite a few arrays that are filled with zeroes.
<xarray.DataArray (dim1: 100, dim2: 100, dim3: 100)>
array([[[81.20, 13.20, 12.24, ..., 81.24,
         14.61, 85.58],
        [31.34, 83.96, 02.97, ..., 46.88,
         01.81, 48.24],
        [43.54, 12.50, 35.33, ..., 39.23,
         91.93, 01.21],
        [37.95, 75.59, 71.00, ..., 15.14,
         68.76, 44.56],
        [54.31, 48.99, 85.59, ..., 15.58,
         86.48, 81.19]],

       [[ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
...
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ]],

       [[ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ],
        [ 0.  ,  0.  ,  0.  , ...,  0.  ,
          0.  ,  0.  ]]])
Coordinates:
  * dim1  (dim1) <U7 'x0 y0 z0' 'x1 y0 z0' 'x2 y0 z0' ... 'x10 y10 z8' 'x10 y10 z9' 'x10 y10 z10'
  * dim2  (dim2) float64 0.0 0.1 0.2 ... 9.8 9.9 10.0
  * dim3  (dim3) float64 0.5 1.0 1.5 ... 49.0 49.5 50.0

I tried
new_array = old_array.drop_sel(dim1 = np.zeros(100))

But it gives me KeyError: "not all values found in index 'dim1'"
I also tried
new_array = old_array.drop(np.zeros(100), dim1)

But then I have a ValueError: dimension 'x1 y5 z3' does not have coordinate labels.
I wanted to tell xarray "If 'x2 y3 z7' is an array with all zeroes, then delete it", but I don't know how to do it.
Comment: You'll need to provide more information to get useful feedback here. Can you provide a complete example that reproduces your problem?
Answer: Its still a little hard to tell what you are trying to do but from what I can tell, you want to drop parts of the array that are equal to zero. For that you should use DataArray.where with drop=True:
old_array.where(old_array > 0, drop=True)

drop_sel is used to drop index labels based on their value.

Drop zeroes from xarray DataArray


Get text with jQuery

Question: I have this code
<input type="checkbox"/>
Foobar
<input type="radio" checked="checked">Foo
<input type="radio">Bar

How to get the text Foo with jQuery where $(this) is the node <input type="checkbox"/>?
I can get the <input type="radio" checked="checked"> with $(this).parent().find(":checked").not($(this)) but I don't know how to have the text.
Comment: I agree - I stand corrected http://www.w3.org/TR/html401/interact/forms.html#h-17.4, specifically that `End tag: forbidden`
Comment: This isn't correctly formed HTML so you might have trouble
Comment: @m.edmondson: What isn't correct in the HTML?
Comment: The  aren't closed they should be ``Foo or `Foo` or am I mistaken?
Comment: @m.edmondson: The first example in your comment is only required  for XHTML validation. The second isn't actually valid HTML.
Comment: But it is correct they should be closed?
Comment: Using [label](https://developer.mozilla.org/en/HTML/Element/label) tags together with your inputs will improve usability as well as making it easier to find the text associated with a particular input.
Comment: @m.edmondson: No. Closing it with `` is only an XHTML validation consideration. Closing it with `text` is invalid altogether. Doing `` is perfectly valid HTML, but won't be accepted by XHTML validators.
Comment: @m.edmondson : I copy the code from Firefox with Firebug (right click > copy innerHTML), it didn't put the `slash`.
@mblase75 : I will use the label tag
Answer: Once you get to the target element...

use [0] to get the DOM element at the first index from the jQuery object,
use nextSibling to get the text node,
use data to extract the text content.

var txt = $(this).next().next()[0].nextSibling.data

or
var txt = $(this).nextAll(':radio')[0].nextSibling.data

Comment: Ahaha, again. Was just typing this ;)
Comment: I want the text of the checked radio button so I change `:radio` by `:checked` `$(this).nextAll(':checked')[0].nextSibling.data`
Thanks
Answer: It looks like .val() might work (API Reference).
$(this).parent().find(":checked").not($(this)).val()

Get text with jQuery


RewriteRule Not Rewriting URL properly

Question: I have the following virtual host file:
<IfModule !wsgi_module>
  LoadModule wsgi_module modules/mod_wsgi.so
  WSGISocketPrefix run/wsgi
</IfModule>

<VirtualHost *:80>
  RewriteEngine On
  RewriteLog "/var/log/httpd/rewrite_log"
  RewriteLogLevel 1
  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,NE,L]
</VirtualHost>

<VirtualHost *:443>
  ServerName https://tendril-api.dev.adnxs.net
  ServerAlias 06.tendril-api.dev.nym2.adnexus.net/api

  RewriteEngine  on
  RewriteRule    ^docs$  docs/  [R]
  ...
  # SSL & WSGI Setup
</VirtualHost>

For some reason, My docs Rewrite rule isn't taking effect at all. Why is this? My HTTP-->HTTPS rewrite rule in the *:80 VirtualHost works properly. I am doing something really similar.
Does it have to do with having two different Rewrite rules in different VirtualHosts?
Any ideas?
Comment: @MadHatter I've read, and followed that guide. If you look at my rules, they conform with the documentation for mod_write.
Comment: Your question is tagged both `apache-2.2` and `apache-2.4`. If you're running 2.4 you should go read the apache mod_rewrite docs again; there may habe been some changes.
Answer: As per http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule:-

What is matched?
In VirtualHost context, The Pattern will initially be matched against the part of the URL
  after the hostname and port, and before the query string (e.g. "/app1/index.html").

Your pattern is matching an exact URL of "docs". The actual URL is probably "/docs", so adding a "/" after the "^" may work:-
RewriteRule    ^/docs$  docs/  [R]

RewriteRule Not Rewriting URL properly


Somehow, edit/delete has been changed to node->title/edit or node->title/delete for one of my project. Can anyone have idea what could be a reason?

Question: Somehow, edit/delete has been changed to node->title/edit or node->title/delete for one of my project. Can anyone have idea what could be a reason?
Any lead towards the debugging would be appreciated.
Answer: On one of my projects, for this kind of functionality I have used Sub-path URL Alises module. Maybe it's enabled on your project ?


How to display all children on parent node for custom content type?

Question: I have a custom content type, let's call it 'parent'. I have another custom content type, let's call it 'child'.
I created a template file where I can display the 'parent' content type fields any way I want: node--parent.tpl.php. By using code such as...
<?php
  print $content['field_city'][0]['#markup'];
?>

I can move fields around and customize the markup, which is great. But how would I also display the parent's children on the same page?
(I don't use Views. I create a content type template file instead because gives me more flexibility for arranging the HTML).
Answer: How are the children linked to the parent? Do you use an Entity Reference field?
Also, what do you want to display from the children? The titles? The entire, rendered nodes?
If you look up entity_metadata_wrapper (see: Entity metadata wrappers) you can see how to access an Entity Reference field.
You also may want to reconsider Views. Overriding templates for Views can give you a lot of flexibility.
Comment: yes, it's an entity reference field. I want to have access to everything from the children.
Comment: tried the examples, don't work: `$node->field_number[LANGUAGE_NONE][0]['value']`, `$node_wrapper->field_number->value();`, `$wrapper->label();`
Comment: BTW I don't want to use Views because then it gets complicated with custom url aliases. Also, you get pages with duplicated information and links to Views/Nodes get confused, for example: the View for the individual node has the the information are the individual node page.
Answer: I know its an old one but it does not seem satisfactorily answered
For drupal 7 usually don't need to mess with template files for such a task.
I would use https://www.drupal.org/project/field_extractor which is a field formatter for entity reference that will let you output any referenced fields from the list of referenced entities (only 1 field though)
If you want to output more than one fields I would suggest the https://www.drupal.org/project/eva which will allow you to create a special entity reference view which you can associate with the referencing entity (parent) and will allow you to output any fields from that entity and format it any way you would format a view.  Automatically the view will be available in the display settings of the referencing entity so you can change the order of appearence.
if the previous 2 modules don't seem to help you can try 1 of the following which work with views but they are a little more difficult to setup and I am not going to go into detail here
drupal.org/project/field_embed_views
drupal.org/project/viewfield
drupal.org/project/views_field_view
(sorry my reputation wont allow me to post more than 2 links)


Breaking guitar strings too quick

Question: Two weeks ago I spent a decent amount of cash and time replacing all the strings on my guitar. They were getting rusty and sounded dull. Since then I've been playing about two hours a day, all going well. But just yesterday the low E string snapped. Of course I could change it but isn't 2 weeks a too short time? Could it be something with my playing, my guitar, or the strings themselves?
FYI I had been playing 'Spit out the bone' by Metallica, which has a LOT of tremolo picking on the low E. This would have led to greater wear, tear and stress on that string, but is it still OK to be getting through a brand new string in 2 weeks? I'm mainly concerned because I'm 15 and there is only so much I can spend on buying strings, so being economical is important for me.
I would be really thankful if someone could tell me if wearing out strings this fast is normal, and how I can possibly increase their longevity.
Comment: Where along the string did it break? This can highlight whether a problem with the nut or bridge is the cause. Also, what kind of guitar are you using?
Comment: @BobBroadley I broke it along the place where the pickups are (where the plectrum hits)
Answer: Playing a couple of hours each day, guitar strings should last longer than 2 weeks. But, light gauge strings may not last as long as heavier strings, and vigorous playing may take a toll on these.
Sometimes when strings are replaced, you may not get a full wrap at the string post; this causes extra stress at the point where the string threads into the post, and this can break rather quickly. Or sometimes you may get a kink in the string during installation; this kink will be a weak point that may break sooner.
You can extend the life of your strings by wiping them down after every playing session with a clean rag; this will slow the appearance of oxidation on the strings, and keep them sounding more lively longer. If you have enough extra string wrapped around the posts, you can remove the strings and boil them to clean them. You may be able to do this once or twice, and it will make them sound remarkably brighter if they are starting to sound dead. It is a little tedious, but when you need to save money....
Of course, try to avoid kinking the strings each time you install them. Make sure that the strings are seated properly at the saddles, and make sure that you have good wraps at the posts. If you remove old strings and boil them, look for places where the strings are worn; strings with worn wrappings probably need to be replaced.
Comment: @Tim-- I haven't played on strings that light in a long time, but my recollection is that they did not handle wear from frets as well as heavier strings. Light strings never seemed to handle vigorous strumming as well as heavier strings to me.
Comment: @Tim-- Not wearing the frets, but wear on the strings. Strings that have seen a lot of action get wear spots in the windings, sometimes wearing all the way through, at the frets. This also happens to unwound strings; less string to wear through on lighter strings. I am sure that breakage has to do with the player too. I use .013s on my archtop electric, and when I pick up a guitar with .008s, it feels like there is nothing there!
Comment: @Tim-- I guess I think that light strings are less forgiving than heavy strings as far as player technique is concerned when it comes to breakage. But the more important points wrt breakage in my answer were about proper installation, avoiding string kinks, etc.
Comment: Why do you say thin strings won't last as long as eavier strings? I use .008s, which won't be as tight, thus under less tension, with more give. Can't remember the last one I broke, years ago, and on a couple of guitars the strings have been on for a year or two, not rusty, in tune, still very playable.
Comment: I'd have thought heavier strings would wear the frets rather than vice versa! Never had problems with ultra-ultra-light gauge, used them for over 30 yrs. Perhaps I'm a bit kinder than some in my playing!
Answer: A lot more info is needed: make of guitar, gauge of strings, standard tuning? Type of pick, height of action, where along the string was the break. All relevant facts.
With so many unknowns, it could be a faulty string - I've known a couple from the same batch break as soon as they were up to pitch.It may be a sharp spot at the nut or saddle. It may be you could use some lighter strings. It could be that you need to tame your picking down to a frenzy. All guesswork till we have more info.
To stop strings rusting, wash hands before playing; wipe down after playing; store guitar in dry room; use fast fret or such like. Although it may just be your sweat reacts badly with the string material.
Answer: Unless you are using a metal pick, there is no way that a low E should be snappable in 2 weeks of use.
So you must have had a faulty string, or had accidentally kinked it when installing it. Incredibly unlikely for that to happen again, so I'd suggest just fitting a new string.
Comment: Nope. Not using a metal pick. Using a D'addario Duralin 0.6 mm pick
Answer: Short answer with nothing much to substantiate my theory except experience, however...
Breaking strings at the picking point is a sure sign you're picking too hard & with a bad 'release' technique.
I'd guess way too much of the hard flat of a hard inflexible pick would be the worst for that. If you're too heavy on it, there's no forgiveness in the pick itself to compensate for your style of attack.
I'd drop to a lighter pick, I'd even go so far as to suggest a thin nylon pick, which are especially kind to strings - as that's an easier way of reducing the strike 'power' without having to relearn your technique overnight.
Long-term, I'd suggest re-learning your technique.
The first time you break a string during a gig will be the point at which it was too late to do either.

Breaking guitar strings too quick


Meteor user profile update

Question: This Meteor client code is trying to update the current user profile with a new property header if it does not exist and asign to it a value from a variable menuShortName
The below code is crashing the app, it does not like ['header'] How can it be done? Thanks
I need to have both server and client be able to modify this value.
Meteor.users.update({_id: userId},{$set: {profile['header']: menuShortName}});

Answer: Your syntax is close. You must wrap nested properties in quotes:
Meteor.users.update({_id: userId}, {$set: {'profile.header': menuShortName}});

Meteor user profile update


Como pegar o processo atual que o usuário está utilizando?

Question: Eu fiz um programa para pegar o processo atual do usuário, mas só o que ele pega é "
ConsoleApplication1.vshost" (
ConsoleApplication1 é o nome do programa), mesmo em janelas como o Google Chrome, etc.
Código:
<code>Process process = Process.GetCurrentProcess();
int vkCode = Marshal.ReadInt32(lParam);
StreamWriter sw = new StreamWriter(Application.StartupPath + @"\log.txt", true);
process = Process.GetCurrentProcess();
if (x == process.ProcessName)
    sw.Write((Keys)vkCode);
else
{
    x = process.ProcessName;
    sw.Write("\n{0}", x);
}
sw.Close();
</code>
Estou fazendo isso da maneira errada? Como posso pegar o processo atual que o usuário está usando de maneira certa?
Answer: Sim. Está.
Para recuperar o processo ativo (em uso) você deve pegar a janela em foco.
Para isso você deve usar a API GetForegroundWindow.
A partir do HWND retornado por esta API você é capaz de recuperar o nome do processo a qual esta janela pertence.
Comment: Tentei fazer dessa maneira e não funcionou: `string y = GetForegroundWindow().ToString();`
Comment: Não é assim que usa. Veja um exemplo aqui. http://www.pinvoke.net/default.aspx/user32.getforegroundwindow
Comment: Se eu copiar e colar da isso:
Erro CS0103 O nome "ApplicationState" não existe no contexto atual ConsoleApplication1   77 Ativo
Comment: Olha, você deve estudar um pouco mais sobre como utilizar as API's do Windows no C# (ou VB.net). É com elas que vai conseguir atingir o seu objetivo.


How to replace primary key with new column with autogenerated values in MySQL?

Question: I have a table merchants with the next columns: name, program_id, program_name.
The current primary key is name + program_id
What I need to do is to add a new column id, fill it in with autogenerated values (preferably uuid or something like that) and make it a new primary key.
How to do that?
Answer: ALTER table merchants DROP PRIMARY KEY, ADD id INT NOT NULL AUTO_INCREMENT PRIMARY KEY;

if your database engine is innodb,I suggest you use auto increment integer as primary key,not uuid,because primary key in innodb is clustered index.Auto increment primaryk key can reduce page splitting.

Notice that not only does it take longer to insert the rows with the UUID primary key,but the resulting indexes are quite a bit bigger. Some of that is due to the larger primary key, but some of it is undoubtedly due to page splits and resultant fragmentation as well.

and the cons of using onsequentially primary key:

The destination page might have been flushed to disk and removed from the caches,or might not have ever been placed into the caches, in which case InnoDB will have to find it and read it from the disk before it can insert the new row. This causes a lot of random I/O.
When insertions are done out of order, InnoDB has to split pages frequently to make room for new rows. This requires moving around a lot of data, and modifying at least three pages instead of one.
Pages become sparsely and irregularly filled because of splitting, so the final data is fragmented.

If you want to learn more about primary key's influence on page splitting or page merging your can visit here


How to skip records with if else statement

Question: Can anyone provide me logic for this problem
Only process the gtV with  bVH01-iMS-FLG = 'Y' .
1)  If not iMS-ORDER,  bypass the record , read next record  & find next gTV to check. One gTV can have multiple records in the input file gTVFLE.
2)  If iMS-ORDER,  continue process  -> abc00-PROCESS-RECORDS.Need to make sure if  any tVL didn't pass the validation/error, then the whole gTV should be held; and then continue to find/read next  gTV.
Comment: The information provided is insufficient. No one can answer this question correctly without some deatils - Where does IMS-Order come from? What are gTV and tVL?
Comment: You're going to have to expand your question. Remember that all is clear to you, but only what you describe can possible be clear to us. Show some sample input, and how you expect that to be processed. Your question should be something we can answer, not expecting us to just do your code for you.
Answer: From the limited information you have provided it appears there will be a field on some record that you are reading called BVH01-IMS-FLG, you will need to identify the condition for that using an 88 level, like so:
01 BVH01-IMS-FLAG pic X.
  88 PROCESS-THIS-RECORD value 'Y'.

It also seems that you have related records in the gTV file and those need to be processed as a group, so something like this:
Perform Read-gTV-Record
Perform until End-Of-File
   If PROCESS-THIS-RECORD
      Perform abc00-Process-Records
   End-IF
   Perform Read-gTV-Record
End-Perform

Really, you need to provide more description of what you are trying to do.  Record layouts of the gTV and what it means to be a valid tVL would be helpful.


Restrict blocks to specific pages

Question: I am using someone else's theme on a very small site.
Specifically, I want to display blocks on specific pages. I am able to display blocks on  only and on all pages except .
My understanding is that I should be able to display a block only on page "what-we-do" putting what-we-do where I put .
Alternatively I code put node/7 (this page being node/7).
The result is that the block is displayed persistently on the front page and on no others.
This is clearly nonsensical and either I am doing something very silly or I need to start reading through the code.
My question, precisely: has anyone encountered this problem before and can they suggest a way forward?
Comment: Could you provide a screenshot of your block configuration (admin/structure/block/manage/system//configure)
Comment: It seems page.tpl.php is override for home page. And the region in which you placed the block is not printed in any other template file except front page.
Comment: And is it a contributed theme or something someone customised?
Comment: In addition to the other excellent advice given, have a look to see if you have any modules in there that could be overriding normal block behaviour, specifically something like Context.
Comment: MrWatergate - not sure what you are looking for there. Daraven - contributed theme with a very simple sub-theme - yes potential for error but minimal edits on the .info and .css.
Comment: Sumit Madan and J. Reynolds - I ultimately installed Context and go some traction - and then the whole system stopped again.
Comment: Thanks everyone. I think a fresh build for starters and then a deep trawl through the code.
Answer: Sumit Madan was spot on.  Several blocks were hard coded as front page only in the page.tpl in the contributed theme.
For other newbies caught out by hard coding, the cues are:

The visibility settings for a block behave erratically, i.e., in a pattern not consistent with your expectations
When you inspect the regions (/Structure/Blocks - at the top), some of the regions do not appear. Yet, you can put a block into them and the show up when you inspect under Firebug. Now I understand the problem, a quirk that had puzzled me is fully explained.

To find the hard coding in page.tpl, look for ($is_front) and change that to ($page != 0).
page=0 refers to pages like lists of taxonomies. So this edit means the relevant blocks will be available to all pages including the front page and can be managed using the block visibility as usual.
Thanks everyone.

Restrict blocks to specific pages


Migrations adiciona a letra S no nome da tabela

Question: Tenho um model:
public class pimentel
{
    [Key]
    public int id { get; set; }
    public string cod_item_Crm { get; set; }
    public string tag { get; set; }
    public string data_anal { get; set; }
    public string modelo { get; set; }
    public int cod_cli { get; set; }
}

Porém, quando executo a aplicação, o sistema, sempre procura a tabela de nome pimentels, e caso nao exista, ele cria uma tabela, mas, sempre com a letra "S" no final.
Posso mudar o do model para qualquer outro, e sempre ele gera com a letra "S" no final

Aguem tem noção oque pode ser?
Answer: É a regra padrão de pluralização do nome das classes.
Você pode desabilitar isto no método OnModelCreating, com o seguinte código
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();


What would be the equivalent to SetForegroundWindow with X11?

Question: I'm part of the SFML Team and we're currently looking into a feature to "request" window focus. The goal is to get very similar behavior across Windows, OS X and Linux.
For Windows one gets the rather simple SetForegroundWindow function via the WinAPI, which has a few condition as to how the window actually gets focus. The most important part to notice here is, that it only gets focus if it's from the same foreground process.
On OS X it's possible to get the focus for the active app only and otherwise let the icon bounce, i.e. notification.
Here comes the problem now, we'd like to get the same behavior on Linux as well, meaning the window should get focus if the window belongs to the active/foreground process and otherwise it should generate a notification. What would be the closest thing to that with X11?
There are already a few suggestions on the issue tracker of SFML, but none of them are actually implementing this behavior.
"User Story"
I guess developers can think of different things when being confronted with different technical names, as such here's the issue from a user perspective.
There are mainly two situations in which requesting focus is needed:

Sometimes when starting an application that uses a console window in the background, it can happen that the console window gets the focus instead of the actual GUI window. When this happens it's rather annoying for the user having to click on the window first. Since the console window and the GUI window are from the same application there's no harm done in switching the focus to the GUI window.
When one is writing an application that supports multiple windows, there might be situations where the application should decide which window gets the focus and again since the window belong to the same application there's no harm done in switching the focus from one GUI window to the other GUI window.
Further more if a different application has the focus/is being used then it's not okay to steal the focus and as such we just want to get the user's attention. For Windows that might be a blinking taskbar or for OS X that might be a jumping icon.

The current implementation seems to work fine on OS X and Windows, butwe're unsure about the X11 implementation. Thus the question is: How would one go about switching the window focus if the currently focussed window has been created by the same application that makes the focus request and otherwise create some kind of notification. For the notification we're/I'm not even sure if there's some generic way of doing it with X11.
Comment: (1) There is no such thing as an active/foreground process on Linux. (2) Windows belong not to processes, but to *clients* (which may be processes on any computer on the network, or hardware devices). The whole thing is very poorly defined. What behaviour do you actually need? Tell a **user story**. Users have no idea what words like "process" or "focus" or "foreground" mean.
Comment: Thanks @n.m. for your comment. I've added some more info that hopefully explain things a bit better.
Comment: How have you done this in Mac?
Comment: You can find the full implementation for SFML on GitHub: https://github.com/SFML/SFML/tree/master/src/SFML/Window/OSX
Answer: In X11, "focus" means "the keyboard focus", that is, the window that gets the keyboard input. The window that has the focus is not necessarily in the foreground. This depends on your window manager focus policy. Most can be configured to have "click-to-focus" or "point-to-focus" policy. If you are interested in the keyboard focus, use XSetInputFocus. If you want to bring your window to the foreground, use XRaiseWindow.
It is OK to call RaiseWindow and XSetInputFocus once, when the application starts. It is also OK to bring a window to the foreground/set focus as a response to a user interaction with that or some other window of the same application. But it's not OK to do so as a response to some background event (time passed, file downloaded etc).
The standard X11 method of drawing attention to a window is setting the urgency hint. This will normally flash or bounce the icon, depending on your window manager. Do not forget to unset the hint when the user finally interacts with the window.
I think all of this has been discussed in the thread you have linked. I'm not quite sure which concerns are still left unanswered. Nothing can implement the exact same behaviour as with the other windowing systems, simply because X11 is not those windowing systems, and it's totally OK. X11, Mac OS X and Windows all behave differently and the users know and expect that. It would annoy me to no end if some application on X11 decided to behave exactly like it does on Windows, instead of toeing the X11 party line.
Comment: Thanks! The main reason I opened this question here, was because I wanted to get some second opinion on things, especially from someone that has been doing quite a bit of X11 development. I don't know how much the other participants know about X11 deevelopment, but it seemed like there were quite a few uncertainties.


If $ A_{k} = \frac{k(k-1)}{2}\cos\left[\frac{k(k-1)\pi}{2}\right]\;,$ Then $\sum^{101}_{k=1}A_{k}=$

Question:
If $\displaystyle A_{k} = \frac{k(k-1)}{2}\cos\left[\frac{k(k-1)\pi}{2}\right]\;,$ Then $\displaystyle \sum^{101}_{k=1}A_{k}=$

$\bf{My\; Try:}$ Let $\displaystyle S = \sum^{101}_{k=1}A_{k} = A_{1}+A_{2}+A_{3}+........+A_{101}$
So we get $$\displaystyle S = 0\cdot \cos (0)+1\cdot \cos \left(\pi\right)+3\cdot \cos(3\pi)+6\cdot \cos (6\pi)+10\cdot \cos(10\pi)+.....+5050\cos(5050\pi)$$
Now I did not Understand How can I solve it
Help me
Thanks
Answer: Since
$$
\cos\left(\frac{k(k-1)\pi}2\right)=\left\{\begin{array}{rl}
1&\text{if }k\equiv0,1\pmod{4}\\
-1&\text{if }k\equiv2,3\pmod{4}
\end{array}\right.
$$
For the sum of four consecutive terms, we get
$$
\small\frac{(4k+1)4k}2-\frac{(4k+2)(4k+1)}2-\frac{(4k+3)(4k+2)}2+\frac{(4k+4)(4k+3)}2=2
$$
Therefore, the sum
$$
\begin{align}
\sum_{k=1}^{100}\frac{k(k-1)}2\cos\left(\frac{k(k-1)\pi}2\right)
&=\sum_{k=0}^{24}2\\
&=50
\end{align}
$$
Adding the term for $k=101$, which is $5050$, yields
$$
\sum_{k=1}^{101}\frac{k(k-1)}2\cos\left(\frac{k(k-1)\pi}2\right)=5100
$$
Answer: HINT: If $n$ is even, $cos(n\pi)=1$ and If $n$ is odd, $cos(n\pi)=-1$.
Answer: Observe that $$\frac{k(k-1)}{2}=1+2+3+ \ldots +(k-1) = \sum_{r=1}^{k-1} r = S_{k} (say)$$
And since sum of an even and an odd number is odd while sum of two odd numbers is even, we have that:
$ S_2,S_3, S_6 ,S_7, S_{10}, S_{11} \ldots S_{4k+2},S_{4k+3} $ are all odd and they are $50$ in number. Similarly, $ S_1,S_4, S_5 ,S_8, S_9, S_{12}, S_{13} \ldots S_{4k+4},S_{4k+5} $ are all even and they are $51$ in number.
So if noted carefully, your sum can be expressed as the sum of $$\sum_x x \cos (x\pi) = \sum_x t_x$$
When $x$ is odd, $t_x=-x$ and when $x$ is even, $t_x=x$
So your sum boils down to $$\sum_{k=0}^{24}(S_{4k+4}+S_{4k+5})-\sum_{k=0}^{24}(S_{4k+2}+S_{4k+3})+S_{1}$$
$$=\sum_{k=0}^{24}(S_{4k+4}+S_{4k+5}-S_{4k+2}-S_{4k+3})+S_{1}$$
$$=\sum_{k=0}^{24}(4k+3+4k+3+4k+2)+0$$
$$=\sum_{k=0}^{24}(12k+8)$$
$$=6 \cdot 25 \cdot 24 + 8 \cdot 25$$
$$=3800$$
Hope this helps you. And ignore the calculations if there is any mistake in calculations.
Answer: You can solve the more general problem:
$$A(n)=\sum_{k=1}^{2n+1}\frac{k(k-1)}2\cos\Bigl(\frac{k(k-1)}2\Bigr).$$
Observe first that $\;\dfrac{k(k+1)}2- \dfrac{k(k-1)}2=k$. As $\cos\dfrac{k(k-1)\pi}2=1$ if $k=1$, we deduce that $\cos\dfrac{k(k-1)\pi}2=(-1)^{k-1}$, and the sum is simply, grouping in consecutive pairs of indices:
\begin{align*}
A(n)&=\sum_{k=1}^{2n+1}(-1)^{k-1}\frac{k(k-1)}2=\sum_{k=2}^{2n+1}(-1)^{k-1}\frac{k(k-1)}2\\
&=\sum_{j=1}^{n}\biggl(-\frac{2j(2j-1)}2+\frac{(2j+1)2j}2\biggr)\\
&=\sum_{j=1}^{n}2j=\color{red}{n(n+1)}.
\end{align*}
Comment: There's a missing summation on the next-to-last line of your answer.
Comment: Thanks for pointing it. It's corrected now.


Menu, submenus NAV Bootstrap dinâmicos com PHP PDO Mysql

Question: Boa noite.
Preciso montar um menu dinâmico, de três tabelas, que precisam estar interligadas, mas estou perdido. Segue uma parte do organograma abaixo:

No momento, tenho o seguinte código:

    Produtos

Audiologia

      <?php

      require 'conexao.php';

      $consulta = $PDO->query("SELECT * FROM subcategoria WHERE categoria_id = '1' ORDER BY ID;");

      while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) { ?>

<a href="produto.php?id=<?php echo "$linha[id]"; ?>"><?php echo "$linha[titulo]"; ?>

      <?php } ?>

        <?php

        require 'conexao.php';

        $consulta = $PDO->query("SELECT * FROM produto WHERE categoria_id = '1' AND subcategoria_id = '1' ORDER BY ID;");

        while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) { ?>

<a href="produto.php?id=<?php echo "$linha[id]"; ?>"><?php echo "$linha[titulo]"; ?>

        <?php } ?>

No meu banco de dados, tenho as tabelas:
CATEGORIAS = com as categorias principais, ID e CATEGORIA.
SUBCATEGORIAS = com os campos ID, CATEGORIA_ID e SUBCATEGORIA.
PRODUTO = com os campos ID, CATEGORIA_ID, SUBCATEGORIA_ID e TÍTULO.
Consigo, à partir deste código, ter a categoria e a sub categoria, mas não o produto. Não creio que essa seja a forma correta de fazer, gostaria de instruções.
Comment: Sei que não é sobre a pergunta, mas você não precisa colocar dois require para conexão.
Comment: Tem razão... vou corrigir isso... é o cansaço... obrigado pelo toque
Answer: Assim o código fica menor e mais fácil de enxergar, por mais que o meu código não esteja 100% do jeito que você precisa, para ajustar fica mais simples desta forma.
Na segunda query eu coloquei para ele pegar o id da primeira query e caso você precise utilizar mais um foreach para as categorias eu deixei separado a variável $id_categoria para ficar mais simples de substituir.
<?php
require 'conexao.php';
$id_categoria = 1;
$consulta = $PDO->query("SELECT * FROM subcategoria WHERE categoria_id = '".$id_categoria."' ORDER BY ID;");
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
    $categoria[$linha['id']]['titulo'] = $linha['titulo'];
    $subconsulta = $PDO->query("SELECT * FROM produto WHERE categoria_id = '".$id_categoria."' AND subcategoria_id = '" . $linha['id'] . "' ORDER BY ID;");
    while ($sublinha = $subconsulta->fetch(PDO::FETCH_ASSOC)) {
        $categoria[$linha['id']]['subitens'] = array($sublinha['id'], $sublinha['titulo']);
    }
}
?>

    Produtos

Audiologia

        <?php foreach($categoria as $indice => $item): ?>

<a href="produto.php?id=<?php echo $indice; ?>"><?php echo $item['titulo']; ?>

            <?php foreach($item['subitens'] as $subindice => $subitem): ?>

<a href="produto.php?id=<?php echo $subindice; ?>"><?php echo $subitem; ?>

            <?php endforeach; ?>

        <?php endforeach; ?>

Comment: Obrigado pela pronta resposta. Ainda tem algo errado, a subcategoria não carrega...
Comment: esqueci da '' na $linha['titulo'], editei agora.
Comment: Acredito que a lógica esteja certa, mas algo não fecha... uso o Sublime, depois do `categoria_id = '".$id_categoria."'` o AND e o ORDER BY ID não ficam vermelho, como de costume no programa. Alguma aspa? Sei lá... :(
Comment: Coloquei o código no notepad++ não deu este problema, mas você pode tentar desta forma: "SELECT * FROM subcategoria WHERE categoria_id = '$id_categoria' ORDER BY ID;", que funciona da mesma forma.
Comment: Nada feito. Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING
Comment: O que eu preciso colocar é: CATEGORIA --> SUBCATEGORIA --> PRODUTO. Não consigo enxergar onde está o erro.
Comment: Tente ver o que esta retornando coloque embaixo dos whiles var_export($categoria); para enxergar o que ele esta pegando.
Comment: NULLarray ( 1 => array ( 'titulo' => NULL, ), )array ( 1 => array ( 'titulo' => NULL, 'subitens' => array ( 0 => '1', 1 => 'teste', ), ), )array ( 1 => array ( 'titulo' => NULL, 'subitens' => array ( 0 => '1', 1 => 'teste', ), ), 2 => array ( 'titulo' => NULL, ), )array ( 1 => array ( 'titulo' => NULL, 'subitens' => array ( 0 => '1', 1 => 'teste', ), ), 2 => array ( 'titulo' => NULL, ), 3 => array ( 'titulo' => NULL, ), )array ( 1 => array ( 'titulo' => NULL, 'subitens' => array ( 0 => '1', 1 => 'teste', ), ), 2 => array ( 'titulo' => NULL, ).....
Answer: Tente isso:
<?php require_once('conexao.php');
$id_categoria = 1;
$consulta = $PDO->prepare("SELECT * FROM subcategoria WHERE categoria_id = :idCategoria ORDER BY ID;");
$consulta->bindParam(':idCategoria', $id_categoria, PDO::PARAM_INT);
$consulta->execute();
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
    $categoria[$linha['id']]['titulo'] = $linha['titulo'];
    $subConsulta = $PDO->prepare("SELECT * FROM produto WHERE categoria_id = :idCategoria AND subcategoria_id = :idSubcategoria ORDER BY ID;");
    $subConsulta->bindParam(':idCategoria', $id_categoria, PDO::PARAM_INT);
    $subConsulta->bindParam(':idSubcategoria', $linha['id'], PDO::PARAM_INT);
    $subConsulta->execute();
    while ($sublinha = $subConsulta->fetch(PDO::FETCH_ASSOC)) {
        $categoria[$linha['id']]['subitens'] = array($sublinha['id'], $sublinha['titulo']);
    }
}
?>

    Produtos

Audiologia

                <?php foreach ($categoria as $indice => $item) { ?>

<a href="produto.php?id=<?php echo $indice; ?>"><?php echo $item['titulo']; ?>

                        <?php foreach ($item['subitens'] as $subIndice => $subitem) { ?>

<a href="produto.php?id=<?php echo $subIndice; ?>"><?php echo $subitem; ?>

                        <?php } ?>

                <?php } ?>


Show that some quotient space of $GL_2(\mathbb{Q}_p) $ is compact

Question: Let $T_{\tau}:=\{\begin{pmatrix}a&b\tau\\b&a\end{pmatrix}:a,b\in\mathbb{Q}_p,a^2-b^2\tau\neq0\}$, where $\tau\in\mathbb{Q}_p^{\star}$ with $\tau\notin(\mathbb{Q}_p^{\star})^2$.
Author claimed that $T_{\tau}/Z$ is compact, where $Z:=\{\begin{pmatrix}r&0\\0&r\end{pmatrix}:r\in\mathbb{Q}_p^{\star}\}$, i.e $Z$ is a center of $GL_2(\mathbb{Q}_p)$.
To prove this, author showed that any element $t$ in $T_{\tau}$ can be written in the form $t=\begin{pmatrix}p^n&0\\0&p^n\end{pmatrix}\cdot k$, $k\in T_{\tau}\cap GL_2(\mathbb{Z}_p)$ under the assumtion $\tau\in \mathbb{Z}_p^{\star}$ and $p>2$.
Then, author says that this completes the proof that $T_{\tau}/Z$ is compact.
I understand how $t$ can be written in the above form but why this implies that $T_{\tau}/Z$ is compact?
Also, author called $T_{\tau}$ as torus. Is there any reason to this?
Full arguments can be found in [Dorian goldfeld, automorphic representations and l-functions for the general linear group: volume 1, page 189]
Thank you.
Comment: If a quotient group $G/N$ has a compact subset of representatives $S$ in $G$, then the composition of natural maps $S \to G \to G/N$ is continuous and surjective, so $G/N$ is compact.
Comment: @KCd Thank you for the answer! So $G=T_{\tau}$, $N=Z$, and $S=GL_2(\mathbb{Z}_p)\cap T_{\tau}$. $GL_2(\mathbb{Z}_p)$ is compact in $GL_2(\mathbb{Q})$ so $S=GL_2(\mathbb{Z}_p)\cap T_{\tau}$ is compact in $T_{\tau}$ with subspace topology in $T_{\tau}$. Finally as your map is continuous and surjective(surjectivity follows from the decomposition of $T_{\tau}$ as in the book). Is it ok??
Answer: To put this into a possibly enlightening context, notice that for any field $K$ and any $\tau \in K^* \setminus (K^*)^2$, we have $a^2-b^2\tau =0$ for $a,b \in K$ if and only if $a=b=0$, so the algebra of matrices $\pmatrix{a&b\tau \\b&a}$ identifies (via $\mapsto a +b\sqrt{\tau}$) with the field extension $L_\tau:=K(\sqrt{\tau})$, your $T_\tau$ with its multiplicative group $L_\tau^*$, and the determinant $a^2-b^2\tau$ of such a matrix with the norm map $N_\tau:L \rightarrow K$ which induces a homomorphism of multiplicative groups $L_\tau^* \rightarrow K^*$.

Calling $U_\tau$ the kernel of this homomorphism, i.e. the multiplicative group of norm-$1$-elements of $L_\tau$, we further always have a short exact sequence
$$ 1\rightarrow U_\tau \rightarrow L^*_\tau \rightarrow N_\tau(L_\tau^*) \rightarrow 1$$
Now in the case of $K$ being a local field, that norm-$1$-group $U_\tau$ is always compact. In fact, in the archimedean case $K=\mathbb R$, wlog $\tau =-1$, this sequence becomes
$$ 1\rightarrow e^{i\mathbb R} \rightarrow \mathbb C^* \rightarrow (\mathbb R_{>0}, \cdot) \rightarrow 1$$
which is well-known to split i.e. give the standard "polar coordinates" $z = r e^{i\phi}$ for complex numbers, with $U_\tau$ being the unit circle i.e. the original torus $\simeq S^1$.
In the non-archimedean case, it's well-known that the absolute value of $K$ extends essentially uniquely to $L$ via $| \cdot |_L := \sqrt{N(\cdot)}$. In the case you specialize to, namely $K=\mathbb Q_p$ with $p \neq 2$ and $|\tau|=1$, you are looking at the unramified quadratic extension and the exact sequence becomes
$$ 1\rightarrow \{x \in \mathcal{O}_L^\times:N(x)=1\} \rightarrow L^* \rightarrow p^{2\mathbb Z} \cdot \mathbb Z_p^* \rightarrow 1$$
which looks non-split, at least including the group on the right back into the middle certainly does not provide a splitting.

That being said, the construction you cite is kind of "orthogonal" to that one and looks at the exact sequence
$$ 1\rightarrow K^* \rightarrow L^*_\tau \rightarrow L_\tau^*/ K^* \rightarrow 1$$
The quotient on the right is what you are interested in. As orangeskid notes in their answer, the underlying topological space of that quotient is $P^1(K)$, the one-dimensional projective space over $K$ (this forgets a lot of structure, as it does not even need $L$ to be a field, just a two-dimensional vector space over $K$). Already in the case $K=\mathbb R$ this quotient is not actually the full unit circle $e^{i\mathbb R}$, but its quotient modulo $\{\pm 1\}$ (which however topologically is still the circle $S^1$).
In your case, the product decomposition from your source certainly shows (as per KCd's comment) that the quotient is compact. But in fact I was not joking when I said this sequence is orthogonal to the other one, as we always have the following commutative diagram with exact rows and columns: $\require{AMScd}$
\begin{CD}
 @.  1 @. 1 @.  1@. \\
@. @VVV @VVV @VVV \\
1 @>>> \pm 1 @>>> K^* @>()^2>> (K^*)^2=N_\tau(K^*) @>>> 1\\
@. @VVV @VVV @VV a V \\
1 @>>> U_\tau @>>> L_\tau^* @>N_\tau>> N_\tau(L_\tau^*)@>>> 1\\
@. @VVV @VVV @VVV \\
1 @>>> U_\tau/\pm 1 @>b>> L_\tau^*/K^* @>>> N_\tau(L_\tau^*)/N_\tau(K^*)@>>> 1\\
@. @VVV @VVV @VVV \\
@.  1 @. 1 @.1@.\\
\end{CD}
The map $b$ is an isomorphism if and only if the includion $a$ is an equality, which is the case for $K=\mathbb R$, but not for other local fields. However, for $p$-adic fields with $p \neq 2$, the bottom right object is just of size $2$ (and even for $p=2$ it is finite), so the object we are interested in (the middle of the last row) is "up to finite obstacles" the torus $U_\tau$. (In particular, it is as compact as $U_\tau$ is).
Comment: Thank you for the detailed answer! I have one basic question for your anwser. Author called $T_{\tau}$ as torus and $T_{\tau}\cong L_{\tau}^{\star}$ as in your answer. It seems like(If I understood correctly) that you call $U_{\tau}$ as torus not $T_{\tau}$. Also I'm wondering why unit circle=$S^1$ can be regarded as torus.
Comment: @KSM: I was using "torus" in the generalized sense of https://en.wikipedia.org/wiki/Torus#n-dimensional_torus , i.e. any finite product of copies of $S^1$. Apparently the author uses an even more generalized notion which is common in the language of algebraic groups, namely, a torus is any such group which (after scalar extension) becomes isomorphic to a finite product of the multiplicative group (scheme). Here, it is the multiplicative group itself.
Comment: Thank you so much!
Answer: You could see the quotient as $\mathbb{P}^1(\mathbb{Q}_p)$, a union of two compact subsets, $[1\colon \mathbb{Z}_p]$, and $[\mathbb{Z}_p\colon 1]$,  depending on which component has the smallest $\nu_p$. Also works for $\mathbb{P}^n(F)$.
Comment: Thank you for the answer!


Is the closed unit ball of a Hilbert space a weak sequential space?

Question: I am currently reading a proof on characterizations of a compact operator for Hilbert spaces. Let $\mathscr{B}_1$ be the closed unit ball of the Hilbert space $H$. One of the equivalent statement involves: $T\in B(H)$ is the norm-limit of finite rank operators if and only if $T_{|\mathscr{B}_1}:\mathscr{B}_1\to H$ is continuous as a function from $\mathscr{B}_1$ endowed with weak topology to $H$ endowed with the norm topology.
The author then proceeds to prove the $\implies$ direction of the result basically by showing that $\{x_n\}$ converges weakly to $x$ in $\mathscr{B}_1$ implies that $\{Tx_n\}$ converges to $Tx$ in norm of  $H.$ I know this is the sequential criterion for continuity, but this is only valid if $\mathscr{B}_1$ is a (weak) sequential space. Is it?
I've tried looking for other sources, but to no avail.
Answer: This is just from the definition of weak convergence. First, suppose $Tx = \phi(x) y$ is an operator of rank $1$, where $\phi \in H^*, y \in H$. Let $(x_\alpha)_\alpha$ be a net in $\mathscr{B}_1$ converging weakly to $x \in \mathscr{B}_1$. Then
$$\|Tx - T x_\alpha \| = | \phi(x - x_\alpha) | \|y \| \to 0 .$$
We can then extend this fact to an operator of finite rank by finite additivity. Now if $S$ is an arbitrary compact operator, then if $T$ is a finite-rank operator that norm-approximates $S$, then
\begin{align*}
\| Sx - S x_\alpha \| & \leq \| Sx - Tx \| + \| Tx - T x_\alpha \| + \| T x_\alpha - S x_\alpha \| \\
& \leq \| S - T \| \|x \| + \| Tx - T x_\alpha \| + \| T - S \| \|x_\alpha \| \\
& \leq 2 \| S - T \|  + \| Tx - T x_\alpha \| .
\end{align*}
Now fix $\epsilon > 0$, and choose $T$ finite-rank so $\| S - T \| < \epsilon / 3$. Then choose $\beta$ so $\alpha \geq \beta \Rightarrow \| Tx - T x_\alpha \| < \epsilon / 3$. Then if $\alpha \geq \beta$, then $\| S x - S x_\alpha \| < \epsilon$.
Therefore $S$ is continuous from the weak $\mathscr{B}_1$ to the normed $H$.
Comment: I am! Thanks! I have actually forgotten about that very important difference between nets and sequences!
Comment: Does the sequential continuity, as what you have shown imply that $T$ then is continuous wrt  to the appropriate topologies?

Edit: I am not really asking how to show sequential continuity, but I am asking how showing it would imply actual continuity of $T$.
Comment: @Kurome Are you familiar with nets? A net is a generalization of a sequence such that a function $f : X \to Y$ between *any* topological spaces is continuous iff for every net $(x_\alpha)_\alpha$ in $X$ converging to a point $x \in X$, the net $(f(x_\alpha))_\alpha$ in $Y$ converges to $f(x)$. I claim you could replace all the sequences $(x_n)$ in my answer with nets $(x_\alpha)$ and things would work out just the same.
Comment: @Kurome I've edited my answer to hopefully cut down on the confusion.


Codeigniter: Using button click to view more data from database

Question: Ideally, In my database table, I have username, name, location, email.
Now I have a table in my view.php where it returns value from the database.
Table header consists of name, username, and more info where name and username comes directly from the database while more info will have a button for each row. When the button is clicked, it should display location and email in a pop up.

Question: How can I retrieve location and email of a user when the button is clicked specifically?

Example:
user1, joe doe, [button] -> user1 location, firstname.lastname@example.com
user2, jay doe, [button] -> user2 location, email@example.com
Codes: p.s. code includes pagination.
controller.php
function pagination() {
        $config = array();
        $config['base_url'] = base_url() . "controller/pagination";
        $total_row = $this->model->record_count();
        $config["total_rows"] = $total_row;
        $config["per_page"] = 8;
        $config['uri_segment'] = 3;
        /* $config['use_page_numbers'] = TRUE; */
        $config['num_links'] = $total_row;
        $config['cur_tag_open'] = ' ';
        $config['cur_tag_close'] = '';
        $config['next_link'] = '»';
        $config['prev_link'] = '«';

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        $data["results"] = $this->model->fetch_data($config["per_page"], $page);
        $str_links = $this->pagination->create_links();
        $data["links"] = explode(' ', $str_links);

        // View data according to array.
        $this->load->view("view-employees", $data);
    }

model.php
public function record_count() {
    return $this->db->count_all('users');
}

public function fetch_data($limit, $start) {
    $this->db->limit($limit, $start);
    $query = $this->db->get('users');

    if ($query->num_rows() > 0) {
        foreach ($query->result() as $row) {
            $data[] = $row;
        }

        return $data;
    }
    return false;
}

view.php

    username
    name
    more

    <?php foreach ($results as $data) { ?>
    <?php echo $data->username; ?>
    <?php echo $data->name; ?>

        <button type='button' class='btn'>
           <?php echo $data->location;
                 echo $data->email;
           ?>
        </button>

Comment: adding some code would be nice ..
Comment: @AbdullaNilam added.
Answer:
You could write a Codeigniter-controller which will return email and location
Then you write Javascript-functions which will call this controller to retrieve the data asJSON-Data

Both, writing a controller which returns JSON and an example how to call this controller from JS can be found here:
Code Igniter - How to return Json response from controller
Comment: I have updated my post together with the codes. Can you check please?
Answer: Try like this..
MODEL:
public function record_count() {
    return $this->db->count_all('users');
}

public function fetch_data($limit, $start) {
    $this->db->limit($limit, $start);
    $query = $this->db->get('users');

    if ($query->num_rows() > 0) {
         return $query->result_array();
        }

    }
    return false;
}

View:

    username
    name
    more

    <?php foreach ($results as $data) { ?>
    <?php echo $data['username']; ?>
    <?php echo $data['name']; ?>

        <button type='button' class='btn'>
           <?php echo $data['location'];
                 echo $data['email'];
           ?>
        </button>

<?php } ?>

Comment: Hi, Thank you for your response. Yes, it does work perfectly if echo it out directly to the button. Is there a possible way to echo it in a pop up?
Comment: yes you can study about bootstrap model.set some html with attribute..I hope you can do it.
Comment: see here about model http://www.w3schools.com/bootstrap/bootstrap_modal.asp
Comment: if you got help form this answer feel free to accept ans vote up.best of luck ahead.


Gradient descent algorithm explanation

Question: How do I get from the derivative in the second last line to get xj in the last line?
Answer: $$
\frac{\partial}{\partial \theta_j} h_\theta(x) = \frac{\partial}{\partial \theta_j} [\theta_0 x_0 + \dots + \theta_j x_j + \dots + \theta_n x_n] = 0 + \dots + x_j + \dots + 0
$$
The underlying assumption here is that: $\frac{\partial \theta_i}{ \partial \theta_j }= 0 \ \forall i \neq j$.

Gradient descent algorithm explanation