A computer's memory is finite, so how can there be languages more powerful than regular?

Question: A computer has a finite memory. There are no computers with infinite memory. Therefore the only languages that a computer can process are those whose member strings are finite. As I recall, the computational power required for any finite language is small -- a deterministic finite state automata is sufficient to process finite languages, I think.
So there is no such thing as context-free languages or recursively enumerable languages, right? Programming languages are not context-free, they are just simple regular languages, right? The idea that a programming language is a context-free language ... well, that's an illusion, right?
Why do we even bother to talk about context-free languages, recursive languages, recursively enumerable languages since inside the (finite) computer everything is just a regular language?
Obviously I am playing devils-advocate here, but I would really like to understand the fallacy of my argument.
Summary of Responses
Thank you very much to all who responded. I have studied your responses carefully. There are so many pearls of wisdom in your responses that I decided to summarize them. If my summary is incorrect, unclear, or missing an important concept, please let me know.
> A computer has a finite memory. There are no computers
> with infinite memory. Therefore the only languages that
> a computer can process are those whose member strings
> are finite.

Responses
A computer's memory is finite, so in its memory it can recognize only finite languages. However, if you would pass an external input to the computer, then it could recognize some infinite languages.
Example: a*b is an infinite language and any string in that language can be recognized, even if the string exceeds the size of the computer's memory. Here's how: pass the string into the computer character by character. If the first character that is passed in is not an "a" then go to an error state. Otherwise, stay in the "a" state until a non-"a" character is input. If the character is not a "b" then go to the error state. Otherwise, go to an accept state. For any characters beyond "b" go to the error state.
Not all infinite languages can be recognized using this technique of feeding the input strings in as external input. In fact, the technique can be used only with regular languages. And even of the regular languages, only some of them can be recognized.
Example: For illustration purposes, suppose the computer has a ridiculously small memory size, say, 2 bytes. Suppose 1 byte is required for each state of a finite state automaton. Then the computer will not be able to recognize this regular language: a*b*c* because at least three byes are needed – one byte for the state that consumes all the a's, a second byte for the state that consumes all the b's, and a third byte for the state that consumes all the c's.
Any finite state automaton that requires more states than there are bytes in the computer's memory cannot be recognized.
Finally, with this technique of feeding arbitrarily long strings into the computer as external input, we would need to find a way around certain technical limitations such as a continuous power supply.
> A computer has a finite memory. Therefore the only languages
> that a computer can process are those whose member strings
> are finite … So there is no such thing as context-free languages
> or recursively enumerable languages, right?

Responses
Consider an infinite language. It consists of strings of arbitrary length. Many strings will be longer than the size of the computer's memory. It is incorrect to say that because a computer can hold in its memory only those strings that are of a certain finite length, the language has only finitely many strings.  It is true that any finite subset of a language is regular. But that does not mean that the original language must have been regular.
> A computer has a finite memory. Therefore, in general, a computer
> can only process a finite subset of an infinite language. A finite
> subset of a language is regular. So why don't we simply treat all
> languages used in computers as regular?

Responses
The reason to treat, say, a programming language as context-free is that the context-free grammar tells how to parse the language. If you considered just the subset of programs with length no more than 232, that would be regular but the regular expression would likely consist of millions of individual cases and wouldn't be helpful for parsing the programs.
Comment: You are making the following invalid deduction: because a particular computer can only hold finitely many C programs in its memory, therefore there are only finitely many C programs. In general it is true that any finite subset of a language is regular, but that does not mean that the original language must have been regular, if it was infinite.
Comment: You can process arbitrarily long strings with finite memory, i.e. you don't have to store them (but nothing beyond regular).
Comment: I know it is slightly OT but I remembered this question http://math.stackexchange.com/questions/946/computation-with-a-memory-wiped-computer. It might also interest you ;)
Comment: Note, it isn't fair to say that there aren't infinite languages, it's only fair to say that nobody has ever needed them.
Comment: You are making a very serious error when you try to discuss the theoretical computers used in computer science and real computers in the same way.  Theoretical computers are usually not infinite in size, but they are assumed large enough for any finite computation at hand.  Real computers have a fixed size, though clever techniques or money can improve it.  CS has (often) not found it useful to worry about whether you have 1MB or 1TB available, so assumes you have enough.  Real people who have to buy memory do care.
Answer: The reason to treat a programming language as context-free is that the context-free grammar tells how to parse the language. If you considered just the subset of C consisting of programs of length no more than $2^{32}$ that would be regular, but the regular expression would likely consist of millions of individual cases, and wouldn't be helpful for parsing the programs. You might not even be able to fit the compiler in memory...
For a simpler example, consider a context free grammar for arithmetical expressions with natural numbers, addition and multiplication.

E -> {sequence of digits 0-9}
E -> ( E + E )
E -> ( E * E )

If you only look at expressions with 500 or fewer symbols, that fragment of the language is regular, but it is much more difficult to describe as a regular language than as a context-free one.  Plus, the parse tree for the context-free grammar gives a direct way to evaluate the expressions, while the parse tree for that smaller fragment as a regular language is not likely to help evaluate the expression.
Comment: http://trevorjim.com/c-and-cplusplus-are-not-context-free/
Answer: Actually, in the sense of the program, you can make a computer as power as the universal Turing Machine. (In fact, the computer you are on probably is.) More precisely, you can write down explicitly a universal Turing Machine in many of the actual computer languages out there. So in a very real-world sense, there are computer program much more power than any finite automata (the model of computation that recognizes regular langauges).
It is true that a computer has finite memory. This just means that a computer will imitate any Turing machine until it runs out of memory, electric, etc. However any computation that halts takes finite amount of time. So theoretically, one would just need to build a more powerful computer. If a computation does not halt by an idealize Turing machine, neither will it by any real computer no matter how powerful. This does change the fact that your real computer is running the same program as a universal Turing machine.
Morever, you should make a distinction between languages and the model of computation. A language is a string of symbols. A recursive langauge is one decided by a Turing Machine. A recursively enumerable language is one accepted by a Turing machine. For instance, the set $H$ of code $\langle e, f \rangle$ such that the $e^\text{th}$ Turing Machine halts on input $f$ is the recursively enumerable set corresponding to the Halting problem. This is a just a set of numbers! An idea! Why should the fact that real computers have finite memory have any bearing on whether a recursive language or regular language (some infinite set; an abstract idea) should "exists" or not.
To ask whether languages (an abstract notion) exists because of the nature of real computers is not entire well-defined question. Does a recursive language not exists because no existing computer can run long enough to halt? But it will halt eventually. Similarly, one can make huge finite automata that will not halt in anyone's lifetime. It will stop eventually too. Does this mean no regular language exist either because no current device can finish the calculation.
Recursive language and regular languages are just ideas computed by other abstract notions like Turing machines or finite automata. The nature of physical computers don't make ideas real.
Answer: There are some interesting points raised here.
The thing about all languages recognizable by a computer being finite is wrong. For example, you can make an interactive program that reads an input string from a user, and your program processes each character in the input stream as it is entered. We can eliminate the need to store the whole input string in memory. This means we can have an arbitrarily long input string. It is also possible to make up an infinite language and a program that recognizes the language. For example, suppose the set of alphabet is $\{0,1\}$. I can make up a language $L = 1^*$. $L$ is infinite, and it is obvious how a recognizer can be programmed. ($L$ here is still regular though.)
It is true, however, that assuming limited memory, every language recognizable is regular simply because you can view all the possible states of the memory as states of a DFA. Obviously there is an unfavorable character of this DFA - the outrageously large number of states. This, in a sense, is a reason why programming languages have control statements other than "if" and "case".
Answer: There's no fallacy. In practice everything really is regular (finite). However, you won't get much done if you treat them as such. A DFA for the reasonably long strings of an interesting language will end up having unreasonably many states.
Comment: @RogerCostello, do try constructing a DFA for the strings in language generated by $S \to () | (S) | SS$, that are at most 10 symbols long. Non-regular grammars are used because, contrary to what theorists will have you believe, they make your life much easier.
Comment: Thank you for your response. Would you elaborate on "you won't get much done if you treat them as such" please? Do you mean that we can treat a language as, say, a context-free language, even though it is really regular? And by doing so, we can have a simpler implementation? So context-free, recursive, and recursive enumerable languages are just fictitious things we create to make it easier to implement finite automata?
Comment: They are no excuse, if every language of importance were regular, every interesting computational problem would be easy to compute, which is not the case at all.
Comment: As an example why infinite languages are useful: note that that to recognize whether a program is grammatically correct is for most programs not regular furthermore there exists countable infinite valid programs over most languages
Answer: I do not agree with this. Suppose you want to check whether two graphs are isomorphic, or whether a number is prime. A priori you do not know the bound on the number of nodes or on the size of the number, hence we do need infinite languages. This however does not contradict the fact that a computer has finite memory, since a Turing machine always uses a finite amount of memory at any given time, it however can use as much memory as it wants in a finite sense, this is fair since we want to abstract out hardware. This is conform with the idea that even for general computers we assume no a priori bound on the amount of memory it has.
Comment: It's probably safe to say that $10^{80}$ (an estimate of the number of atoms in the observable universe) is an upper bound to the number of nodes or the size of the number.
Answer: I think, Carl Mummet's answer hits the point but I'd like to add the practical view because Carl doesn't mention the essence of the practical meaning of (non-)regular languages.
Remember: practice never equals theory. Different from theory, it makes more sense in practice to define language types by their efficency of memory use (to recognize a language), not the possible structure of infinite languages (infinite languages don't even exist in the real world, just think of planned obsolescence of technology, limited life spans etc., finite particles universe, so it won't make even sense to consider inifinite languages in real situations).
After all, no useful programming language is just a context-free language (it wouldn't allow for variables, although regular programming languages with turing-complete semantics exist, for example Iota and Jot or other esoteric programming languages). Useful programming languages are typically context-sensitive needed for productive semantics like namespaces. Of course, you could enumerate all possible warning-free compilable C programs which fit into 1KiB but storing them would take massively more memory, significantly more programs than particles in our universe. This is pratically impossible.
By this argument, regular languages cannot practically achieve the same like non-regular languages, even when limited to finite memory. (Parsers of) Languages of certain size cannot fit into your memory, if you try to recognize them as a regular language since the regular expression will grow large, in the worst case (for totally random words) almost linearly with the number of words in the language! Whereas infinity in practice means finity in theory. But with something like a Linear bounded automaton, you can use finite memory to recognize languages containing exponentially (or more?) words. Of course, regular languages are FAST but without a certain efficiency of memory use you won't be able to detect languages at all in practice!
And practice also tells us, that computers cannot process infinite languages with certain complexity. If the program requires unboundedly growing memory to recognize the language. Except for control systems which are LTI-filters or digital hardware automata, it concerns most interesting infinite languages since with finite memory, you could only compress infinite languages into finite space which is possible for finitely bounded languages as well. You really need infinite memory to make use of the power of parsing infinite languages but then what should be the use for us human of an infinite result, even if it's effectively infinite by the notion of infinity due to very long processing time?
So actually, the set of infinite languages that a computer could really recognize in practice are very limited at all. It can be even doubtful, if any reasonable or good computer software should parse infinite languages since maintenance is a relevant factor (everyhwere) as well as limited lifetime of the CPU.


php if/elseif not working at all

Question: The page that calls this script allows the user to pick from 1 to 5 fields. The idea is to add up the number of fields selected and fetch the appropriate results. No matter how many fields are selected from the form the if/elseif statements do not work and I cannot see the problem.  Any help would be greatly appreciated.
<code>$sql = "SELECT * FROM my_table";
$result = $conn->query($sql);
$fields_select = 0;
if($country_type != "") {
  $fields_select = $fields_select + 1;
  $winearr[] = "\$country_type";
  $winearr[] = "Country";
}
if($region_type != "") {
  $fields_select = $fields_select + 1;
  $winearr[] = "\$region_type";
  $winearr[] = "Region";
}
if($wine_type != "") {
  $fields_select = $fields_select + 1;
  $winearr[] = "\$wine_type";
  $winearr[] = "Type";
}
if($rating_type != "") {
  $fields_select = $fields_select + 1;
  $winearr[] = "\$rating_type";
  $winearr[] = "Rating";
}
if($vintage_type != "") {
  $fields_select = $fields_select + 1;
  $winearr[] = "\$vintage_type";
  $winearr[] = "Vintage";
}
if ($result->num_rows > 0) {
  if ($fields_select == 0) {
    echo "No Results Found In Search";
  } elseif ($fields_select == 1) {
    while($row = $result->fetch_assoc()) {
      if($winearr[0] == $row[$winearr[1]]) {
        makeListing($row); // call the function
      }
    }
  } elseif ($fields_select == 2) {
    while($row = $result->fetch_assoc()) {
      if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]]) {
        makeListing($row); // call the function
      }
    }
  } elseif ($fields_select == 3) {
    while($row = $result->fetch_assoc()) {
      if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]] && $winearr[4] == $row[$winearr[5]]) {
        makeListing($row); // call the function
      }
    }
  } elseif ($fields_select == 4) {
    while($row = $result->fetch_assoc()) {
      if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]] && $winearr[4] == $row[$winearr[5]] && $winearr[6] == $row[$winearr[7]]) {
        makeListing($row); // call the function
      }
    }
  } elseif ($fields_select == 5) {
    while($row = $result->fetch_assoc()) {
      if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]] && $winearr[4] == $row[$winearr[5]] && $winearr[6] == $row[$winearr[7]] && $winearr[8] == $row[$winearr[9]]) {
        makeListing($row); // call the function
      }
    }
  }
}
/* Debug */
echo $winearr[0]."-".$winearr[1]."-".$winearr[2]."-".$winearr[3]."-".$winearr[4]."-".$winearr[5]."-".$winearr[6]."-".$winearr[7]."-".$winearr[8]."-".$winearr[9];
echo "<br>\$fields_select=".$fields_select;
</code>
Comment: Did you do any debug? What's the value of `$fields_select`?
Answer: From your code I gusset you are trying to search something by php which is not correct. Try to search by your query and let your database handle the search.
<code>$sql = "SELECT * FROM my_table WHERE ";

if($country_type != "") {
    $sql .= 'Country = "' .  $country_type .'"';
}
if($region_type != "") {
    $sql .= 'AND Region = "' .  $region_type .'"';
}
.
.
.
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
            makeListing($row); // call the function
    }
}
</code>
in the end fetch your result.
Comment: Thanks for the reply Saeed Am.  The visitor needs to look up a wines by all kinds of different criteria.  I can access with just one simple statement.  This database need a much more complex combination of possible ways to search.
Comment: I didn't understand you saying " I can access with just one simple statement." but if you have access to database for avoiding any complexity you can use `FULL TEXT INDEX` on several columns and then use `MATCH() ... AGAINST ` statement. I'm assuming you use MySQL.
Comment: another thing, I don't know what are you trying to do with this `$winearr[] = "\$country_type";` you can simply do this `$winearr[] = $country_type`
Answer: Resolved - The problem is incorrect coding. $winearr[] = "\$country_type"; returns $country_type instead of the variable that was selected.  Instead of $country_type being equal to Australia, is was literally $country_type every time no matter want was select.
<code>$winearr[] = "\$rating_type";
</code>
should have been
<code>$winearr[] = $rating_type;
</code>
The routine now works exactly as it should.

php if/elseif not working at all


How can I imagine double/repeated root of a quadratic equation?

Question: A quadratic equation such as $(x-2)^2=0$ has a repeated root $(2,2)$.
A lot of things in math (equations, matrixes and so) can be nicely drawn on a $2D, 3D$ etc plane (with $x$-$y$ axis).
I mean, I though there is a relation between algebraic equations and geometry, but in this equation, $(x-2)^2$ is a parabola with clearly only one point that lies on an $x$ axis? How could I understand, that there are two roots then?
Also with the imaginary roots I have found ways how to draw it, but it was just something like - how to find the roots with geometry, not something as logical and simple as when a parabola graph penetrates $x$ axis.
Is it because the real result is not exactly a parabola that we can draw on a $x$-$y$ plane or why?
Just for info - I know how to solve it and all the rules, I am really just asking on how to understand it geometrically.
Thanks a lot
Comment: It would be clearer if you said that $(x - 2)^2 = 0$ has a repeated root at $x = 2$.
Answer: Easiest way to understand it imo, is to consider the quadratic function
$f(x)=(x-2)^2+c$
Edit: I think it's important to point out here that changing the value of $c$ translates the graph of $f$ vertically.
For small values of  $c<0$. You will notice that there are two roots, but that as $c$ gets closer to $0$ those roots are getting closer not only to each other, but also to the vertex of the parabola. When $c=0$ the roots now coincide, and you have what is known as a double root or repeated root. (This concept can be further generalized for higher degree polynomials and is known as multiplicity of a root; it conveys certain information about relative behavior of the graph around the given root.)
If you continue to considering $c>0$, you no longer have real roots, but there are complex numbers which can still satisfy the equation.
Answer: Try to interpret (x-2)^2 = 0 as the intersection of y = (x-2)^2 and y = 0. You will find the latter is tangent to the parabola.
You can further imagine that one half of the tangent is running from – infinity towards (2, 0) and the other half is running from the + infinity towards the (2, 0).
Comment: Ok, but in books they say parabola has one vertex. Only one.
Comment: @TomasS The theory is just the same as a straight line touches a circle. They will cut each other at one single point … but when solving the resultant quadratic equation (combined from the linear equation of the straight line and the second degree equation of the circle), we end up with 2 but equal roots. The converse of the above is also true
Comment: The two roots are the same point. That point is the vertex. This is only true for parabolas tangent to the x-axis.
Comment: Also either there is a problem, that the roots are two but we cannot draw it on our 2D plane basically or the vertex is really just one, and the root also, we only cannot describe it with equations in another way than to make two out of it? I get all the facts and can solve it. Its just my couriosity, i just tried it, if there is anyone who was already thinking about it this way and found something interesting. Thanks for answers btw!


fail2ban filter for ical regex

Question: i am trying to get a regex for an ical service on my host working without success. This is a part of the logfile:
Tue Jul 23 13:55:23 2019: ical|T720] [info   ] Accepted connection from [::ffff:188.8.131.52]:56450
Tue Jul 23 13:55:23 2019: [net/[::ffff:5.6|T5234] [error  ] HrLogon server "http://localhost:123/" user "Admin": logon failed
Tue Jul 23 13:55:23 2019: [net/[::ffff:5.6|T5234] [warning] Login failed (0x80040111 logon failed), resending authentication request
Tue Jul 23 13:55:23 2019: [net/[::ffff:5.6|T5234] [notice ] [::ffff:126.96.36.199]:56450 - Admin [23/Jul/2019:13:55:23 +0200] "GET / HTTP/1.1" 401 0 "-" "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1"
Tue Jul 23 13:55:23 2019: [net/[::ffff:5.6|T5234] [info   ] Connection closed

This is the part of the log file and i tried already different things to get this into a filter. The important parts are "Login failed" and in the next line the part with the IP.
But how can i get this working?
Any help would be great!!!
Thanks in advance
icey
Actual configs looking like:
ical.conf:
[INCLUDES]
before = common.conf

[Definition]

failregex = ^*Login failed\n^.*\[notice \] \[::ffff:<HOST>\]$

ignoreregex =
[Init]
maxlines = 2

and the jail conf:
[ical]

enabled = false
port = 8443
filter = kopano-ical
logpath = /var/log/ical.log
maxtetry = 3
bantime = 3600

Comment: Welcome to Server Fault! What are the "different things" you have  tried? What did you expect to happen? What happened instead? What does your config look like?
Comment: Hi Jenny, thanks for your answer. The purpose is that the ip is beeing banned as in the config:
`[ical]
enabled = false
port = 8443
filter = ical
logpath = /var/log/ical.log
maxtetry = 3
bantime = 3600`
The filter conf looks like this:
`[INCLUDES]
before = common.conf

[Definition]

failregex = ^*Login failed\n^.*\[notice \] \[::ffff:\]$

ignoreregex =
[Init]
maxlines = 2`
Comment: It's very hard to read the config when it's in a comment - please instead click the "edit" link below the question, and add the config there. Then use the `{}` button to format it as code, so it will be easier to read.
Comment: hope it is better now, sorry for the trouble..
i tried around with several expression variants but i am not able to get the expression written that it finds the correct part in the log file.
Answer: I believe your regex is not correct. You're missing dot (.) at the beginning right after ^, .* before \n and since you used $ and the end you need to put .* before $, ] is not the last character.
failregex = ^.*Login failed.*\n^.*\[notice \] \[::ffff:<HOST>\].*$

Comment: Thanks Ergec, it seems to work fine :) Thanks a lot!!

fail2ban filter for ical regex


Zoom JPanel in Java Swing

Question: I have an existing Java Swing application.  In the middle of the application is a single JPanel which I want to be able to zoom in and out of.  The JPanel has a number of JComponents on it (mostly other JPanels and JLabels).
Also mouse position will need to be adjusted appropriately as well - so mouseevents need to remain same even after the JPanel has been zoomed.  As such simply changing the paint methods of each component doesn't seem plausible.
EDIT:

OK i kind of got it working using the MagnifierUI class with some minor edits.  However the magnified panel I create has the wrong mouseevents - i.e. the panel is scaled, mouseevents are not.
Comment: I've had it packaged it [here](https://www.dropbox.com/s/re1hmvypp19oqy1/JXLayer-PBJar-Demo.zip). Check out the `TestWrapped` demo in PB's Jar...
Comment: *"Any suggestions?"*  Leave this to user choice of screen resolution or the OS' inbuilt screen magnification utility.  If the user needs it, they'll know where to find it.
Comment: JXLayer can do this.  Getting hold of an example (or even JXLayer itself) is problematic now days
Comment: I should mention, I have tried the following methods 1) [Utils4Swing5](http://javadeveloperslife.wordpress.com/2009/07/18/zooming-swing/) which does not work at all.  2) I have also attempted Peit Blok's method using JXLayer and PBTransform - however Peit Blok appears to have left the planet and I can no longer find the jar necessary for PBTransform [link](http://www.java.net/node/700255)
Comment: @MadProgrammer yep I have tried using JXLayer (and JLayer) but TransformUI appears to be the only UI class that can be used with JXLayer to zoom and it is strangely absent from the internet (as Peit Blok, its developer, appears to have shut up shop)
Comment: @MadProgrammer Sweet! I'll give it a try, report back later today - exactly what I was looking for!
Answer: This is just a scetch:

in your JPanel keep track of an AffineTransform which represents the scale factor (see AffineTransform.scale(double,double),
override the paint method of your JPanel: before calling super.paint apply the affine transformation to your Graphics2D object (cast from the parameter of the paint method) by calling Graphics2D.setTransform(AffineTransform), call super.paint afterwards
override the methods processMouseEvent, processMouseMotionEvent and processMouseWheelEvent, apply the affine transformation to the coordinates of their mouse event parameter (AffineTransform.transform(java.awt.geom.Point2D,java.awt.geom.Point2D)), call respective super-method afterwards.

Hope this helps.
Answer: Try SwingUtilities.convertPoint(source, point,destination);

Zoom JPanel in Java Swing


remove drupal admin menu from actual site

Question: i'm using drupal 7 and i want to hide the admin toolbar from the normal sites. but in the configuration i can only find the option to disable the toolbar completely. what i want is that it is only visible on "mysite.com/admin/" and removed from the actual website.
i found some drupal modules with which you can collapse the toolbar or hide it by pressing the UP key but what i want the complete admin toolbar markup gone on my actual site.
i'm removing all the drupal system css and js anyway (using the template.php file) so even if i wanted the admin toolbar on my sites it would look messed up because of the missing styles and scripts.
any ideas?
Answer: You can remove the toolbar from the "normal" part of you're site by unsetting its entry in the $page array using hook_page_alter. You can do this in either a module or a theme.
function mymodule_page_alter(&$page) {
  unset($page['page_top']['toolbar']);
}

Answer: You can use the function admin_menu_supress() to remove the admin menu from a specific page. It can be called from almost anywhere.
Reference - https://www.rit.edu/drupal/api/drupal/sites!all!modules!admin_menu!admin_menu.module/function/admin_menu_suppress/7.43
Answer: The admin toolbar is only visible when you log in as admin; for the normal users, this toolbar will not be display.
Comment: Not true...any role can be granted the 'Use the administration toolbar' permission.
Comment: ok, But For the questioner don't want admin toolbar for the normal users.He needs only on /admin.Thats why i said like that.
Comment: What if his users have access to *some* parts of the admin section but not others? The downvote was perhaps a bit harsh though, I've removed it
Comment: i did indeed want to remove it for the admin as well, so that it's removed no matter which role you are.
Comment: If it so, then "Toolbar" is a module, you can go to modules and uninstall the toolbar module.
Comment: i meant for the admin role, not on the admin site. it should be there on the admin sites and it should be gone on the normal sites (for every user no matter which role)


Does a homomorphic image of even permutations consist of even permutations?

Question:
If $f:S_n \to S_n$ is a homomorphism, prove $f(A_n) \subseteq A_n$.

If every image of a transposition is even, then there is nothing to prove, but it is not sure..
How can I prove the problem?
Comment: Hint: What are the homomorphisms from $S_n$ to $C_2$ (are there any others than the sign?)
Comment: @Tobias Kildetoft what is $C_2$?
Comment: cyclic group of two element
Comment: I know the homomorphism, he says. But isn't it not relative to the given homomorphism f?
Comment: $$\;1\lneq N\lhd G\;,\;\;N\lneq G\;\implies \exists\;k\in\Bbb N\;\;s.t.\;\;G_k\rlap{\;\,/}\subset N $$

Well, take a peek at $\;G_k\cap N\lhd G_k\;$ . By the above, it must be $\;G_k\cap N=1\;$ and etc.
Comment: $$G_1\subseteq G_2\subseteq G_3\subseteq \dots\subseteq G_n \subseteq G_{n+1}\subseteq \cdots$$

Are all simple groups. Prove that $$G=\bigcup_{n=1}^{\infty}G_n$$ is also a simple group.
Answer:
$A_n$ is the set of products of an even number of transpositions

this is one common definition of $A_n$

$A_n$ is the set of products of products of two transpositions

just group pairs of transpositions

$A_n$ is the set of products of 3-cycles

$(12)(23)=(123)$, $(12)(34)=(123)(234)$

$A_n$ is the set of products of squares

$(123)=(132)^2$ and the square of every permutation is even

$f$ maps products of squares to products of squares

$f$ is a homomorphism

$f$ maps $A_n$ into $A_n$.
Comment: I've followed an argument from MacLane–Birkhoff *Algebra*, where they prove that $A_n$ is a characteristic subgroup of $S_n$ using that it is generated by squares. Why don't they conclude that $A_n$ is fully invariant as above??
Comment: $A_n$ is the *set* of squares for $n\le 5$. See http://oeis.org/A003483.
Comment: Wow! Your answer is very constructive. Thanks a lot:)


Java program question

Question: import java.util.*;

public class Guess
{
    public static void main (String[] args)
    {

        final int MAX=10;
        int answer, guess;

        Scanner scan = new Scanner(System.in);
        Random generator = new Random();

        answer = generator.nextInt(MAX)+1;

        System.out.print ("I'm thinking of a number between 1 and " + MAX + ".Guess what it is: ");

        guess=scan.nextInt();

        if (guess==answer);

            System.out.println (" You got it!");
        else
        {
            System.out.println("That is not correct");
            System.out.println("The correct answer is"+ answer);
        }
    }
}

When I try to compile this I get an else without if error, I cant see why because I only have one if condition and that else is right after the if. Help please, and also could someone explain this line answer = generator.nextInt(MAX)+1; why did the author from the book added 1?
Answer: You have an error there.
if (guess == answer);
    System.out.println(" You got it!");
else {
    System.out.println("That is not correct");
    System.out.println("The correct answer is" + answer);
}

should be
if (guess == answer) {
    System.out.println(" You got it!");
} else {
    System.out.println("That is not correct");
    System.out.println("The correct answer is" + answer);
}

The author added 1 to ensure the value would be at least 1. nextInt(MAX) returns 0 to MAX-1.
Answer: This line is the culprit:
if (guess==answer);

Remove the semicolon; it is terminating the entire if statement.
Answer: if (guess==answer); // looks like you threw an extra semicolon in here
        System.out.println (" You got it!");

Just remove the semicolon and you'll be fine.

Help please, and also could someone
  explain this line answer =
  generator.nextInt(MAX)+1; why did the
  author from the book added 1?

generator.nextInt(MAX) will generate a random number between 0 and MAX, and the author wanted it to be at least 1, so he added 1 to it.
Comment: It happens to everyone. Some tools (like the NetBeans IDE) can point out semicolons that do nothing, which in this case would have prevented the problem.
Answer: you have an unecessary semicolon here
if (guess==answer);

Answer: Your if statement needs brackets, not a semicolon.
Answer: The if statement should look like this:
    if (guess==answer) {
        System.out.println (" You got it!");
    } else
    {
        System.out.println("That is not correct");
        System.out.println("The correct answer is"+ answer);
    }

The random value is incremented because the random generator creates random numbers between 0 and MAX-1.
Answer:
Remove the smeioclon after the if
condition. You don't necessarily have to have the curly braces since it's just one statement after the condition. If you have more than one then you have to include the curly braces around the statements like you have in your else condition.
Lookup the Random class in the
javadocs.
Comment: Which `if` condition? As it stands, your answer is rather vague.

Java program question


Data Provider annotation of Testing

Question: I'm new to Selenium...
Can anyone please explain me Data Provider annotation of Testing in easy way with examples.
P.S.: I have searched in your site for this topic but I didn't get the basic leveler explanation
Your help is much appreciated.
Comment: Hello and welcome to Stack Exchange. Please consider taking the [tour] and going through the help center.
Comment: Read [this](http://stackoverflow.com/help/how-to-ask). Reviewers will likely reject your question because it is too broad and shows too little research. Suggest you google *selenium data provider annotation*.
Answer: hi to understand data provider read below
Marks a method as supplying data for a test method. The annotated method must return
an Object[][] where each Object[] can be assigned the parameter list of
the test method.The @Test method that wants to receive data from this DataProvider needs
to use a dataProvider name equals to the name of this annotation.

for more info go to official url http://testng.org/doc/documentation-main.html
Answer: The @DataProvider annotation is a TestNG feature, not Selenium.   The data provider allows you to pass an entire row of test data, from a spreadsheet, directly into your test method, OR you can pass a instance of webdriver (generated inside the dataprovider method, complete with desired Selenium capabilities) directly into each method under test.   Also, in @Before annotations, you can access things coming from data provider and make setup decisions before your test starts.  For, example, your if CSV row data contains a particular environment name, you can call a environment test fixture based on that value, before the test starts.
The HOW of how it works, is partially explained in the above link.

Data Provider annotation of Testing


Where to put a script to provide AJAX/JSON response?

Question: I'm using drupal 7. I want to create a php script that uses Drupals DB abstraction layer to query the database and spit out JSON data.  Where would I place such a script?  At the moment, I've done it in a round-about way by create a new node, then in the function theme_process_page() of my theme/template.php, I wrote an IF statement to detect the node id, then run my code, then call a die() statement.
Is there a more appropriate place for me to put this script?
** additional notes **
This script is to be called every time a person presses "Provide a menu link" when adding/editing a node in the CMS.  The script will then automatically select the appropriate Parent Item and weight based on any other existing translation.
Comment: Can you clarify a little more what is the purpose of your Ajax script ? When should it be called ? Is it after the insertion of a new node, before loading a node ?
Comment: @tostinni - ok more info added.
Answer: The easiest is to use Views datasources if it can solve your problem, in essence this means that if you can use views to display the data you need, you can use this module to return it as JSON.
Another option is to write a custom module and use hook_menu to define a 'menu' item which you can use from the calling code. To return your data as JSON you can use the standard php functions.
If you need multiple scripts and advanced configuration you can always have a look at Services or
Comment: Ok, i'm looking at module.   I want to expose a destination url for my ajax call.  How would I do it?
Comment: Drupal provides http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_json_output/7 for outputing JSON.
Comment: With all 3 solutions outlined above you can expose any url you want for the callback


paypal express checkout notify url without api

Question: I have a situation I am unable to fine the answer. I am using Paypal Express checkout method by simple form method not api . when user/buyer reaches the paypal payment page and after successful payment it give user/buyer two button option ( your paypal account ) - ( return to site) If user returns to site good enough get all the transaction details but incase he does not there is no way to capture the transaction result. Is there a return url that can be specified in the html express checkout method also does it require the seller to enable Ipin in his account or is it enable by default .
My issue is its a thirdparty application where seller adds his paypal account to accept payment but one successful payment it needs to return the website . issue cant ask seller to enable any specific things to his paypal account as if he does or does not there is no way for me to verify while he sets up the account to my service or platform .
Answer: You need to be using Instant Payment Notification (IPN) to handle that instead of Payment Data Transfer (PDT).  They're essentially the same thing except that PDT only works on the return URL (which isn't guaranteed to get hit as you're finding out) and IPN will be triggered in the background regardless of whether or not the buyer makes it back to your return URL.
You can include the "notify_url" parameter in your HTML form code to pass the URL you'd like the IPN's to get sent to.  This will override any setting the merchant might have setup in their own PayPal account.


fetching facebook user's friends list

Question: I made one android app which will fetch all friends of logged in user of facebook.But it is not fetching all the friends.Can anyone tell what is the issue and help me with the correct process.Right now i am using the below code.
Request rt=Request.newMyFriendsRequest(session, new GraphUserListCallback() {
<code>        @Override
        public void onCompleted(List<GraphUser> users, Response response) {

            if(response.getError()==null){

            ListIterator<GraphUser> graphUser=users.listIterator();
            ArrayList<String> friends=new ArrayList<String>();
            while(graphUser.hasNext()){
                GraphUser friendObject=graphUser.next();
                friends.add(friendObject.getName());
            }
            System.out.println(friends);

            TextView listOfFriends=(TextView) findViewById(R.id.welcome);
            listOfFriends.setText("hello"+friends);
            }
            else{
                Toast.makeText(MainActivity.this, response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show();
            }

        }
    });
    rt.executeAsync();
</code>
please suggest me what should i do?
Answer: If you created your app after 04/30/2014, you're forced to use Graph API 2.0, which means you will no longer get a full list of friends. Instead, you will only get friends that are also using your app.
Comment: Thanx for your valuable comment.So can you suggest me what should i do for getting full friend list?
Comment: You can use something like taggable_friends - https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends - but your app's usage of this permission must be reviewed by Facebook.
Comment: Can you please share guidelines for reviewing application in facebook
Comment: https://developers.facebook.com/docs/apps/review/login
Comment: 1.Can you explain about Privacy Policy URL and how to generate it?
2.Can you give some sample Privacy Policy URL?
3.Is it possible to give demo application for review?

fetching facebook user's friends list


Ubuntu 10.04 CPU Throttling

Question: I have an old laptop I'd like to repurpose as a print/SSH server (among a few other light tasks).  The laptop has a 2.0GHz Pentium M processor with 1GB of RAM (to be specific, its an old Dell Precision M60).  The system is running Ubuntu Server 10.04.  A combination of htop and my screen config show that the CPU is constantly running at its full speed, even when under little/no load -- this was not an issue under 9.04 and 9.10.  I'd like to drop the speed of the processor down to save on power, heat, and noise.
Is there any way that I can force the system to only run at 600MHz.
Answer: You could under clock the processor at the hardware level through BIOS.  Here's a guide for overclocking that specific model (you'll want to do just the opposite ;):
http://www.overclockers.com/forums/showthread.php?t=277264
I wouldn't trust software that claims to do this but that's just a personal BIOS (lame pun).  I've seen it done for video cards.
Comment: I've poked around in the BIOS for the P-M60 a bunch, but never seen anything for setting the CPU speed only.  Unfortunately, Intel processors are always multiplier-locked, so I'd have to downclock the entire system to do this.
Comment: Yes, downclocking the entire system would be the outcome.
Answer: You don't need to use the BIOS.  There's some stuff in /sys/devices that'll set the CPU Scaling factor
Have a look at this guide: http://embraceubuntu.com/2005/11/04/enabling-cpu-frequency-scaling/
It can explain more than I can easily
Comment: This stuff was working in versions previous to 10.04 automatically.  I think 10.04 broke something.
Comment: Odd.  I'm sure I've had it working on a 10.04 server.

Ubuntu 10.04 CPU Throttling


A tarefa "Xamarin.Forms.Build.Tasks.GetTasksAbi" não foi carregada do assembly

Question: Esse é o erro que estou pegando:

C:\meu_caminho\packages\Xamarin.Forms.22.214.171.124203\build\portable-win+net45+wp80+win81+wpa81\Xamarin.Forms.Build.Tasks.dll.
  Confirme se a declaração  está correta, se o assembly e
  todas as suas dependências estão disponíveis e se a  tarefa contém uma
  classe pública que implementa Microsoft.Build.Framework.ITask.

Abaixo o código fonte do xaml.cs
<code>[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        public LoginPage ()
        {
            InitializeComponent ();
        }

        public  void Login_Clicked(object sender, EventArgs e)
        {
            LoginService svc = new LoginService();
            LoginRS res = svc.Login(txtUsuario.Text, txtSenha.Text);
            if (res != null && res.Success  )
            {
                App.LooggedUser = res;

                Application.Current.MainPage = new MainPage();
            }
            else if(res != null && ! res.Success)
            {
                lblErroLogin.Text = res.Exception;
            }
            else
            {
                lblErroLogin.Text = "Não foi possível realizar o Login, por favor verifique sua conexão com a Internet";
            }
        }
    }
</code>
Antes estava dando o erro abaixo no InitializeComponent

Unhandled Exception:  System.TypeLoadException: Could not resolve type
  with token 01000043 (from typeref, class/assembly
  Xamarin.Forms.Internals.ResourceLoader, Xamarin.Forms.Core,
  Version=18.104.22.168, Culture=neutral, PublicKeyToken=null) ocorreu

Como faço para resolver esse problema?
Answer: Erro MSB4062: a tarefa "Xamarin.Forms.Build.Tasks.GetTasksAbi" não pôde ser carregada a partir do assembly
Olá.
Resolvi meu problema montando o projeto (arquivo-para-arquivo) e compilando e conseguindo acompanhar o problema.
Uma biblioteca de solução exigiu o pacote Microsoft.Bcl.Build no projeto que faz referência (a aplicação no meu caso).
Acabei de instalar o pacote via nuget e tudo está bem ...
Eu espero que isso ajude.
Answer: Duas coisas indispensáveis para se fazer usando Xamarin em caso de problemas:

Limpe a solução.
Reinicie o Visual Studio.


AWS Cognito Userpool via cloudformation file

Question: I am trying to code my cognito userpools as cloudformation templates. I am running into one open question however: how to define standard attributes? Will Cognito know that birthdate in Schema is meant to be the standard birthdate - and validate it as such? How is the attribute Schema defined in the cloudformation template mapped to the standard, non-custom attributes like email, birthdate, ...?
More details: AWS Cognito separates between standard attributes and custom attributes. This separation is amongst other things important because standard attributes are validated for their format: email and birthdate for example accept only an AWS defined, specific format.
Thus my question: how does AWS Cognito map the cloudformation Schema defined attributes to standard AWS Cognito attributes? Does it at all, and if so by identity of the attribute name?
Also see:
AWS Cognito Cloudformation Schema
Example created by someone: Cloudformation example
Comment: Be careful when updating schema via cloudformation though, it will redeploy your whole userpool
Answer: You need to use the SchemaAttributes property. For standard attributes they must be named according to the Open ID Connect specification -
http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
http://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html
By doing this they will map appropriately and you can set other properties on the property such as Required. It appears the docs need to be updated to make this more clear.
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html
Comment: What an absolute travesty of documentation. Thanks for your explanation!
Comment: Do you need to define every standard attribute in `Schema`? In order to be able to use them in an `AWS::Cognito::UserPoolClient`'s `ReadAttributes`
Comment: Thank you, but to my understanding this does not solve my issue. First: there are only `Schema` and `AliasAttributes` properties, I assume you are speaking of these. Now `AliasAttributes` supports only 3 values for phone, mail, username - to my understanding intended for cases where you want aliases. Which I don't - my question more simply put: how to define _standard_ attributes? Will Cognito know that `birthdate` in `Schema` is meant to be the standard `birthdate` - and validate it as such?
Comment: I had to try this a few times, so just wanted to summarize this to save anyone else a few minutes. This was exactly what I wanted though.

If you want to say make 'email' a standard attribute 'required', add it under Properties > Schema and use Name: 'email' (from openid) like they said
Comment: Updated answer.
Comment: Thanks! Due to the convoluted namings I am still not sure if we understand each other. On the root level of the `AWS::Cognito::UserPool` resource in cloudformation you only have `Schema` and `AliasAttributes`. Now `Schema` is a list of `SchemaAttributes`. Thus your answer is what I am implying in my question: that `SchemaAttributes` will be mapped by their name to the standard attributes - and validated accordingly.
Comment: Correct. You need to map each standard Cognito attribute by setting the SchemaAttribute's name to the standard name of the attribute following the Open ID Connect standard naming, as is shown in the two links I provided. Does that help clarify?


HTML5 edit text on the canvas

Question: I'm trying to create something similar to http://www.listhings.com where you can edit the text within the canvas.
I've read the other post HTML5 Canvas Text Edit . But I don't want to edit the text outside of the canvas. I want to edit the text within the canvas.
I'd appreciate if anyone can point me in the right direction.
Thanks
Answer: First, Mohsen correctly points out that when you do context.fillText you are actually "painting a picture of letters" on the canvas. It's not like a word processor!
You can capture the key events on the window and then write the keystrokes out to your canvas.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/7tXd4/
This example ONLY types lowercase a-z (no capitals, spaces, backspaces, etc)
You will probably want to make more enhancements like these:

Adding more keys (A-Z, 0-9, etc).
Respond to command keys like backspace to  remove letters from the keyHistory.
Put a cursor so users know where they are on the line as they type (hint: http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/)
If you allow multi-line text, handle the [enterkey] and move to the new line.
Etc

Here's code just to get you started:
<!doctype html>

<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />

First click in the red canvas below

Then type any lowercase letters from a-z

    <canvas id="canvas" width=300 height=100></canvas>

Comment: There is more better solution for keys handling with not only english letters:
function keyPressHandler(event) {
    addletter(String.fromCharCode(event.charCode));
}
Comment: @albertxing: Nice! Thanks for sharing.  I especially like the "code typing" you use as an intro.
Comment: Thanks, I appreciate your feedback. How come I can't @mention you?
Comment: Correction for the above comment: `String.fromCharCode(event.keyCode)`
Answer: fillText() do not create an object or text node that you can edit afterwards. It will fill text on canvas, that means it will leave pixels on canvas.
You can use Canvas libraries like http://kineticjs.com/ to have a single layer for that text so you can erase the layer and retype the text in. Kinect allows you to bind values to layers so you can save the text you have in the layer in a value binded to the layer.
Answer: Try this solution https://jsfiddle.net/tabvn/zjyoexf1/
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Canvas Input Element</title>

    <canvas id="draw" width="500" height="500"></canvas>

Comment: @Simeon it's ok
Comment: Welcome to SO, please add provide some explanation to your answer that simply describe how your solution solves the problem and avoid posting code only answers.
Comment: :) i noted that
Comment: @Toan, is it allowed to reuse your code example above in an CC0 way?

HTML5 edit text on the canvas


Overfitting during epochs

Question: Especially in deep learning, the validation accuracy of a model usually not only plateaus but decreases when it starts overfitting. Because we only measure the validation accuracy after each epoch, wouldn't it be possible for a model to start overfitting during an epoch?
From my understanding, this could be a significant problem if there is a lot of similar data available but I haven't found any material about it and have never seen such an approach in practice. Is there a reason besides computational cost that we only ever validate our models after an epoch? And would it make sense to check validation accuracy every n batches rather than epochs if you are trying to get the last bit of performance out of a model (e. g. for a Kaggle competition)?
Comment: Keras, by default, checks after each epoch.  Not sure if that setting can be twiddled.  In my own implementation I have it check after every $k$ passes, where $k$ is an argument.  Or course keras is faster, but mine works better for my particular problem.
Comment: I am pretty sure it can't be changed right now but there is ongoing discussion over at the [keras github repo](https://github.com/keras-team/keras/issues/2850). I will definitely try this because epochs are relatively arbritrary as @JanKukacka said.
Answer: There is no particular theoretical reason behind evaluating after each epoch.
"Epoch" is often used as a somewhat magical term, but there is really nothing magical there. Epoch simply means $\frac{N}{K}$ mini-batches, where $N$ is dataset size and  $K$ is the mini-batch size. When the data augmentation is employed (usually the case with deep nets), the argument that "during an epoch every training sample is used" becomes invalid since new samples are generated every time. So if you want to get every little bit of your model, evaluate after every batch (if you have the time)1.
Usually, deep nets don't overfit so fast (even though in theory, the scenario you described could happen), so evaluation at the end of every epoch is simply convenient.
In practice, you could save weights' snapshots after every epoch and if you notice the overfitting starts within some particular epoch, you can just start from the last snapshot before it and this time evaluate after every batch.

1 Note that in this case you start simply overfitting to the validation set. There may be even inferior effect on the test performance.

Overfitting during epochs


Can get Play 2.2 details when running JUnit testing with Play 2.3

Question: I'm having issue with play framework and JUnit test with play 2.3
When running: "activator test" then it runs fine, but...
[info] Loading project definition from /.../test/toto/project
[info] Set current project to toto (in build file:/home/jenkins/.../)
[info] Compiling 6 Java sources to /home/jenkins/automated_tests/.../toto/target/scala-2.11/test-classes...
[warn] application - do execute tests in class utils.UtilsTest
[warn] application - do execute tests in class test_marketcity.BasicTest
[info] Passed: Total 14, Failed 0, Errors 0, Passed 14
[success] Total time: 29 s, completed Feb 12, 2015 9:48:51 AM

There's nothing about the test which have been run, only the full total of test (14 here). With play 2.2 I had a more detailled log containing also each test:
[info] x firstTest (x means here it failed)
[info] + secondTest (+ means here it succeeded)

Should I have to put a specific option here to get more details ?
Thx
Answer: It is a common issue with tests on activator. I usually run activator clean before tests to get the output. Sometimes running tests from sbt helps.


Launch EC2 instance with more than 8G of disk space

Question: It seems that by default EC2 instances get launched with an 8G EBS volume attached.
Is there an easy way to launch an instance with a bigger EBS volume?
Answer: Sure - you can define the volume size at launch time.  If you're using the web console, it's step 4 of the launch ec2 instance wizard ("Step 4: Add Storage").  Simply edit the "Size (GiB)" value for the root ebs volume and launch as you otherwise would.
The OS will come up with an 8gb filesystem on a volume of whatever size you specified - simply resize the filesystem (amazon linux defaults to ext4, so that'd be resize2fs /dev/xvda1 - amazon linux 2 defaults to xfs, so that'd be xfs_growfs /).
Voila
Answer: I suggest you can select extra storage once you creating your ec2 instance, in my case there was extra nvm-e included that I would like to use.
There is "Additional launch parameters - optional" in launch parameters.
Then you can increase your EBS volume.


Sort by weight using \Drupal::entityQuery()

Question: I want to get all taxonomy term in $lang language, following snippet works correctly and return all terms of $lang code.
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

Then I want get results in order that in the taxonomy list they are, try to sort them with $query->sort('weight','ASC'); but with following snippet the results are  the same before adding sort.
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $query->sort('weight','ASC');
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

Does anybody know where the problem is? How can I get terms in order they are in  taxonomy list?
Answer: Taxonomy overview list uses something like:
  ->sort('weight', 'ASC')
  ->sort('name', 'ASC')

If that doesn't work for you, take a look at \Drupal\taxonomy\TermStorage::loadTree
Comment: thansk for your attention, but not worked
Comment: in my question I write down sort by weight, adding another sort by name couldn't help. **This is not WORKS**
Comment: I confirm that it works for a flat list only.
Answer: As was previously suggested, taking a look at \Drupal\taxonomy\TermStorage::loadTree is helpful. Entity Query only provides access to properties of the entity and its Field API values. Since the weight of the term is available in the taxonomy_term_field_data table, it will be available to entityQuery as well. However, any nesting of terms, aka hierarchy, will require access to the taxonomy_term_hierarchy table. That would require a database query.
You can access it via a database query, as seen in loadTree, line 204:
    $query = \Drupal::database()->select('taxonomy_term_field_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $result = $query
      ->addTag('taxonomy_term_access')
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->condition('t.default_langcode', 1)
      ->orderBy('t.weight')
      ->orderBy('t.name')
      ->execute();

I have updated the query to use Drupal's container, rather than the dependency injection so it can be used more readily. You should be able to modify this to fit your needs if Entity Query is not working as you desire it to.


Como passar os dados de um switch button para outra acivity?

Question: Estou desenvolvendo uma aplicaçao mobile no AS que tem uma lista de cardviews. Nesses cards tenho um switch button que ao clicar em ON abrirá um alert dialog para confirmar a mudança de status. Porem estou com problemas ao passar as informaçoes, acredito eu, do switch button, tanto é que me retorna o erro abaixo:

O layout do meu cardview onde tem o switch button:
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:id="@+id/cv">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp">

        <ImageView
            android:src="@drawable/board"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/tv_qtd"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="16dp"/>

        <TextView
            android:text=""
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_nome"
            android:layout_toRightOf="@+id/tv_qtd"
            android:layout_alignParentTop="true"
            android:textSize="20dp"/>

        <TextView
            android:text=""
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_endereco"
            android:layout_toRightOf="@+id/tv_qtd"
            android:layout_below="@+id/tv_nome"
            />

        <TextView
            android:text=""
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_bairro"
            android:layout_marginTop="20dp"
            android:layout_toRightOf="@+id/tv_qtd"
            android:layout_below="@+id/tv_nome"
            />

        <Switch
            android:id="@+id/simpleSwitch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="false"
            android:layout_marginTop="60dp"
            android:layout_alignParentRight="true"
            android:text="Coletada"
            android:textOff="Não"
            android:textOn="Sim"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>

Esta é minha classe PalhetasColetadas reponsavel pelo cardview:
@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    View v = View.inflate(context,R.layout.card_view_palheta, null);
    TextView tv_nome = (TextView) v.findViewById(R.id.tv_nome);
    tv_nome.setText(palhetas.get(i).getCodigo());
    TextView tv_endereco = (TextView) v.findViewById(R.id.tv_endereco);
    tv_endereco.setText("Endereço: " + palhetas.get(i).getEndereco().getRua());
    TextView tv_bairro = (TextView) v.findViewById(R.id.tv_bairro);
    tv_bairro.setText("Bairro: " + palhetas.get(i).getEndereco().getBairro());
    v.setTag(palhetas.get(i).getId());
    Switch simpleSwitch = (Switch) v.findViewById(R.id.simpleSwitch);
    simpleSwitch.setTextOn("Sim"); // displayed text of the Switch whenever it is in checked or on state
    simpleSwitch.setTextOff("Não");
    simpleSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            ColetarActivity coletarActivity = new ColetarActivity();
            coletarActivity.cekstatus (isChecked);

        }
    });

    return v;
}

Na minha classe coleta é que eu verifico se o swicth button foi checado e dependendo dessa verificaçao eu faço um comando.
 private AlertDialog alertDialog() {
    // Use the Builder class for convenient dialog construction
    final AlertDialog.Builder builder = new AlertDialog.Builder(getApplication());
    builder.setMessage("Confirmar a coleta da palheta")
            .setPositiveButton("Sim", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    confirmarPedidos();
                }
            })
            .setNegativeButton("Não", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    finish();
                }
            });
    // Create the AlertDialog object and return it
    return builder.create();
}

O problema está na mudança das classes, onde nao estou conseguindo passar as informaçoes do switch, alguem pode me ajudar?
Answer: A forma de iniciar a ColetarActivity está errada. Você não deve instanciar uma classe Activity manualmente. O correto seria algo como:
Intent intent = new Intent(this, ColetarActivity.class);
intent.putExtra("check_status", message);
startActivity(intent);

Ou, por estar em um adapter, usando um Context:
Intent intent = new Intent(context, ColetarActivity.class);
intent.putExtra("check_status", message);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

E na outra Activity, para pegar o valor passado:
Intent intent = getIntent();
String message = intent.getBooleanExtra("check_status");

Este artigo dá uma explicação completa sobre o assunto.
Comment: Só um complemento da resposta do Leonardo. Quando você utiliza `this` dentro de uma nova classe, você está dizendo para o sistema pegar aquela — nova — classe. Ou seja, o `new Intent(this, ColetarActivity.class)` está pegando a classe `OnCheckedChangeListener` e passando para o `intent`. Você pode usar o `context` (como foi supracitado na edição da resposta) ou `view.getContext();` no lugar do `this`.
Comment: Só um outro complemento, o correto atualmente é utilizar o ContextCompat. Em alguns casos pegando o Context da view, ou passando uma activity, pode gerar um Memory Leak do contexto, e isso na ContextCompat foi corrigido.
Comment: Ao colocar seu codigo @Leonardo ele traz uns erros que postei na pergunta.
Comment: @Leonardo Lima agora estou com este outro erro, atualizado na pergunta.
Comment: @CarlosDiego erro meu, atualizei a resposta
Comment: @LeonardoLima eu ja tinha testado com a intent, e me retorna o erro: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
Comment: @CarlosDiego como o próprio erro indica, você deve incluir a flag indicada. Atualizei a resposta.
Comment: @LeonardoLima eu add essa tag, so que ao mudar o switch button de lado (on/off) ela muda pra uma activity em branca.
Comment: Há alguma informação no `logcat`?
Comment: @CarlosDiego bom, aí já é outro problema fora do escopo desta pergunta. Vc deve implementar adequadamente a `ColetarActivity` e seu `onCreate` para exibir algo nela.
Comment: @ValdeirPsr como estou passando via putExtra o id do cara logado, ele da um erro ao clicar no switch ele abre uma nova intent q nessa, nao há o id. So estranho, pq ele abre uma nova intent ao clica no switch. Mesmo so colocando um log, a tela em branco abre
Comment: Ele realmente manda o ON/OFF do switch pra classe, conforme conferido no LOG, porem tem esse outro pro da mudança de activity em branco
Answer: Crie uma classe dentro da classe onde voce manipula sua listview:
class CustomAdapter extends BaseAdapter{

    private List<Palheta> palhetas;

    public CustomAdapter(List<Palheta> palhetas) {
        this.palhetas = palhetas;
    }

    @Override
    public int getCount() {
        return palhetas.size();
    }

    @Override
    public Object getItem(int i) {
        return palhetas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        view = getLayoutInflater().inflate(R.layout.card_view_palheta, null);
        TextView tv_nome = (TextView) view.findViewById(R.id.tv_nome);
        tv_nome.setText(palhetas.get(i).getCodigo());
        TextView tv_endereco = (TextView) view.findViewById(R.id.tv_endereco);
        tv_endereco.setText("Endereço: " + palhetas.get(i).getEndereco().getRua());
        TextView tv_bairro = (TextView) view.findViewById(R.id.tv_bairro);
        tv_bairro.setText("Bairro: " + palhetas.get(i).getEndereco().getBairro());
        view.setTag(palhetas.get(i).getId());
        Switch simpleSwitch = (Switch) view.findViewById(R.id.simpleSwitch);
        simpleSwitch.setTextOn("Sim"); // displayed text of the Switch whenever it is in checked or on state
        simpleSwitch.setTextOff("Não");
        simpleSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if (isChecked) {
                    Toast.makeText( getApplicationContext(), "SIM", Toast.LENGTH_LONG ).show();
                } else {
                    Toast.makeText( getApplicationContext(), "NAO", Toast.LENGTH_LONG ).show();
                }
            }
        });
        return view;
    }
}

Depois inicialize seu adapter passando a lista de palhetas:
private List<Palheta> palhetas;
private ListView lvPalheta;

Type usuariosListType = new TypeToken<ArrayList<Palheta>>(){}.getType();
CustomAdapter customAdapter = new CustomAdapter(palhetas);
lvPalheta.setAdapter(customAdapter);


Animate layout changes using a transition in same layout

Question: I'm trying to create my first compound control it should look like this:

I was thinking in using a LinearLayout for the container and one TextView for each number, the selected number would have the rounded background and when the user clicks on the number remove the background from the current one and set it to the new one, and then somehow get android to animate that.
This looks something like a shared element transition only that this is not an element, just the background.
How can I accomplish this transition?
Answer: I would have created this:
Relativelayout - (White background, rounded corners)
      └ Framelayout - (Green background, rounded corners)
      └ LinearLayout
             └ TextView 1 |  TextView 2 | TextView 3

Then get the position, center, of a textview upon selection and use that position to move the Framelayout. Use an interpolator,AccelerateDecelerateInterpolator, for the animation. You can animate with an XML or with code, it's up to you.
You can use ImageView or others instead of FrameLayout, this is an opinion based decision.


Launch a new instance when a threshold of HTTP requests is exceeded

Question: I'm trying to use EC2 and CloudWatch to start up a new instance after I hit a certain number of HTTP requests per minute. Is this possible?
Comment: are you aware of auto scaling? are you using an ELB?
Comment: Yes I am, I'm trying to configure the auto-scaling for our site. We are using an ELB and that's exactly where I needed to find the information I was looking for. Thank you.
Answer: Not out of the box.  You can create auto scaling rules on EC2 instance metrics, but request/minute aren't tracked.  You have CPU, Disk I/O, and Network metrics available.
You could base it on network activity, or you could create a custom Cloudwatch metric and feed it information from your instance.


Integrate solr search with og group

Question: I search the method to implement apache solr search with og group and search on the content associated with group.
I want that the user can search the content of a specific group or for all group.
Thank
Answer: If you want to integrate SOLR with Organic groups,  you can use the Apache Solr Organic Groups Integration module but it is in dev mode.
Also, while searching, you can filter data, and alter queries as required.
Comment: Ok I have installed this module. I have a facet group. But the problem is that I have several type of group and I want to show only one type.

Moreover this type of group is content type I don't want that the user can make a search of this group by type his name in search box.
Comment: If you have already added, you can then go for altering queries on the fly. This is what I did too, and was very much successful. However, if you think in terms of scaling, this would be a bit slower than normal.
Mine is a ~1Lac nodes per groups and counting.
Hopefully, this works for you too.

Integrate solr search with og group


Kalman filter conceptual question

Question: I'm using the function dlmGibbsDIG (Gibbs sampler) in the dlmpackage from R to estimate the unknown variances. The output are the unknown variances together with the (saved) sampled states.
Then the dlmFilter function performing the kalman filter only need as arguments the observations and the specified model (with the averaged variances gived by the output of dlmGibbsDIG) but I'm confused about the role of the thetas (states) simulated by the Gibbs sampler above.
Comment: I'm not sure exactly what you're after. The states are often (but not always) unknown parameters of interest in your problem.
Comment: @Glen_b well I was asking basically if the thetas in the output of the Gibbs sampler are of any use.
Comment: @Glen_b this is the case since I'm using a regression DLM but for me it's not straightforward that we only pass the estimated variances for the kalman filter.
Comment: I'm sorry, it's still not clear to me what the difficulty is.
Comment: @AP13 whether they are of use is up to you. I have given you what they are, i.e. $p(x|\theta_i)$ which you obtain by running the Kalman filter at every iteration of the MCMC chain. The rest is up to you, unless you have a further question
Answer: Every time you sample the prior $p(\theta_i)$ you then run the Kalman filter and obtain $p(x|\theta_i)$ - i.e. the distribution of the $\textit{states}$, conditional on the current value of $\theta$.

Kalman filter conceptual question


Como verificar se o input está vazio com Jquery?

Question: Gostaria de que meu form desabilitasse os 'input radio' quando o 'input name' estivesse vazio,
tentei o seguinte: toda vez que o valor do input text mudar, verifica se esta vazio, se estiver desabilita o input radio

  $("input[name='new-sale-cli']").on('change', function() {

    if($.trim($("input[name='new-sale-cli']").val() == '')) {
          $("input[name='payment-option']").prop('disabled',true);
            console.log($("input[name='new-sale-cli']").val());
        }

    else {
          $("input[name='payment-option']").prop('disabled', false);
        }
  });

<input class="form-control" name="new-sale-cli">

O problema é que esta entrando no if sempre, ate quando o input text NAO esta vazio, ou seja, sempre vai estar desabilitado.
Ja tentei usar o 'change', 'on change' na função,
ja tentei usar o 'is(:empty'), ' =="" ' e o resultado e sempre o mesmo,
O que estou fazendo de errado?
Comment: `$("input[name='new-sale-cli']").val() == ''` é uma expressão que retorna `true` ou `false` (se o valor é igual à string vazia ou não). Ao passar tudo isso para `trim`, ele acaba convertendo o booleano para string, resultando em "true" ou "false", e em JavaScript strings não-vazias sempre são verdadeiras, portanto sempre entrará no `if`. Basta fazer `if($.trim($("input[name='new-sale-cli']").val()))`
Comment: Ola  hkotsubo! Eu fiz dessa maneira e agora esta funcionando ao contrario kkk
O objetivo é: se o campo estiver vazio, desabilite os input radio.
No caso, ele esta habilitando os input radio quando o campo esta vazio, e desabilitando quando ha algo escrito. Eu poderia simplesmente inverter, mas nao estaria certo, ja presenciou esse tipo de caso?
Comment: Coloque assim: `if(!$.trim($("input[name='new-sale-cli']").val()))`
Comment: O sinal `!` antes da expressão indica se ela é `false`.
Comment: Esta funcionando agora, mas a logica nao esta errada? "se for false, desabilita" quando era pra ser "se for true desabilita", futuramente numa manutenção pode causar confusao, estou certo?
Comment: Se for vazio (`false`), desabilita. O `if` sempre verifica se a condição é verdadeira, não se a expressão é verdadeira.
Comment: Acho que entendi. Se o campo estiver vazio, o javascript entende como 'false', e se tiver preenchido, entende como true, nesse caso é uma questao de sintaxe,
Answer: SOLUÇÃO FINAL:
Graças a ajuda do hkotsubo e do Sam, a resolução final ficou assim:

  $("input[name='new-sale-cli']").on('change', function() {

     if(!$.trim($("input[name='new-sale-cli']").val())) {
        $("input[name='payment-option']").prop('disabled', true);
        console.log('vazio');
      } else {
            $("input[name='payment-option']").prop('disabled', false);
        }
  });

<input class="form-control" name="new-sale-cli">

O JS entende que campo vazio: false e campo preenchido: true.
O codigo diz: "se for false, desabilita os campos"


Why do fixed effect and dummy variable models differ?

Question: Year as a dummy ( 1995 is the omitted year):
Call:
plm(formula = mrateunder5 ~ GDPPPP + factor(Year), data = FinalData,
    model = "within", index = "Country")

Unbalanced Panel: n = 47, T = 1-3, N = 69

Residuals:
    Min.  1st Qu.   Median  3rd Qu.     Max.
-11.4818  -1.9533   0.0000   1.9816  11.4818

Coefficients:
                    Estimate  Std. Error t-value  Pr(>|t|)
GDPPPP             0.0134389   0.0044836  2.9974   0.00773 **
factor(Year)2000 -15.4565645   6.2679791 -2.4660   0.02394 *
factor(Year)2005 -39.5441044   6.6982650 -5.9036 1.374e-05 ***
factor(Year)2010 -59.1835897   9.9644448 -5.9395 1.276e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Total Sum of Squares:    6722.6
Residual Sum of Squares: 1237.5
R-Squared:      0.81592
Adj. R-Squared: 0.30457
F-statistic: 19.9453 on 4 and 18 DF, p-value: 2.0253e-06

When I include Year and Country as dummy variables, I have the same coefficient value on GDP.
Year as a Fixed Effect:
Call:
plm(formula = mrateunder5 ~ GDPPPP, data = FinalData, model = "within",
    index = c("Year", "Country"))

Unbalanced Panel: n = 4, T = 4-28, N = 69

Residuals:
   Min. 1st Qu.  Median 3rd Qu.    Max.
-59.296 -24.494  -6.722  19.180 107.636

Coefficients:
         Estimate Std. Error t-value  Pr(>|t|)
GDPPPP -0.0251533  0.0030549 -8.2338 1.249e-11 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Total Sum of Squares:    183330
Residual Sum of Squares: 89024
R-Squared:      0.5144
Adj. R-Squared: 0.48405
F-statistic: 67.7951 on 1 and 64 DF, p-value: 1.2488e-1

As you can see, the coefficient estimate on "GDPPPP" is different. The results in the second model are my preferred results (negative coefficient, as higher GDP levels lead to lower mortality rates).
Why do these differ - are they supposed to match?
I think it could be because I have incomplete data (data for some countries for some years is missing - e.g., for Afghanistan I am missing the first two time periods (1995 and 2000) but I have the Afghanistan data for 2005 and 2010).
Does one of my models is drop incomplete data? Which one? Is there a way to make the models match?
Comment: You should not prefer a model because its results accord with your preconceptions.  In this case the second model is *awful* compared to the first: just look at the distribution of residuals.
Comment: That said, it's very helpful if you can share a sample of data (e.g. using `dput()`) that someone can copy and paste to get the same result.
Comment: Whether or not the models "should" match, if perhaps one is a reparameterization of the other with a transformation of coefficients, etc, seem like statistical questions to me, not programmatic ones. I think you'll get better answers and faster answers at Cross Validated.
Answer: The two commands you use estimate two different models. To illustrate, I use the Grunfeld data set; you can think of its firm variable as your Country variable and its year variable as your Year variable.
Your 1st model:
You effectively estimate a two-ways fixed effects model where the time fixed effect are explicitly modelled via dummies (the part +factor(year)) (sometimes this is called LSDV - least squares dummies (approach); here you have the time dimension as explicit dummies and the individual dimension implictly).
You can have that model also via the effect argument by setting it to "twoways", leaving out the explicit dummies (this is the Frisch-Waugh-Lovell theorem [1]).
The coefficient for value is in both cases 0.17997:
library(plm)
data("Grunfeld", package = "plm")

# corresponds to your 1st model:
plm(formula = inv ~ value + factor(year), data = Grunfeld,
    model = "within", index = c("firm", "year"))
#>
#> Model Formula: inv ~ value + factor(year)
#>
#> Coefficients:
#>            value factor(year)1936 factor(year)1937 factor(year)1938
#>          0.17997        -38.10560        -66.31173        -20.32730
#> factor(year)1939 factor(year)1940 factor(year)1941 factor(year)1942
#>        -59.30898        -36.24559         -1.50065         18.71706
#> factor(year)1943 factor(year)1944 factor(year)1945 factor(year)1946
#>         -6.73151         -9.46490        -26.44724         -0.73981
#> factor(year)1947 factor(year)1948 factor(year)1949 factor(year)1950
#>         34.82737         47.09646         28.68980         29.79853
#> factor(year)1951 factor(year)1952 factor(year)1953 factor(year)1954
#>         36.74272         52.86057         64.20592         69.57366

# same with effect = "twoways"
plm(formula = inv ~ value , data = Grunfeld,
    model = "within", index = c("firm", "year"), effect = "twoways")
#>
#> Model Formula: inv ~ value
#>
#> Coefficients:
#>   value
#> 0.17997

Your 2nd model:
You switched the index variables in argument index, so plm takes the time dimension as the observational unit (individual index) and vice versa, see also the output n = 4, T = 4-28, N = 69 in your 2nd model vs. n = 47, T = 1-3, N = 69 in your first.
You effectively estimate a one-way time effect model . You can have the same model without the confusioning mix up of invididual and time dimension and - again - by using the effect argument (set to "time"). You get the same coefficent for value: 0.13983.
# your approach
plm(formula = inv ~ value, data = Grunfeld,
    model = "within", index = c("year", "firm"))
#>
#> Model Formula: inv ~ value
#>
#> Coefficients:
#>   value
#> 0.13983

# one-way time effect model
plm(formula = inv ~ value, data = Grunfeld,
    model = "within", index = c("firm", "year"), effect = "time")
#>
#> Model Formula: inv ~ value
#>
#> Coefficients:
#>   value
#> 0.13983

I suggest you revisit the plm package first vignette for further instructions. The summary() command on estimated models will give you a nice headline about the model estimated if you make use of the index and the effect arguments in a proper way.
The fixed effects as in the dummy-based model can be obtained in the other models via commandfixef, here for the time effects in the two-ways model with arguments effect = "time" and type = "dfirst":
fixef(plm(formula = inv ~ value , data = Grunfeld, model = "within",
      index = c("firm", "year"), effect = "twoways"),
   effect = "time", type = "dfirst")
#>      1936      1937      1938      1939      1940      1941      1942      1943
#> -38.10560 -66.31173 -20.32730 -59.30898 -36.24559  -1.50065  18.71706  -6.73151
#>      1944      1945      1946      1947      1948      1949      1950      1951
#>  -9.46490 -26.44724  -0.73981  34.82737  47.09646  28.68980  29.79853  36.74272
#>      1952      1953      1954
#>  52.86057  64.20592  69.57366


Automatic control of linear system with non independent inputs

Question: I'm currently trying to (re)learn automatic control 2 years after having finished college, and I'm having a hard time. I'm trying to control a simplistic lunar lander in a 2d space.
The only way to control it is to change its angle and/or thrust power, so I have the following state-space representation:
$$
x=\begin{bmatrix}
   x_1 \\
   x_2 \\
   x_3 \\
   x_4
   \end{bmatrix}
$$
$$
\begin{gather}
 \dot{x}
 =
   \begin{bmatrix}
   0 & 0 & 1 & 0 \\
   0 & 0 & 0 & 1 \\
   0 & 0 & 0 & 0 \\
   0 & 0 & 0 & 0
   \end{bmatrix}
   x\;+
   \begin{bmatrix}
   0 & 0 \\
   0 & 0 \\
   1 & 0 \\
   0 & 1
   \end{bmatrix}
   u
\end{gather}
$$
Where:

x$_1$ is the horizontal position
x$_2$ is the vertical position
x$_3$ is the horizontal velocity
x$_4$ is the vertical velocity

And u is the command, accelerations on respectively the horizontal and vertical coordinates.
My problem is the acceleration is unidirectional, and its horizontal and vertical components are correlated:
$$
\begin{gather}
 u
 =
   \begin{bmatrix}
   a\times\cos{\theta} \\
   a\times\sin{\theta} - g
   \end{bmatrix}
\end{gather}
$$
$a$ is the acceleration provided by the thruster and $\theta$ is the angle of the lander. $g$ is the gravity constant.
Since the system is linear, I could calculate the feedback control with the gain K, but I realize this K would consider the two input commands are independent.
I've been stuck on this for a few days, I've tried including $\theta$ and $a$ in $x$ so $u$ could simply be an angular velocity and an acceleration derivative, which would be independent, but then the system becomes nonlinear and I have no idea how to solve it.
Maybe my approach is wrong, but I'm honestly lost here, could anyone explain to me what I did wrong or how I could take this input restriction into account in the feedback loop?
ADDENDUM 1: I'm considering for the sake of simplicity that I can freely and instantly change $\theta$ and $a$.
Comment: What would be the dynamics of $\theta$, $\dot{\theta}=\tau$ with $\tau$ the torque input to the system?
Comment: Here I'm considering I can freely change $\theta$ and $a$, in order to make things simple so I guess $\dot{\theta}$ would be a Dirac delta function? I'm not sure this is the correct term.
Answer: Since $a$ and $\theta$ are essentially polar coordinates. So if you have a state feedback control law $u=-K\,x$ then you can solve for $a$ and $\theta$ given each value for $u$. Namely
\begin{align}
a &= \sqrt{u_1^2 + (u_2 + g)^2} \\
\theta &= \text{atan2}(u_2 + g, u_1)
\end{align}
Comment: Thanks a lot for your help :)


Finding import path in pycharm

Question: I am using pycharm version 3.4 on ubuntu and have a project with the following structure:
~/project/src/python/utils/sub1/sub2/sub3/my_code.py
the utils folder also contains an __init__.py file which offers a number of utility functions. I want to include some of them, but it wouldn't find it:
from project.src.python.utils import read_utf8

I followed this post, which seemed to discuss the same problem:
PyCharm can't find the right paths if I open a directory that is not the Django root
But changing ~/project to a "source" folder didn't help. This isn't a typo on my side, as it should at least find "project" when trying to import something from it, but
import project

also gives my an "unresolved reference" error.

edit: I should add that I cannot change the code, as it is a shared project. I need that exact import line to work on my machine. My counterpart uses eclipse, were it seems to be easier to add a path to additional code.
Comment: Try the second answer in the following link:
http://stackoverflow.com/questions/24197970/pycharm-import-external-library
Comment: what's the value of `sys.path`? try printing it at the start of the script
Comment: also, the syntax of your import statement is wrong, you should separate the paths with dots rather than forward slashes
Comment: @GP89 my bad, a typo. It's dots in the code
Comment: @Omar thank you very much for pointing me to that answer, the first one actually worked for me, which was a bit less of a hassle
Answer: It looks like the source isn't in your PYTHONPATH which is why you're unable to import it.
python only looks in certain places for py/pyc/pyo etc. files and modules to import (the places are the paths listed in sys.path). You can add custom places for it to look with the PYTHONPATH environment variable, or in PyCharm under preferenes > project interpreter > configure interpreters, and then adding any paths in the paths section.
I can't tell which folders are actually modules but from the names of the folders I would guess only utils. If that's the case add the path /home/ceca/project/src/python to the list of paths in PyCharm and in your code from utils import read_utf8
Comment: You are right, except that the free version of pyCharm doesn't include the "configure interpreter" option, as explained in the link offered by Omar. Apart from that, everything is as you said, and my project works now. Thanks a bunch!
Comment: @ArneRecknagel np. I'm running 3.1- it looks like the preferences might have changed since
Comment: huh, what a strange thing to remove. It seems that it's an option which is used quite often, the more visible the better. But what do I know

Finding import path in pycharm


Is there an example of a rational polynomial that has integer output for all integer inputs that are sufficiently large?

Question: Is there an example of a rational polynomial $f(n)\in \mathbb{Q}[t]$ that has integer output for all integer inputs that are sufficiently large, but not for, say, inputs $n=1,2,3,\dots,n$?
Answer: No. If $f$ has degree $d$, you can reconstruct $f(n-1)$ from $f(n), \ldots, f(n+d)$ by taking repeated differences and adding again.
Comment: So a rational polynomial that has integer outputs for sufficiently high integer inputs must in fact have integer outputs for ALL integer inputs?
Comment: Yes. For example a quadratic polynomial with $f(10)=a$, $f(11)=b$, $f(12)=c$ integers will have first differences $b-a, c-b$ and second difference $c-2b+a$; hence the first differences continue to the left with $b-a-(c-2b+a)=-2a+3b-c$, thus $f(9)=a-(-2a+3b-c)=3a-3b+c$.
Answer: No.
Suppose $f$ is a polynomial in $\mathbb{Q}[x]$ outputting integers for sufficiently large integer inputs. Then I claim $f$ can be written
$$
\sum_{i = 0}^n a_i {x \choose i}
$$
where
$$
{x \choose i} = \frac{x(x-1)\ldots(x-i+1)}{i!}
$$
and the $a_i$ are integers; note that this expression is $1$ when $i = 0$ (because the numerator is the empty product). This claim then proves your result, since clearly anything that can be written this way has your property.
The proof: Clearly we can write $f$ this way for some rational numbers $a_i$. We will recover the $a_i$ and then argue that they must be integers. If $g$ is a polynomial, set
$$
\Delta g = g(x+1) - g(x).
$$
We compute (just by writing it out) that
$$
\Delta {x \choose i} = {x \choose i -1}
$$
for $i > 0$ and clearly $\Delta {x \choose 0} = 0$.
Since $\Delta$ is linear, it follows that
\begin{align*}
a_0 =& f(0) & \\
a_1 =& (\Delta f)(0)\\
a_2 =& (\Delta^{(2)} f)(0)\\
\ldots \\
a_n =& (\Delta^{(n)}f)(0)\\
\end{align*}
With these formulas and induction on the degree of $f$, we have that all of the coefficients but $a_0$ must be integers (because the polynomials $\Delta^{(i)}(f)$ have smaller degree, they must evaluate to integers on all integers). But then $a_0$ must be an integer as well, since when you plug in a large number you will get an integer plus $a_0$.
Comment: I don't see how you argue that $a_1=(\Delta f)(0)=f(1)-f(0)$ must be integer.
Comment: $\Delta(f)$ is a polynomial of strictly smaller degree than $f$ which takes integer values for all sufficiently large integers, so it follows from the inductive hypothesis on the degree.
Answer: Any $P\in\mathbb Q[X]$ whose evaluations at all $n \in\Bbb N$ are in $\Bbb Z$ are integer linear combinations of the rational polynomials $\binom Xd$ with $d \in\Bbb N$: the coefficient of $\tbinom X0=1$ is the evaluation $P$ at $0$; subtracting off that (constant) term, the coefficient of $\tbinom X1=X$ is the evaluation at $1$ of the remainder; subtracting off that (linear) term, the coefficient of $\tbinom X2=\frac{X^2-X}2$ is the evaluation at $2$ of the remainder; and so forth. The remainder ultimately becomes $0$ when the coefficient of $\binom Xd$ is taken into account where $d=\deg P$, as we have subtracted off a polynomial $Q$ of degree $d$ whose evaluations in $0,1,\ldots,d$ coincide with those of $P$, which forces $P=Q$.
Now the rational polynomials $\tbinom Xd$ take integer values at all $n\in\Bbb Z$, and therefore so will $P$. If for some $P'\in\mathbb Q[X]$ the evaluations at all integers${}\geq n_0$ are in $\Bbb Z$, then consider $P=P'[X:=X+n_0]$ (substitute $X+n_0$ for $X$), now $P$ has integer evaluations at all $n \in\Bbb N$, and the above applies, so $P'$ has integer evaluations at all $n \in\Bbb Z$.
To make the link with answer by Hagen von Eitzen, this argument only needs the integrality at $\deg P+1$ successive values, which forces all evaluations to be integer.


Question on convexity

Question: If I have a function $f:\mathbb{R}^n\to\mathbb{R}$ that is convex in ${\bf x} = (x_1,x_2,\ldots,x_n)$ and strictly convex in one of the variables, say $x_1$, then is $f({\bf x})$ strictly convex in ${\bf x}$? If so, how would I prove this?
Comment: What does 'weakly' convex mean in this context?
Comment: Edited, I meant convex.
Answer: No, just consider $f(x) = x_1^2$. This is strictly convex in $x_1$ and weakly convex in $x$ but not strictly convex in $x$.
Comment: Wouldn't $f$ then be a function from $\mathbb{R}$ to $\mathbb{R}$? I would like to place the additional restriction that each $x_i$ needs to show up in the function.
Comment: isn't $f(\lambda x+(1-\lambda)y)<\lambda f(x) + (1-\lambda) f(y)$ for $x,y\in\mathbb{R}^n$, $\lambda\in(0,1)$? Meaning that $f$ is strictly convex.
Answer: Take any convex (but not strictly convex) function $c:\mathbb{R} \to \mathbb{R}$ and any strictly convex function $s:\mathbb{R} \to \mathbb{R}$, then the function $f:\mathbb{R}^2 \to \mathbb{R}$ given by $f(x,y) = c(x)+s(y)$ satisfies the criteria in the question, but clearly $f$ is not strictly convex for any fixed $y$.
Comment: If I get a chance I will have a look at it.
Comment: I added an answer to the other question. Hopefully that helps answer your question. Note that if the function $c$ above was strictly convex, then  $f$ would be too.
Comment: Thanks, I asked a similar question a while ago, care to explain the difference between this case and the one seen here: http://math.stackexchange.com/questions/720680/is-this-function-strictly-convex I'm a bit confused.
Comment: What do you mean by 'explain the difference'? There are many differences...
Comment: Sorry for the ambiguity. I don't understand what additional property of the function (in the link) is making it strictly convex compared to only convexity of the function in the question posed here. If I were to add an additional assumption to the question above to make $f$ strictly convex, what would it be? Is it because each function in the sum of the three terms (in the link) is convex in the same variable that the function is strictly convex in (i.e. $x_1$)? Relating it back to this post, being convex in ${\bf x}$ and strictly convex in one variable is not enough. Thanks for your attention

Question on convexity