Instance initialization block and subclasses

Question: I'm getting confused about when the instance initialization block should run.
According to Kathy Sierra's book:

Instance init blocks run every time a class instance is created

So, consider having two classes: a parent and a child, according to this question and java's documentation:

instantiating a subclass object creates only 1 object of the subclass
  type, but invokes the constructors of all of its superclasses.

According to the above:
why does the instance initialization block located in superclasses gets called every time an object of the subclass is instantiated? it isn't like that a new object of the superclass is instantiated.
Answer: After compilation instance init blocks become part of constructors. javac simply adds the init block to each constructor, that is this:
public class Test1 {
    int x;
    int y;

    {
        x = 1;
    }

    Test1() {
        y = 1;
    }
}

Is equivalent to this:
public class Test1 {
    int x;
    int y;

    Test1() {
        x = 1;
        y = 1;
    }
}

So the init block runs when constructor runs.
Comment: Actually, there is a little more to it, the instance initializer blocks get added to the constructor after any existing call to a super constructor.  See http://java-blog.kbsbng.com/2016/01/instance-initializer-blocks-in-java.html for reference
Answer:
it isn't like that a new object of the superclass is instantiated.

Actually, it is like that.
Every instance of a subclass implicitly contains an instance of its superclass.
A superclass constructor is always invoked as the first step in any constructor (and that in turn runs any instance initializer blocks for the superclass)
Comment: You can look at it that way. But you could also say that the same object is also an instance of the superclass. And to be sure, the instance contains all the fields defined by the superclass in addition to its own.
Comment: I know that all of the superclass constructors will be invoked, but what I understand is that regardless of invoking these constructors: only one object is being instantiated/created there, that is for the subclass.
Answer: Though it was  a old post I came across this concept thought worth sharing it
Since we are talking about instance block here is how instance code flow executes in parent child relation class
// Child  extends Parent
  If we create a object for Child
1) Identification of instance members of the class from parent to child
2) execution of instance variable assignments and instance blocks only on parent      class
3)execution of parent  constructor
4)execution of instance variable assignments and instance blocks only on Child class
5)Execution of child constructor
Answer: Because there is always an implicit super() call(if not done explicitly) to the parent's constructor in the constructor of the child.


What is the Western equivalent scale of Indian Raga Mayamalavagowla?

Question: Mayamalavagowla is the first raga taught to students who learn South Indian Carnatic Music. But I wonder what is the western scale used to represent this Raga ? Why did Carnatic Music system selects this Raga for starting lessons? Is there any advantages or disadvantage with this Raga ?
Comment: @Stinkfoot why, she/he used the valid technical term for the raga.  You wouldn't ask someone writing asking about the major scale to explain what it is, or writing about 6/8 time to explain what 6/8 time is... Anyone capable of answering a question about those things will know what they are, it's standard vocabulary for western music theory. Explaining what a raga *is* to someone unfamiliar with the concept isn't exactly easy or brief to do (it's more than just a set of notes), and it's unnecessary because anyone capable of answering the question will be familiar with the standard terminology.
Comment: @Stinkfoot why should they have to explain what something is in western terms? If your asking about the western equivalent of an Indian concept, it makes sense to describe it in Indian terms.
Comment: @Some_Guy - I didn't say to explain it western terms. I asked to explain it - somehow/anyhow! Please read my comment again. Tnx
Comment: @Sooraj Namaskār! :) Could you drop a "hi/hello" message in this chatroom : [Saptak](https://chat.stackexchange.com/rooms/132745/saptak).
Comment: Although this question is old, I'm throwing in a close-vote as it asks three questions.
Comment: @AndyBonner alternatively, one can edit and remove the last two questions, since the OP has accepted a nice answer to the titular question, and it's rather unlikely that any further improvements will be made to the question by the OP.
Comment: There are two or three questions here. Please focus on one at a time. You should also explain what _Mayamalavagowla_, is before asking us to explain it in western terms.
Comment: @Some_Guy : I don't think so. :)
Comment: @Some_Guy I think Stinkfoot made a perfectly appropriate and correct suggestion. This site is not just for the asker/answerers but for many users on into the future. A little more background and details makes a more attractive question so more users will click it and learn something. ... That said, I think you also are coming the right place: trying to protect new users. Any further discussion on this should probably be on meta.
Comment: @Namaskaram Good point, but I generally don't want to make edits that invasive. Sooraj, feel free to edit yourself, or if you're still curious about the "why is this raga so popular" questions, follow [this recent question](https://music.stackexchange.com/q/129023/78419).
Answer: I will answer the question in the title, Stinkfoot is right, for other questions (why is this the most common beginning raga taught), it is better to ask them separately.
The name we give to the western scale that uses the same notes as the Raga Mayamalavagowla is the double harmonic scale.
In C, it looks like this:

Obviously, a raga is about more than just the notes, so the details of Mayamalavagowla (the order, the importance of the notes, and microtonal inflections) isn't covered by the Double Harmonic Scale which is a term which simply describes the 7 notes that makes the scale (and nothing more).  I'm not an expert in this, but I know enough to know that a "raga" includes more information that just the scale itself.
Something to note about this scale is, like the major scale, it is "symmetric".   The intervals from the fifth to the tonic are a repeat of the intervals from the tonic to the fourth.  So C Db E F and G Ab B C are the same pattern repeated.
The most well known melody in the west which uses this scale is probably miserlou, a Greek/Turkish folk melody made famous by dick dale's surf rock version and then by the movie pulp fiction, which used it prominently.

In western music the Double Harmonic scale is not a traditional scale, and when it's used, it's often used to give a "middle eastern feel" to music (in film scores for example, music may use this scale to evoke Arabia).  That's probably because this scale is very common in middle eastern music (maqam music), where it is known as maqam hijaz kar, (although even more common is the slightly different maqam hijaz which has a flattened 7th.)

This scale is known as the "Phrygian Dominant Scale" and is very common in both Arabic/Turkish/Persian music (where it is known as maqam hijaz) and Jewish Klezmer music (in Jewish music I'm not sure what it's called, but it's everywhere).  Greek folk music uses it a lot too.  Again, it is not a traditional "western" scale.
Answer: Raga is not equivalent to scale. Scale never explains the acceptable phrases, ascending and descending patterns.
Comment: I don't dispute the first statement, but "never" in the second sentence seems to be going a bit too far.  For example, the melodic minor scale has different forms depending on direction, and while they may not be formalized as they are for raga, there are indeed formulaic phrases that are associated with the major and minor scales (even more so with the medieval melodic modes).


routerLink change in Angular 16

Question: When using angular < 16, I used to have this routes configuration:
{
  path: Section.Security,
  canActivate: [AuthGuard, AccessGuard, AdminGuard],
  children: [
    {
      path: '',
      pathMatch: 'full',
      redirectTo: 'administrators'
    },
    {
      path: '',
      outlet: 'left-menu',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/components/left-menu/left-menu.component').then(m => m.SecurityLeftMenuComponent)
    },
    {
      path: 'administrators',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/pages/security/security.page').then(m => m.SecurityHomePage)
    },
    {
      path: 'contributors',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/pages/security/security.page').then(m => m.SecurityHomePage)
    },
    {
      path: 'readers',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/pages/security/security.page').then(m => m.SecurityHomePage)
    }
  ]
}

And, in the SecurityLeftMenuComponent, I had simple links to sub routes like:

   <rn-key name="security::administrators" />

It was working very well but since I updated to angular 16, the links generated by routerLink now have a different format: "/security/(readers//left-menu:administrators)"
I could fix this by using:

   <rn-key name="security::administrators" />

But the goal is to have relative links.
I tried using "./" but I still have the same issue.
What would be the best way to keep the same behavior as before?
Edit:
As I'm in the process of migrating several applications, I noticed that the issue really occurs when using relative routes. I didn't encounter any issue in the absolute route of the other applications
Answer: I'm encountering the same issue on my side with @email@example.com.
It's linked to this issue : https://github.com/angular/angular/issues/50611
To confirm this, you can test your navigation before the migration (ng 15.x). Navigation works, but if you look at your console, you should see a warning looking like this :

The navigation to /list/(details:item-1) will instead go to
/list/(/(details:item-1)//details:item-2) in an upcoming version of
Angular. relativeTo might need to be removed from the
UrlCreationOptions.

From my understanding, the only workaround available currently is to avoid using relative links and stick with absolute ones.
Answer: I am not sure if this fixes your problem, but I made the wollowing work:
<button
  mat-raised-button
  color="primary"
  [routerLink]="['..', 'project-creator']"
>
   Text
</button>

The routes are relative and I can even manage to use '...' to go a level up.
What did the trick for me was to import RouterModule in my Standalone Component. Otherwise, the property routerLink does not exist on button, hence you can't bind to it.
For clarity, this is my component that uses these importing
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { RouterModule } from '@angular/router';

@Component({
   selector: 'my-selector',
   standalone: true,
   imports: [CommonModule, MatButtonModule, RouterModule],
   templateUrl: './project-overview.component.html',
   styleUrls: ['./project-overview.component.scss'],
})
export class ProjectOverviewComponent {}

I did not need to inject the RouterModule, importing it was enough

routerLink change in Angular 16


Properties of multivariate polynomials over $\mathbb Q$ modulo an ideal

Question: I am a computer scientist, not a mathematician, please forgive my imprecisions.
I came across the following structure and I need to understand it better.
Let $R = \mathbb{Q}[X,Y,Z,W]$ be multivariate polynomials over $\mathbb{Q}$ and consider the following elements:
$X^2 - \alpha$, $Y^2 - \beta$, $Z^2 - X - \alpha$, $W^2 + X - \alpha$.
I understand these generate an ideal $I$, with respect to which it is possible to define an equivalence relation $a \sim b \Leftrightarrow a-b \in I$.
I need to operate with the classes $[a] = \{ b \in R : a \sim b \}$ defined by this equivalence, let me call the set of these classes $K$.

Is $K$ a field?
In case it is, is it a finite extension of $\mathbb Q$?
Can I find its dimension and a basis so as to treat it as a vector space?

I have some familiarity with similar issues involving finite fields and univariate polynomials but I do not know how to deal with the multivariate case.
I did some quick research and I found about Groebner bases, do they have something in common with this problem?

edit
To make things clearer without reading the many comments below, the problem arised from trying to compute with $\sqrt{5}, \sqrt{2}, \sqrt{5\pm\sqrt{5}}$.
It happened that the generators were chosen too naively and did not yield a field.
A good choice is proposed in the answer below.
Comment: What are $\alpha$ and $\beta$?
Answer: My comments here are still incomplete, but it now appears that $R/I$ is never a field, because it has zero divisors: $(ZW)^2 - (2X)^2 = (ZW-2X)(ZW+2X)\in I$.
If the goal is to compute with $\sqrt{2}$, $\sqrt{5}$, and $\sqrt{5\pm \sqrt{5}}$, then the ring that should be used is $\mathbb{Q}[\sqrt{5+\sqrt{5}},\sqrt{2}] \cong \mathbb{Q}[X,Y]/(X^4-10X^2+20,Y^2-2)$, which is a field over $\mathbb{Q}$ of dimension $8$, with basis $\{X^i Y^j \mid 0\leq i \leq 3, 0\leq j \leq .1\}$
The important calculation in seeing that the above has everything you need is this one: $\sqrt{5+\sqrt{5}} \cdot \sqrt{5-\sqrt{5}} = 2\sqrt{5}$.  Any field containing $\sqrt{5+\sqrt{5}}$ will also contain $\sqrt{5}$, therefore it will contain $\sqrt{5-\sqrt{5}}$.

It's not necessarily a field, depending on $\alpha$ and $\beta$.  For example, if $\alpha = c^2$, then $\overline{(X-c)}$ is a zero-divisor in $R/I$.
It may also have nilpotents.  If $\alpha^2 = \alpha$, then $(\overline{ZW})^2 = \overline{(\alpha-X)}\overline{(\alpha+X)} = \overline{(\alpha^2 - X^2)} = 0$.
It is, however, a vector space over $\mathbb{Q}$ with dimension $16$, with basis $\{\overline{X^a Y^b Z^c W^d} \mid a,b,c,d\in\{0,1\}\}$.  I would work directly with this basis when doing computations, as the particular form of your ideal makes it very easy to reduce any polynomial to one written in terms of this basis (for this reason, you probably have little need for Gröbner bases).
I would speculate that $R/I$ is a field for most choices of $\alpha,\beta$, but I don't see how to quickly prove this.
Comment: If $\alpha = c^2$ for some $c$ then I think $X - c$ and $X + c$ are zero divisors, and likewise with $Y$ and $\beta$, right? So there are quite a few $\alpha$ and $\beta$ that don't work, although I don't necessarily disagree that "most" still will.
Comment: Thanks! I will take some time to digest your answers and see what happens.
By the way, what do you mean by the overbar?
My first attempt was something like what you proposed, considering the exponents in $\{0,1\}$, but I noticed that I would have a redundant representation (different polynomials being actually equivalent and not noticing it in the algorithms) and I did not know well how to take full care of it, so I thought that I need to find a better basis.
I also reduced the dimension to 12 by noticing that $ZW - 2X \in I$.
Actually, $\alpha = 5$ and $\beta = 2$.
Comment: @BenMillwood Yes, this is what I intended to say; I forgot briefly that $\beta$ was already in use.  It should be the case that the set of "good" $\alpha,\beta$ in $\mathbb{A}^2$ contains a Zariski open... this is my intuition, anyway.
Comment: @user9137 I just used the overlines to distinguish between elements of $R$ and elements of $R/I$.  How did you arrive at the conclusion that $ZW-2X \in I$?
Comment: You are right, it is not general. My bad, I see I derived it using my knowledge of $\alpha = 5$ and $\beta = 2$. Looking at the answer by Mariano I notice I can actually drop $X = \sqrt{\alpha}$ from the basis, right? I now suspect that this will give a unique representation for $R/I$.
Comment: @user9137 How did you derive it even with those assumptions?—it seems like Mariano's answer supports that the dimension is 16.  And I don't know what you mean by "drop", but then again I don't know your goals.
Comment: @Slade I am not sure I did not make any illegal assumption, but: $X=\sqrt\alpha$, $Z=\sqrt{\alpha+X}$, $W=\sqrt{\alpha-X}$, $ZW=\sqrt{\alpha(\alpha-1)}$, which is $2X$ when $\alpha=5$, therefore $ZW-2X=0 \in I$. If this holds, then also $5W+XW-2XZ=0$ and $\{X^a Y^b Z^c W^d : a,b,c,d \in \{0,1\}\}$ are not linearly independent. Where do I get it wrong?
Comment: @user9137 As I said, I don't know your exact goals, but as stated this is wrong.  All this shows, on the level of polynomials, is that $(ZW)^2 - (2X)^2 = (ZW-2X)(ZW+2X) \in I$, but not that either of the two factors are in $I$.  I still think the dimension is $16$ for $\alpha=5$, $\beta=2$.  Mariano's answer confirms that it is a power of $2$ for any $\alpha,\beta$, since you are making a series of four extensions by square roots, each of which has degree $1$ or $2$.
Comment: @user9137 In more "algebraic" terms, you have stated that $Z=\sqrt{\alpha+X}$, but if you are thinking of "solving" these equations, you should really write $Z=\pm\sqrt{\alpha+X}$.
Comment: Sorry, I shouldn't say that the dimension is a power of $2$.  It is _always_ 16, as far as I can tell, but if we add some extra structure (like passing to a prime ideal containing $I$) then we get a field whose dimension is a power of $2$.
Comment: Yes I think I understand what you are meaning, I arrived at similar arguments while reviewing my last comment. It seemed to me anyway that, say $A=ZW-2X,B=ZW+2X$, we have $AB \in I \Rightarrow AB \sim 0$, thus at least one of the factors should be null if $R/I$ is a field. My final goal is to compute symbolically with $\sqrt{5}, \sqrt{2}, \sqrt{5+\sqrt{5}}, \sqrt{5-\sqrt{5}}$, and I was trying to understand whether this can be done in a finite extension of $\mathbb{Q}$ and which basis could be used, mainly to be able to efficiently check whether a given element is rational.
Comment: @user9137 I've just updated my answer.  In short, your original ring can't possibly be a field, but there is a nice field that you can work with, requiring only two generators.
Answer: This addressed part of your question. I'll write $a$ and $b$ instead of $\alpha$ and $\beta$.
If none of $a$, $b$ and $ab$ are squares in $\mathbb Q$,then the ring $\mathbb Q[X,Y]/(X^2-a,Y^2-b)$ is a field, namely $\mathbb Q[\sqrt a,\sqrt b]$. If over this field neither $a+\sqrt a$ nor $a-\sqrt a$ are squares then your ring is the field $\mathbb Q[\sqrt a,\sqrt b,\sqrt{a+\sqrt a},\sqrt{a-\sqrt a}]$, which is just $\mathbb Q[\sqrt b,\sqrt{a+\sqrt a},\sqrt{a-\sqrt a}]$.
If those conditions are not satisfied, then your ring is not a field.


webform 5 access other webform tokens

Question: Is there a way to access tokens of another webform ? I have users of one role who need to evaluate in a webform files uploaded by users with another webform
Answer: This is not supported and could be a security issue because it would allow people to use tokens to pry into information available in other entities.

webform 5 access other webform tokens


What happens when std::move is called on a rvalue reference?

Question: Consider the following c++ programs:
string construct(string&& s) {
    // Passing a r-value reference as an argument to the assignment operator
    string constructed = s;
    return constructed;
}

int main() {
    string original = "Hello";
    string temp1 = construct(std::move(original));

    printf("%s\n", original.c_str()); // Prints "Hello", so original has not changed
    return 0;
}

Now a small change that I perform is calling std::move on an r-value reference argument:
string constructWithMove(string&& s) {
    // Passing a cast to an r-value reference using r-value reference as an argument.
    string constructed = std::move(s);
    return constructed;
}

int main() {
    string original = "Hello";
    string temp = constructWithMove(std::move(original));

    printf("%s\n", original.c_str()); // Prints "", original is set to the empty string, WHY???
    return 0;
}

So it looks like casting an r-value reference to an r-value reference induces something peculiar. Why in the first case the original string retains its value but not in the second?
Comment: _Now a small change that I perform is calling std::move on an r-value reference argument_  No, that's not what you did.  You called std::move on an l-value reference parameter.
Comment: @Eljay Is `string&&` not an rvalue reference?
Comment: The parameter takes an r-value argument by reference.  The local parameter is named, so it is not an r-value, and needs to be `std::move`d to be used as a r-value.
Comment: I think point you're missing is that after `string constructed = s;`, `s` *must* remain valid and *cannot* be moved from. After all, the very next line of code could be `string constructed2 = s;`. However, in `string constructed = std::move(s);`, you have given permission to move from `s` to construct the new string and thus it may change `s` to a valid but different state.
Comment: @eerorika Perhaps that should have been rephrased: you cannot call functions on arguments of reference type *because there is no such thing as an expression of reference type*. In `constructWithMove`, the expression `s` is an lvalue of type `string`. `std::move` is being called with an lvalue `string`. The declaration `string &&s` influence what *binds to `s`* (at the callsite) but does not affect the behavior of `s` within the function body. Actually calling `std::move` on an rvalue would be `std::move(std::move(s))` or something like `std::move(std::string(""))`.
Comment: @Eljay So if the local parameter is an l-value reference, then why calling `construct(original)` where `string original& = "Hello"` gives a compile time error? In this case `original` is an `l-value reference` as well. So why can't I pass `original` as an argument, but `std::move(original)` as an argument is allowed and inside the function the passed argument is an l-value reference? What am I confusing here?
Comment: @mercury0114 As I said: the way that you declare `s` in the signature of `construct` controls *how you can call it*, but inside the body of `construct` `s` is always an lvalue. If you declare `std::string &&s`, then you can only call `construct` on rvalues.
Answer:
What happens when std::move is called on a rvalue reference?

std::move casts the argument into an rvalue reference, which it returns.

Is std::move(r_value_reference_argument) undefined

No.

// Prints "", original is set to the empty string, WHY???

What's happening here?

Because the result from std::move is an r-value (x-value to be more specific). And being passed to a constructor of std::string, it invokes the move constructor. You are observing a string that was moved from.
Note that this moving leaves the original string in an unspecified state. It is not guaranteed to be empty, nor even different from what it used to contain. Neither is it guaranteed to not be empty.

OK, but why in the first case the original string is not empty?

Because s is an lvalue1, and therefore the copy constructor was used. The copy constructor leaves the original string unmodified.
1 Easy rule of thumb: If it is a name, then it is an l-value.
Comment: @mercury0114, `s` is an lvalue. Its type is irrelevant.
Comment: @mercury0114: because of that, `string constructed = s;` invokes copy-construction.  The compiler won't move from it unless you explicitly use `std::move`, as a later line in the function might also refer to `s` and expect it to still be in the state passed as a function argument.  Using `std::move()` is effectively promising the compiler you understand that and have coded accordingly.
Comment: OK, but why in the first case the original string is not empty? I modified the question a bit.
Answer:  // Prints "", original is set to the empty string, WHY???
Because you moved it.
Comment: To be precise, having been moved-from explains why it's *allowed* to empty, but doesn't require it to be so.  The general expectation of a moved-from value is that it will be left in a valid state for destruction.  I personally think it's desirable to design your own movable types so they'll be valid for reassignment or `clear()` then reuse, but this is a quality-of-implementation matter.  For types that don't document semantics for moved-from objects, you should only depend on "destructability" and not assume or depend on the moved-from object having any particular value or being reusable.
Comment: (In particular, some objects with pointers to dynamically allocated memory may swap buffers, so any text in the destination object ends up in the moved-from object, as a lazy way to provide the moved-from object with some heap-allocated memory in case it is reused, and defer deallocation).
Comment: How about throwing an exception?
Comment: `if (ive_been_moved) throw std::logic_error("hammer error: can't touch this");`
Comment: @super: you *never* want a destructor to throw an exception, so if there's something in the move-then-destruct processing that might throw, you definitely want that done at "move time".  Elijay's allusion to objects tracking/checking for moved-from state is rarely desirable: just a whole new surface of extra state/logic that can go wrong; when possible, just put the object back in a "normal" state where the expected operations will work or throw or whatever of their own accord.
Answer: string constructed = s;

This does not cause a move because s is not an rvalue. It is an rvalue reference, but not an rvalue. If it has a name, it is not an rvalue. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression.
string constructed = std::move(s);

This causes a move because std::move(s) is an rvalue: it's a temporary and its type is not lvalue reference.
There are no other moves in the program (std::move is not a move, it's a cast).
Comment: Is `std::move(s)` an rvalue or **rvalue-reference**? I thought `std::move` makes a cast to r-value-reference, no?
Comment: @mercury0114 it is an rvalue because it is a temporary. Its type is "rvalue reference to string". The two properties are orthogonal.


iOS Game that Runs Continuously in Background

Question: I'm trying to understand the most logical way of creating an iOS game that runs continuously in the background.
For example.. you have tower and enemy waves. The game has endless enemy waves even when the game exits. When you open the game again, it will retrieve the data that occurred when the app was closed.
I assume a database on a server would be the best solution. The values continuously increment on the server. The game connects to the server and retrieves the specific user's updated game data.
Answer: A server / database will only be helpful if you would like to present your information to multiple users, for a high score board for example.
In your case it seems that the easiest way to do it would be to store locally the time when the app was exited, and when you open the game again, you compare the current time to time stored before, and you calculate the impacts of all waves occuring between time now - time before.
Example: let's say you have 10 enemy monsters per minute, i exit the game i store the time (12:35), i open the game again at 12:45, 10 minutes difference * 10 enemy monsters have attacked my towers... From there you calculate the impact of 100 enemy monsters on your towers :)
Makes sense ?
And all without any complicated client / server programming.
Cheers
Comment: Well there are two matters here:

#1 A motivated hacker will always find a way to hack your game. And actually, making the client server programming right without any exploits might be a lot more complicated and prone to security issues.

#2 It's quite easy to encrypt your local data to make the hacker's life complicated :)
Comment: That makes sense. However, is this feasible on an iOS device? And doesn't this solution leave the game open to "cheating" such as if a user alters his or her machine time?
Comment: And yep the example i gave is feasible on an iOS device :) You just have to request the system time :)
Comment: @user2913669 It's a fairly common technique.  Any iOS game that work offline has to do this because you aren't allowed to stay running in the background.
Comment: thanks for the responses. so you're both saying accessing the time locally is the best solution? Could you elaborate on how to prevent users from say simply changing their system time?
Comment: I see 2 protections you can add against that:
First one would be to check that the time difference between your local stored time and the current time when restoring isn't too big. If the number is over a certain limit (say, more than 7 days), display an error message or anything you want and overwrite the time stored with the current time without earning anything. That will prevent users from changing system time to 10 years in the future :) Or you could even allow users to get credits for offline time only up to one day for example... Then problem is almost entirely solved.
Comment: Second one i can see is, IF the device is online, to call a web time api to check against the current time, but same issue as before, the device needs to be connected and the call is subject to a man in the middle attack anyway...
There is no way to really prevent it if the hacker is really really motivated, you can only make his job harder.
Comment: Isn't there a way to obtain the device's uptime, ie time since it was first booted or connected to iTunes? I remember something like that exists, resetting that is more intricate than just changing the clock in the Settings app.


Filter values similar

Question: I want filter values similar, I tried as following js code, but this code can not filter value 111 because this no ,. my html code is as following (Some do, some do not this: ,).
How can fix js code for filter all strings?
DEMO: http://jsfiddle.net/bNuRE/
HTML:

111

111, 222, 333

444, 111

222, 333

///////////////////////////////////////////////////////

111

777

333

666

JS:
var valeache = $('.oo').text().split(', ');
$.each(valeache, function (a, val) {
    $('.ww').filter(function () {
        return $(this).text() == val
    }).remove();
});

Comment: I don't understand what the problem is. Your demo seems to be working fine.
Comment: ok, `111` in `.oo` and `111` in `.ww` are similar, but don't work filter value for this. because this not have `, ` in `111` on `.oo`.
Comment: @TaylorGomez, is `333` in `.oo` also filtered?
Answer: Your construction of valeache is wrong.
You need to iterate over each .oo element to correctly construct valeache.
var valeache = $('.oo').map(function(){
    return $(this).text().split(', ');
}).get();
$.each(valeache, function (a, val) {
    $('.ww').filter(function () {
        return $(this).text().trim() == val;
    }).remove();
});

Comment: Uhm, I still see something odd there, give me a minute
Comment: This creates an array of arrays.
Comment: @undefined, are you sure about that? Notice, the "odd" thing that I described is that there's no evidence that `333` shall be filtered or not I'm afraid. I will wait for OP's reply :)
Answer: var valeache = null;

$('.oo').text(function(i, text) {
    valeache += text.replace(/\s/g,'') + ',';
})
valeache = $.unique( valeache .replace(/,$/,'').split(',') );

$.each(valeache, function (a, val) {
    $('.ww').filter(function () {
        return $(this).text() == val
    }).remove();
});

Demo: http://jsfiddle.net/xfSK4/3/
Answer: It's not entirely clear to me what you're trying to do.  Are you simply trying to remove the elements from the target list whose value match one of the (possibly comma-separated) values from any of the elements of the source list?  If so, I think you can do it more easily:
var vals = $.map($('.oo'), $.text).join(", ").split(", ");

$('.ww').filter(function () {
    return $.inArray($(this).text(), vals) > -1;
}).remove();

Demo: http://jsfiddle.net/CrossEye/MVGLQ/1/
That initial array contains duplicates, but that shouldn't be a problem.

Filter values similar


Are $l^p$ and $(l^q)'$ canonically isomorphic or just isomorphic?

Question: As we know from basic functional analysis, the sequence spaces $l^p$ and $(l^q)'$ are isometrically isomorphic.
Are they considered to be canonically isomorphic or just isomorphic?
Based on the replies to this question, I'd guess that they are indeed canonically isomorphic because the map between them doesn't seem to require a choice of a basis. But I'm not entirely sure.
Answer: The usual (isometric) isomorphism between $\ell^p$ and $(\ell^q)^*$, where $1/p+1/q=1$, is given by
$$\Phi:\ell^p\to(\ell^q)^*$$
$$\ell^p\ni(x_n)_{n=1}^\infty:=x\mapsto\Phi(x):\ell^q\to\mathbb{C}$$
where
$$\Phi(x)(y_n)_{n=1}^\infty=\sum_{n=1}^\infty x_ny_n $$
for all $(y_n)\in\ell^q$.
Based on the discussion in the linked post, since there were no "choices" involved in the definition of this isomorphism, we can say that this is a canonical isomorphism. Also, as mentioned already, this term does not have a precise meaning, so we usually say that something is "canonical" when it is "expected" to be defined in this way. This map is definitely of that form, the reason behind that being measure theory:
We can actually see $\ell^p$ as the $L^p$ space of $\mathbb{N}$ with the counting measure and $(x_n)\in\ell^p$ is nothing but a function $f$ such that $\int|f|^p<\infty$. We send such an element of $L^p$ to the linear functional $g\mapsto\int f\cdot g$, which is the most "canonical" thing to do. By the famous H"older inequality, this is bounded on $L^q$, which again in our case is identified with $\ell^q$. This is precisely what our map $\Phi$ does.
Comment: This isomorphism looks a bit like an inner product. Can this also be seen through the lens of the Riesz representation theorem? (although I know that the theorem assumes a Hilbert space and $l^p$ is only Hilbert for $p=2$). Thanks +1
Comment: @Leo Well, I don't think so. Also, I wouldn't say that it looks like an inner product; maybe you have this impression because you are thinking of the Hilbert space $\ell^2$ and its inner product, but in general there is no reason to expect that, or at least that's what I think.


How to use more than 2 versions on jquery?

Question: I want to use bootstrap theme and it requires jquery 1.9, but when I set 1.9, ajax enabled views do not work. I am using views 3.14. There are few contrib modules which require older version of jquery. So in jquery_update I can set "default drupal" for admin pages and 1.7 for the site.
How to get 1.9 as well for my site with no conflicts?
I have found jquery multi module during search, but do not know if it is what I am looking for.
Secondly, Can I use this module with jquery update enabled?
Comment: Worth noting that the answer to this can be found on the project page of the jQuery multi module.
Answer: Since you need to run multiple versions of jQuery for different contrib modules I would say the jQuery multi module would be the easiest solution (although I don't know the specifics of your requirements).
The 7.x-2.x branch of jQuery update is supported with jQuery multi.
For example, you could use Drupal default jQuery for admin pages, jQuery 1.7 for non-admin pages and jQuery 1.9 for the specific plugins/modules that require it.
Or alternatively you can use 1.9 as the main version and 1.7 for specific plugins/modules.
Whichever works best for your site.
Usage instructions for the jQuery multi module can be found in its README.txt file when you download it.


When pushing a new view controller to my navigation controller, I get returned the the same view controller I tapped from instead of the new one

Question: I have a UIViewController that has a UITableView added as a subview. When I tap on a cell to return a new UIViewController (detail view controller, empty aside from background color) I get returned the same starting view controller and table view.
I am using navigationController.pushViewController(), but I have the same issue with present(). I am led to believe that I am calling the wrong view controller but when using the debug view hierarchy my detail view controller appears to be a copy of the main view controller. I can't figure out why because the detail view controller is mostly empty. I'm also sure I have the scene delegate set up correctly with the navigation controller set to the root view.
This is the tableView code, the variable "countries" is an array of strings. I have tried using self.navigationController?.pushViewController() and nothing changes.

extension ViewController : UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return countries.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FlagCell.identifier, for: indexPath) as! FlagCell
        let country = countries[indexPath.row]
        let image = UIImage(named: country)
        cell.flagImageView.image = image
        cell.countryNameLabel.text = country
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = FlagViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
}

Here is the code for the detail view controller.
import UIKit

class FlagViewController: ViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .systemMint
    }
}

Answer: This line is likely your problem:
let vc = FlagViewController()

If you create a view controller like that, it won't get views from a storyboard or nib-file. The only way I know of to create a view controller by calling an initializer with no parameters like this is if that view controller implements loadView() method and builds its view hierarchy in code.
Unless you're created your FlagViewController's view hierarchy in code, you probably want to load it from a storyboard using the UIStoryboard method instantiateViewController(withIdentifier:).
Comment: Ok to update, the app is sending 2 views, the main view and the detail view. If I reduce the constraints, I can see a new tableview load underneath the detail view.
Comment: You said "the app is sending 2 views..." I don't know what "sending views" means. Use specific, appropriate terms like "pushing" (onto a nav stack) or "presenting" (modally.)
Comment: Also, don't conflate views and view **controllers**. A view is something that shows up on-screen. A view controller implements business logic and manages views. They are not the same thing, and you'll cause confusion (to yourself and others) if you mix up the terms.
Comment: Ok thank you for the explanation and advice. My detail view controller class was conforming to "ViewController" (The name of my main view controller) instead of "UIViewController" so it was pushing the subviews from both classes.
Answer: Thank you it seems that I needed more code for the view hierarchy, I am confused because I've seen many tutorials and articles that had identical code to mine to do similar jobs but it is what it is. I used viewDidLoad() but please tell me if it is recommended to use didLoad()
Heres the final update of the new viewController
let flagView: UIView = {
    let flagView = UIView()
    flagView.backgroundColor = .systemMint
    return flagView
}()

override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
}

// MARK: - UI Setup
private func setupUI() {
    self.view.addSubview(flagView)
    flagView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        flagView.topAnchor.constraint(equalTo: self.view.topAnchor),
        flagView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
        flagView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
        flagView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),

        flagView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        flagView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
    ])
}

Comment: You are missing the key point from my answer: Every time your user selects a cell in your `ViewController` class, you are creating a new instance of your `FlagViewController` and presenting it on top of the existing pile of modals in your UI. That is wrong.


AbstractMethodError when calling overridden method of abstract class from a class compiled at runtime

Question: Let me first summarize what exactly I'm trying to do. Basically, I'm using the JavaCompiler package to compile a class at runtime that extends my superclass "Player". The only thing that I know will be in the subclass is that it will extend Player and override the abstract method calcMove(). To load the class at runtime after it has been compiled, I create a URIclassloader object to load the class file after it has been created. The problem is that when I try to run the calcMove method from the instantiated object (by using java.lang.reflect)
Here's bascially what I'm doing:
//to hold the compiler output
ByteArrayOutputStream compilerOut = new ByteArrayOutputStream();

                //compile
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

int compilationResult = compiler.run(null, compilerOut, compilerOut, playerFile.getAbsolutePath());

if (compilationResult == 0) {

System.out.println("File " + playerFile.getName() + " compiled successfully");

} else {

//code 99 as compile error
System.err.println(compilerOut.toString());
System.exit(99);
}

Once the file is compiled, I use this code to make a uriclassloader to load the class (the upload folder contains the source and class files) The className is determined from the file name. Then I use java Reflection to instantiate the class as an object and cast it as a Player:
URL classUrl = new File("upload").toURI().toURL();

ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{classUrl}, ClassLoader.getSystemClassLoader());
                classLoader.loadClass(className).asSubclass(Player.class);

Class<?> studentCustomClass = Class.forName(className, true, classLoader);

Constructor<?> constructor = studentCustomClass.getConstructor();
Player studentPlayer = (Player) constructor.newInstance()

The instantiation apparently works until I get to where it calls calcMove. I create a new "Game" class that takes 2 Player arguments, within this Game class I call the calcMove() method from the custom class objects (cast as Players). However I'm getting an AbstractMethodError Exception because its trying to call the abstract calcMove method from Player instead of the implemented version from the subclass.
So, I'm wondering, is there some reason why it's trying to call the abstract version from the parent class instead of the version from the class I just compiled? (As far as I can tell, java considers the object I create to be a type of the subclass class rather than just a Player class , which I couldn't instantiate anyway since its abstract) Right now I'm using java Reflection to force it to call the calcMove fucntion from the object
Method calcmove = players[0].getClass().getMethod("calcMove");

calcmove.invoke(players[0]);

I'd like to avoid using reflect at this point in the code for security reasons. So why does this work, but this:
players[0].calcMove();

Gives me an AbstractClassError?
Comment: This looks like code is compiled against some other version of your class than the one actually available in runtime, like such error could be thrown if method was changed from normal one to abstract one or other way around.
Answer: I've managed to find a solution that works. If I declare the abstract method calcMove in Player to be protected, then it properly uses the calcMove from the subclass without using reflection to force it. I'm assuming this is because it can't call the protected method in Player so it calls the public/package access method in the subclass (since overridden methods can have higher levels of visibility than the method they override I've discovered) I'm not entirely sure why this works though.


Perform authoritative DNS A record lookup with single command?

Question: To get the authoritative A record for the apex of a domain I'm using:
$ nslookup -q=ns example.com
Server:     184.108.40.206
Address:    220.127.116.11#53

Non-authoritative answer:
example.com nameserver = a.iana-servers.net.
example.com nameserver = b.iana-servers.net.

Authoritative answers can be found from:
b.iana-servers.net  internet address = 126.96.36.199
a.iana-servers.net  internet address = 22.214.171.124

$ dig -t a +noall +answer example.com @a.iana-servers.net
example.com.        86400   IN  A   18.104.22.168

Is there a better way?  Also not all name servers are created equally so b.iana-servers.net takes much longer (x100, sometimes times out) to respond than a.iana-servers.net, it'd be very useful if there was an easy way to query them all and returned the result of the first to respond.
Answer: Your example is broken. The delegating name server information you fetch may be outdated, so the name server you query for the authoritative information may no longer be an actual authoritative server for the requested domain. In order to get as close as possible to having guaranteed authoritative-right-now information, you have to recurse from the root every single time, since every step on the way has the potential to change at any moment.
That said, why do you think you want this? You're trying to bypass the design of DNS, so it will never be easy or convenient. What reason do you have to go to all this extra effort?
Comment: The basic recursion algorithm is described in section 5.3.3 of RFC 1034. It's not really that complicated, it's just all the details that make it tricky to implement. The implementation I'm most familiar with is a somewhat odd one in Perl, which you can find [here](https://github.com/dotse/zonemaster-engine/blob/master/lib/Zonemaster/Recursor.pm).
Comment: Thanks for the answer.  The motivation is two fold.  Firstly when I change a DNS record the original is almost always in my local cache so I want a second way to double check what will eventually be propagated out to the rest of the DNS.  Secondly when I'm looking for the current TTL value of a record I get the time remaining when viewing the cache, where as I want to see what the current authoritative record has set for the TTL value.  You mentioned you could recurse to the root, could you give me a pointer on a tutorial or tool that might explain / do that?  Thanks.


File upload broken on node form

Question: I have the same problem described in I get image field upload errors with a custom node_add() form.
How do I add these lines to the menu item array?
<code>'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',
</code>
I get the following errors:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 800 of C:\xampp\htdocs\semt1\includes\form.inc).
  Notice: Undefined index: #node in comment_form_node_form_alter() (line 1194 of C:\xampp\htdocs\semt1\modules\comment\comment.module).
  Notice: Trying to get property of non-object in comment_form_node_form_alter() (line 1211 of C:\xampp\htdocs\semt1\modules\comment\comment.module).
  Notice: Undefined index: #node in location_node_form_node_form_alter() (line 14 of C:\xampp\htdocs\semt1\sites\all\modules\location\location_node.module).
  Notice: Trying to get property of non-object in location_node_form_node_form_alter() (line 15 of C:\xampp\htdocs\semt1\sites\all\modules\location\location_node.module).
  Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
  Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
  Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
  Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
  Notice: Undefined index: #node in translation_form_node_form_alter() (line 135 of C:\xampp\htdocs\semt1\modules\translation\translation.module).
  Notice: Trying to get property of non-object in translation_form_node_form_alter() (line 135 of C:\xampp\htdocs\semt1\modules\translation\translation.module).
  Notice: Undefined index: field_im in file_ajax_upload() (line 271 of C:\xampp\htdocs\semt1\modules\file\file.module).
  Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of C:\xampp\htdocs\semt1\modules\file\file.module).

I am using this module.
Comment: This seems like a very localized issue concerning a non-Drupal hosted module.  You would probably be better off asking whoever wrote the original code.
Answer: Try this:
<code>function yourmodule_menu_alter(&$items) {
  $items['system/ajax']['file path'] = drupal_get_path('module', 'node');
  $items['system/ajax']['file'] = 'node.pages.inc';
}
</code>
Comment: I try this function  bus still same error when upload file
Comment: if you have another solution tell me about
Comment: did you flushed all chaches?
Comment: yes I clear all cache
Comment: Have you replaced `yourmodule` in the function's name with your actual module name?
Comment: of course yes ...
Comment: function block_create_node_menu_alter(&$items) {
  $items['system/ajax']['file path'] = drupal_get_path('module', 'node');
  $items['system/ajax']['file'] = 'node.pages.inc';

}
Comment: does not have another solution?
Comment: sorry man, it worked for but I was using a custom page, not this module (block_create_node)
Comment: ok but how to use custom page?

File upload broken on node form


Revert changes to a specific file from a specific commit

Question: A few weeks ago (i.e. many commits ago), I made a git commit that touched many files.  Most of the commit was great.
However, I'd now like to undo the changes that I'd made to just one of those files, but I don't want to override any changes that had been made to that file after that commit.
Is there a way for me to revert a specific commit but only on one of the files in that commit?
Comment: Related, but not duplicate (I think): [Reverting a single file to a previous version in git](http://stackoverflow.com/q/2733873/456814).
Comment: See also [How do I reset/revert a specific file to a specific revision using Git?](http://stackoverflow.com/q/215718/456814).
Answer: Get a patch-ready diff for that file in that commit, and then reverse-apply the patch:
git show <commit-id> -- <path> | git apply -R -

Make sure you like the result, and if so, add and commit with appropriate message.
Comment: thanks but this failed with: `error: : patch does not apply`
Comment: That implies something in the changes has changed since then, i.e., there's a conflict.  You can either: try adding `-3` (aka `--3way`) to use git's merge mechanisms; or add `--reject` (in both cases, to the `git apply` options) but you must then manually resolve the conflicts.
Comment: @Cupcake: `git apply` wants to take a file name; documentation says `- can be used to read from the standard input`.  Was not sure off-hand if it would read stdin anyway (I've always fed it files, at least as far as I can recall).
Comment: I'd just like to point out that the naive way to get a reverse patch would be to simply do `git diff  ^ --  | git apply`, but I didn't know that you could just use `git apply --reverse`, that's definitely genius! Why does `git apply -R -` have that final dash at the end though?
Comment: Thanks! I used `git show  --  | git apply -3 -R -`
Comment: This is awesome! Thanks!
Answer: Torek's answer is definitely better (and simple!), but for the sake of completeness, I wanted to add a few alternative (some naive) solutions to this problem.
Solution 1: Reverse Patch (naive, compared to Torek's solution)
This is very similar to Torek's solution. To undo the changes to a specific file that were made by a specific commit, just get a reverse diff of that commit by reversing the arguments to git diff:
git diff <commit> <commit>^ -- <filepath> | git apply

Normally, to get the changes introduced by <commit>, you use the order
git diff <commit>^ <commit>

but by reversing the order, you end up getting the inverse of those changes, which is a valid diff that can be used as a patch!
Solution 2: Revert All Files, then Only Commit Changes to Specific Files (very naive)
A more naive solution would be to revert the commit that added the changes that you want to undo, but don't commit the revert. Then just remove all the changes to the other files from the index and working copy:
git revert --no-commit <commit>

# Unstage all changes that revert all files
git reset -- .

# Stage and commit just the reversion changes that you want
git add <yourFile>
git commit -m "Revert changes to <yourFile> from <commit>"

# Undo all reversions changes to the other files
git checkout -- .

This is necessary because git revert doesn't revert changes to individual files, it currently only reverts entire commits.


Should I exclude predictor variables if used to create a new one?

Question: I have a dataset that includes race, gender, income, and family size. In addition, a variable for "sliding fee scale" tier is included, which is determined by income and family size. Should income and family size be excluded when fitting data to a logit model? Or should I first include all variables, examine correlations and then conduct a feature selection procedure to determine whether to include/exclude income and family size?
X1: Gender
X2: Family Size
X3: Income
X4: Tier (determined by X2 and X3)
Answer: If you include all variables you will almost surely get high collinearity. In my view, the best diagnostic for this is the condition index; however, with non-continuous variables you may be better served by something like the 'perturb' package in R. Or, you can just assume the models would have a problem. (Especially since the levels of condition index that are problematic for logistic regression are, as far as I know, not well established).
You can compare models with different combinations of variables: a) Income only b) Family size only c) Income and family size and d) Tier.
I would base model comparison at least in part on substantive concerns; supplemented with AIC or BIC or some other IC. However, by excluding tier you can also look at interactions among income and family size.
Comment: Thank you Mr. Flom. You've helped me with a good number of options to try.


Animating a 2D plot (2D brownian motion) not working in Python

Question: I am trying to plot a 2D Brownian motion in Python but my plot plots the grid but does not animate the line.
Attempted at performing this plot is below,
<code>!apt install ffmpeg

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation

np.random.seed(5)

# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

def generateRandomLines(dt, N):
    dX = np.sqrt(dt) * np.random.randn(1, N)
    X = np.cumsum(dX, axis=1)

    dY = np.sqrt(dt) * np.random.randn(1, N)
    Y = np.cumsum(dY, axis=1)

    lineData = np.vstack((X, Y))

    return lineData

# Returns Line2D objects
def updateLines(num, dataLines, lines):
    for u, v in zip(lines, dataLines):
        u.set_data(v[0:2, :num])

    return lines

N = 501 # Number of points
T = 1.0
dt = T/(N-1)

fig, ax = plt.subplots()

data = [generateRandomLines(dt, N)]

ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))

ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_title('2D Discretized Brownian Paths')

## Create a list of line2D objects
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]

## Create the animation object
anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines), interval=30, repeat=True, blit=False)

plt.tight_layout()
plt.show()

## Uncomment to save the animation
#anim.save('brownian2d_1path.mp4', writer=writer)
</code>
However, instead of performing the plot the program is printing,

How do I animate this plot? I am new to python so I apologize in advanced if this is an easy question.
I found this question on http://people.bu.edu/andasari/courses/stochasticmodeling/lecture5/stochasticlecture5.html , there is a walkthrough of how this code came to being.
Comment: On my system (pycharm under Windows) it works after removing `matplotlib.use("Agg")` and `writer = Writer(...`. And adding `import numpy as np`.
Comment: Thanks at JohanC, I did the same and seems to work, my problem now is it is saving well as a GIF but not showing as a GIF in the notebook.
Answer: Thanks to @JohanC 's help got it to work.
<code>#!apt install ffmpeg
#!brew install imagemagick

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

from matplotlib import animation, rc
from IPython.display import HTML, Image # For GIF

rc('animation', html='html5')
np.random.seed(5)

# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

def generateRandomLines(dt, N):
    dX = np.sqrt(dt) * np.random.randn(1, N)
    X = np.cumsum(dX, axis=1)

    dY = np.sqrt(dt) * np.random.randn(1, N)
    Y = np.cumsum(dY, axis=1)

    lineData = np.vstack((X, Y))

    return lineData

# Returns Line2D objects
def updateLines(num, dataLines, lines):
    for u, v in zip(lines, dataLines):
        u.set_data(v[0:2, :num])

    return lines

N = 501 # Number of points
T = 1.0
dt = T/(N-1)

fig, ax = plt.subplots()

data = [generateRandomLines(dt, N)]

ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))

ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_title('2D Discretized Brownian Paths')

## Create a list of line2D objects
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]

## Create the animation object
anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines),
interval=30, repeat=True, blit=False)

plt.tight_layout()
plt.show()

# Save as GIF
anim.save('animationBrownianMotion2d.gif', writer='pillow', fps=60)

Image(url='animationBrownianMotion2d.gif')
## Uncomment to save the animation
#anim.save('brownian2d_1path.mp4', writer=writer)
</code>


Como resolver este erro 'Undefined variable' ao acessar uma view no laravel 5.1?

Question: O meu problema é o seguinte:
Carreguei os dados para a view banner, que está incluída na view main, esta por sua vez está expandida na view home, está funcionando bem. Mas quando tento acessar outra view (view create-lema) em que também encontra-se expandida a view main, surge o seguinte erro:

Undefined variable: lema (View: C:\xampp\htdocs\GEIGRE\resources\views\paginas\banner.blade.php)
  (View:
  C:\xampp\htdocs\GEIGRE\resources\views\paginas\banner.blade.php)
  (View:
  C:\xampp\htdocs\GEIGRE\resources\views\paginas\banner.blade.php)

Preciso de ajuda. E desde já, agradeço.
Aqui vai o código.
LemaController
public function create()
{
    $lema=new Lema;
    $lema->texto_lm = Input::get('texto');
    $lema->refBilblica_lm = Input::get('refBiblica');
    $lema->status_lm = Input::get('status');
    $lema->save();
    return redirect('/');
}

HomeController
use App\Lema;
use Redirect;

class HomeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $lema = Lema:: where('status_lm', 'Activo')->get();

        return view('home')->with('lema',$lema);
    }
 }

Route
Route::get('criar-lema', function () {
    return view('lema.create-lema');
});

Route::post('criar-lema', 'LemaController@create');

Route::get('/', 'HomeController@index');

view banner

         Iniciar Sessão

            <?php foreach ($lema as $key => $value): ?>

{!! $value->texto_lm  !!}

{!! $value->refBilblica_lm  !!}

            <?php endforeach; ?>

view main
<!DOCTYPE HTML>

    @include("paginas.head")

        @include("paginas.banner")
        @include("paginas.menu")

            @yield("content")

view home
@extends('main')

@section('content')

Canguru

Tubarão

Cão

            Previous

            Next

Thumbnail label

...

Button Button

@endsection

view create-lema
@extends('main')

@section('content')

NOVO LEMA

        <form action="{{url('criar-lema')}}" method="post" enctype="multipart/form-data">
            {!! csrf_field() !!}

                Texto
                <input name="texto" type="text" class="form-control" id="texto" placeholder="Insira aqui o texto do lema">

                Ref. Bíblica
                <input name="refBiblica" type="text" class="form-control" id="refBiblica" placeholder="Referência Bíblica">

                Status
                <input name="status" type="text" class="form-control" id="status" placeholder=" insira 'Activo' ou 'Não Activo'">

            <button type="submit" class="btn btn-success">Salvar</button>
        </form>

@endsection

Answer: Acredito que o problema seja esse aqui:
Route::get('criar-lema', function () {
    return view('lema.create-lema');
});

No seu método index(), você está passando o lema no método ->with(). Já no método acima, você está retornando a view direto na route.
Se você passar rota para uma controller, você pode reutilizar a lógica de como você está pegando os lemas e passar novamente para a view sempre que precisar.  Exemplo:
ROTA:
Route::get('criar-lema', 'LemaController@showCreate');

CONTROLLER (A principal, Controller.php)
protected function getLemas() {
    return Lema::where('status_lm', 'Activo')->get();
}

LEMA CONTROLLER
public function showCreate() {
    return view('lema.create-lema')->with('lema', $this->getLemas());
}

public function create()
{
    $lema=new Lema;
    $lema->texto_lm = Input::get('texto');
    $lema->refBilblica_lm = Input::get('refBiblica');
    $lema->status_lm = Input::get('status');
    $lema->save();
    return redirect('/');
}

HOME CONTROLLER
public function index() {
    return view('home')->with('lema', $this->getLemas());
}

Comment: Desta forma Resultou!!! Está a funcionar do jeito que queria. Muito obrigado @Guh.


What does this site offer that Law.SE's immigration-related tags don't?

Question: I'm sure I'm not the first ex-pat to join this site, then be a little surprised to, first, see that 100% of non-closed questions on the front page were legalistic in nature (status, permits, visas, etc), and second, to learn that this is largely by design.
I'm having trouble understanding when I would actually use this site:

My actual questions to do with living as an ex-pat will be off-topic here (or at least, they'll turn into tedious close-reopen conflicts). Anything that isn't directly related to my legal status can be interpreted as also affecting locals (particularly incomers from other regions). So, for these, I'll use forums, or, if possible, I'll try to make them on topic at travel.SE or workplace.SE
If and when I have questions about legal status issues, I'll ask them at Law.SE, because that's where the lawyers are

Which leaves me puzzled because I'm an expat with expat related questions and knowledge, and I'm an enthusiastic long-standing SE user, but I can't see any situation when I'd use the SE expat site.
Every question I can see on the homepage, I think I'd personally have asked on Law.SE - but maybe there's something I've overlooked? What does this site offer that Law.SE doesn't?

Edit: I just saw the closely related Expatriates sucks because most questions are about Immigration. One of the answers there suggests such questions would be welcome, but this shows that in reality, that's not true and "edge cases" get closed.
Comment: I'm not very familiar with Law.SE (or law/lawyers in general). Does that site cover all bureaucratic procedures?
Comment: As I said in the [un-linked answer](http://meta.expatriates.stackexchange.com/a/285/127). I think this is something we can, and should, fix. I am not sure how, but we need to work on it. I brought it up in [chat](http://chat.stackexchange.com/transcript/message/31006450#31006450).
Comment: @StrongBad Clarifying the policy, and adding examples "this is okay / this is borderline but still okay / this is where the line gets crossed" would be a good start. Separate thought, has anyone here considered going the opposite way - *embracing* being the site for migration rule experts, taking the visa questions from Travel.SE where they're currently unpopular with many users, becoming "Visas & Migration" focusing on attracting experts in that field, meanwhile Travel.SE deals with all traveller-life questions regardless of duration of stay?
Comment: @user568458 excellent points and lots to think about. Will you post that in chat. I think that might be the best place to have the wider discussion.
Comment: @StrongBad Sorry I'm getting distracted too much today already. Feel free to take it and run with it!
Answer: There can be overlaps between StackExchange sites, and that's usually not a problem. You are right, that a lot of strictly law related questions are okay on Law.SE, while some workplace related questions are okay on Workplace.SE. For Travel, they have a no-expat policy (hence this site was born), so I wouldn't say that their site covers our though.
While I'm not really active on Law.SE and don't know their definition of 'on-topic', if you check the home page, there are a few questions that are probably not on topic there, or on any of the other SE sites you've mentioned:

How to become an expat at 22 in a stable 1st world country This is a soft question, not really suited for any of the sites
Can I go as a Skilled Migrant to NZ? This is also more like a soft question, similar to the previous one
Help! I'm buying a car registered in Slovakia for use in Spain and the Uk While this might be on topic on Law.SE, from what I've seen there aren't many car registration questions on that site, while it is definitely on topic here
Is Civic Integration exam needed for (non-EU) wife of Italian citizen to join him in the Netherlands? This is also something that's might not be on topic on Law

And there are some others as well.
Although you do have a good point in pointing it out that we do have some trouble figuring out what "something locals would face as well" mean exactly, especially since a lot of these things might come as a "cultural shock" for someone who just moved from a differnt culture. That's why questions like GEZ / ARD ZDF Germany Radio - can I ask not to pay for it? or Postal Service in France are on-topic, and not closed.
Comment: @user568458 True, and it would be good to have something like that. As a general note: if you can describe in the question why you think it's more relevant to an expat than to a local, it usually stays open
Comment: @user568458 we are still a young/beta site trying to figure out where the line it. It is useful if people ask questions that push our boundries. That is the way we figure out where the line is.
Comment: Interesting, those two questions at the bottom look quite close to the sort of thing I'd want to ask but would anticipate becoming a tedious battle. Right now the policy seems pretty unclear, it'd be great to see some kind of clear "here is where the line is" with examples of what is just on and what is just off.
Comment: [Looks like you guys decided that all "edge cases" get closed](http://meta.expatriates.stackexchange.com/questions/282/honestly-why-is-my-question-off-topic)
Comment: @user568458 if you check even there there is a slight disagreement. You can always open up a meta post if you feel that something was closed unnecessarily


Retrieving movie codec under iOS?

Question: I am trying to find the codec used to compress a movie. I am sure if I need to somehow use CMFormatDescription and get a CMVideoCodecType key. I am stuck as to how to get past the metadata array. Any ideas on how to retrieve the codec?
AVURLAsset* movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
NSArray *tracks = [movieAsset tracksWithMediaType:AVMediaTypeVideo];

if ([tracks count] != 0) {
    AVAssetTrack *videoTrack = [tracks objectAtIndex:0];

    //
    // Let's get the movie's meta data
    //

    // Find the codec
    NSArray *metadata = [movieAsset commonMetadata];
 }

Comment: have you found a solution for this one?
Answer: A Swift approach to retrieving the audio and video codec associated with a movie:
func codecForVideoAsset(asset: AVURLAsset, mediaType: CMMediaType) -> String? {
    let formatDescriptions = asset.tracks.flatMap { $0.formatDescriptions }
    let mediaSubtypes = formatDescriptions
        .filter { CMFormatDescriptionGetMediaType($0 as! CMFormatDescription) == mediaType }
        .map { CMFormatDescriptionGetMediaSubType($0 as! CMFormatDescription).toString() }
    return mediaSubtypes.first
}

You can then pass in the AVURLAsset of the movie and either kCMMediaType_Video or kCMMediaType_Audio to retrieve the video and audio codecs, respectively.
The toString() function converts the FourCharCode representation of the codec format into a human-readable string, and can be provided as an extension method on FourCharCode:
extension FourCharCode {
    func toString() -> String {
        let n = Int(self)
        var s: String = String (UnicodeScalar((n >> 24) & 255))
        s.append(UnicodeScalar((n >> 16) & 255))
        s.append(UnicodeScalar((n >> 8) & 255))
        s.append(UnicodeScalar(n & 255))
        return s.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    }
}

Answer: I think it's definitely harder than it should be
    #define FourCC2Str(code) (char[5]){(code >> 24) & 0xFF, (code >> 16) & 0xFF, (code >> 8) & 0xFF, code & 0xFF, 0}

    if ([assetTrack.mediaType isEqualToString:AVMediaTypeVideo])
    {
        for (id formatDescription in assetTrack.formatDescriptions)
        {
            NSLog(@"formatDescription:  %@", formatDescription);

            CMFormatDescriptionRef desc = (__bridge CMFormatDescriptionRef)formatDescription;
            //CMMediaType mediaType = CMFormatDescriptionGetMediaType(desc);

            // CMVideoCodecType is typedefed to CMVideoCodecType

            CMVideoCodecType codec = CMFormatDescriptionGetMediaSubType(desc);

            NSString* codecString = [NSString stringWithCString:(const char *)FourCC2Str(codec) encoding:NSUTF8StringEncoding];
            NSLog(@"%@", codecString);

        }
    }

Answer: A slightly more readable version of @jbat100's answer (for those who were as confused as I was with that #define FourCC2Str, hah)
// Get your format description from whichever track you want
CMFormatDescriptionRef formatHint;

// Get the codec and correct endianness
CMVideoCodecType formatCodec = CFSwapInt32BigToHost(CMFormatDescriptionGetMediaSubType(formatHint));

// add 1 for null terminator
char formatCodecBuf[sizeof(CMVideoCodecType) + 1] = {0};
memcpy(formatCodecBuf, &formatCodec, sizeof(CMVideoCodecType));

NSString *formatCodecString = @(formatCodecBuf);

Answer: NSArray *formatDescriptions = videoTrack.formatDescriptions;
NSString *formats = [self mediaFormatWithFormatDescriptions:formatDescriptions];

- (NSString *)mediaFormatWithFormatDescriptions:(NSArray *)formatDescriptions {
    NSMutableString *format = [[NSMutableString alloc] init];
    for (int i = 0; i < formatDescriptions.count; i++) {
        CMFormatDescriptionRef desc =
            (__bridge CMFormatDescriptionRef)formatDescriptions[i];
        NSString *type = FourCCString(CMFormatDescriptionGetMediaType(desc));
        NSString *subType = FourCCString(CMFormatDescriptionGetMediaSubType(desc));
        [format appendFormat:@"%@/%@", type, subType];
        if (i < formatDescriptions.count - 1) {
            [format appendString:@","];
        }
    }
    return format;
}

static NSString * FourCCString(FourCharCode code) {
    NSString *result = [NSString stringWithFormat:@"%c%c%c%c",
                        (code >> 24) & 0xff,
                        (code >> 16) & 0xff,
                        (code >> 8) & 0xff,
                        code & 0xff];
    NSCharacterSet *characterSet = [NSCharacterSet whitespaceCharacterSet];
    return [result stringByTrimmingCharactersInSet:characterSet];
}

Retrieving movie codec under iOS?


Killing form is negative definite

Question: Let $G$ be a compact connected semisimple Lie group and $\frak g$ its Lie algebra. It is known that the Killing form of $\frak g$ is negative definite. What about the Killing form $B$ of the complex semisimple Lie algebra ${\frak g}_{\Bbb C}={\frak g}\otimes\Bbb C$?
In particular:

If $X\in{\frak g}_{\Bbb C}$ lies in the Cartan subalgebra ${\frak h}_{\Bbb C}\subseteq{\frak g}_{\Bbb C}$ and $B(X,X)=0$, does that imply that $X=0$?
Answer: Take the compact simple real Lie algebra $\mathfrak{su}(2)$. The Killing form is negative definite. Its complexification is isomorphic to the Lie algebra $\mathfrak{sl}_2(\mathbb{C})$, where the Killing form is non-degenerate, but does not satisfy $B(x,x)=0$ implies $x=0$. If $x,y,h$ is the standard basis, then $B(x,x)=0$.
Comment: But does $x$ lie in a Cartan subalgebra as in my question?
Comment: No, but you have changed this afterwards, right ?
Answer: The Killing form of $\mathfrak g_{\mathbb C}$ is complex bilinear by construction, so in any complex subspace of $\mathfrak g_{\mathbb C}$ you find non-zero vectors which are isotropic.
Comment: Well, in any subspace of dimension $\ge 2$, right?

Killing form is negative definite


Are there versions of the axiom of choice that restrict the size of the factors?

Question: One formulation of the axiom of choice is that an arbitrary product of nonempty sets must be nonempty. The axiom of countable choice AC$_\omega$ is known to be strictly weaker than AC, but still independent of ZF; it is equivalent to the statement that a countable product of nonempty sets is nonempty.
Can one obtain a nontrivial but weaker version of AC by restricting the size of the factor sets in the product, rather than the size of the index set over which the product is taken?
For a non-example, say that AC$_z$ is the statement that an arbitrary product of countable sets is nonempty.  Certainly ZF + AC implies ZF + AC$_z$. But it seems to me that ZF implies AC$_z$ even without AC: Let the index set be $\mathcal C$.  Since for each factor set $s\in\mathcal C$ in the product there is a bijection $f_s: s\leftrightarrow \Bbb N $,  the set $\{f_s(0): s\in\mathcal C\}$ is an element of the product.; Or equivalently if $\mathcal C$ is a family of countable sets, then the function $c:{\mathcal C} \to \bigcup{\mathcal C}$ which takes $s\mapsto f_s(0)$ is a choice function for $\mathcal C$, and exists in ZF without need for  AC$_z$ as a separate axiom.
Let's say that the  "restricted choice axiom" $AC_\Phi$ is the statement

If $\mathcal C$ is an arbitrary collection of sets, and $\Phi(X)$ holds for each element $X\in\mathcal C$,  there is a choice function for $\mathcal C$.

Depending on $\Phi$, $AC_\Phi$ could be very weak, or it could be as strong as AC itself. My question is:

Is there $\Phi$ such that ZF + $AC_\Phi$ proves strictly more than ZF but strictly less than ZFC?

If I've made any errors of fact or logic in this post, I would be grateful for corrections.
Comment: Cohen showed countable choice cannot be proven in ZF without choice, despite what your intuition tells you.
Comment: Did I say anything that implied otherwise?  (This is a serious question. I didn't think I had, but this is a very tricky area and not all the implications are clear to me.)
Comment: Maybe I misunderstood your remark about ZF implying $AC_Z$ "even without AC".  Of course I assumed you were serious and just wanted to raise the possibility that forcing could shed light on a hierarchy of choice-conditioned-on-cardinality axioms.
Comment: Doesn't ZF imply AC$_z$ without AC?  AC$_z$ is not the axiom of countable choice. I used AC$_\omega$ to denote the axiom of countable choice.
Comment: You need AC to choose a bijection for all $s$ at once. To use Conway's terminology, products of _counted_ sets are inhabited, but products of _countable_ sets could be anything.
Comment: Are there sets that can be proved to be countable in ZF but for which you need choice to actually exhibit the bijection? What does it mean to assert that a set is countable if you don't have a bijection?
Comment: @MJD I think you can prove the full axiom of choice in ZF. If the factors are nonempty, then for each factor set $s$ there is an element $x_s\in s$ (what does it mean to assert that a set is nonempty if you don't have an element?) so the map $s\to x_s$ is a choice function.
Comment: Your "choice function", if it exists, would be a  certain set of pairs. How do you prove, using only the axioms of ZF, that that set exists? Answer: you can't. Which is why we have AC.
Comment: I can't figure out what your question is.
Answer: As a basic example, $\mathsf{AC}(\mathrm{fin})$, the statement that the Axiom of Choice holds for all families of finite sets, is known to be implied by the Ordering Principle (that every set can be linearly ordered), but is strictly stronger than $\mathsf{ZF}$ (the existence of a Russell sequence (a countable sequence of two elements sets without a Choice function) is consistent with $\mathsf{ZF}$ and would clearly contradict $\mathsf{AC}(\mathrm{fin})$).
(See Horst Herrlich's Axiom of Choice for some limited information about $\mathsf{AC}(\mathrm{fin})$ and Horst Herrlich & Eleftherios Tachtsis _On the number of Russell's socks or $2 + 2 + 2 + \cdots = ?$ for some basic information about Russell sequences.
Comment: Thanks. I arrived at this question because I was wondering if Russell's socks example wasn't misleading, and if it might be possible to define a choice function for any large collection of pairs of socks.
Answer: In most cases $\sf ZF$ cannot prove that choice from families of restricted sets (rather restricted families) exists. In fact limitation on the size of the family is often independent from the limitation on the size of the members of the family.
In fact even $\sf AC_{fin}$ which states "every family of non-empty finite sets admits a choice function" is independent from $\sf ZF$, but strictly weaker than $\sf ZFC$.
In the texts which deal a lot with fine versions of choice (see P. Howard, Rubin & Rubin, E. Hall, and so on) you will often see $C(X,Y)$ where $X$ is a limitation on the size of the family, and $Y$ is a limitation on the size of the members of the family.
Something of interest, there has been a work of classifying choice from families of finite sets, e.g. choice from pairs does not imply choice from triplets and vice versa. You can find the details in Jech, The Axiom of Choice, chapter 7.
In the same book, on chapter 8, Jech has a proof that $\sf DC_{\kappa}$ cannot prove that there is a choice function on a family of $\kappa^+$ pairs.
More examples include Cohen's first model in which the axiom of countable choice fails; but every well-ordered family of well-ordered sets admits a choice function (i.e. we can choose well-ordered uniformly). On the other hand, assuming that every well-ordered family admits a choice function cannot even prove that every uncountable set has a subset of size $\aleph_1$.
There are tons of intricate relations between the many different ways of weakening the axiom of choice. The general rule of thumb is that whenever something can go wrong, it will. Much like Murphy's Law.
Comment: I'm just glad I grabbed a couple of upvotes before the Axiom-of-Choice upvote back-hole which is you came around!  ;-)
Comment: @MJD: Because you have to choose those bijections. That's why!
Comment: @MJD: It depends on what is $z$, and on a broader note, what is $\Phi$ which defines the particular property. If these are just limitations on the cardinality, or even on "there is a group structure" (for example) then it is indeed a mistake, and $\sf ZF$ does not imply such thing. But it might be reasonable to produce a statement $\Phi$ which is strong enough so that $\sf ZF$ does prove this sort of choice. For example $\Phi$ stating that all the sets are sets of ordinals.
Comment: Can you point to any more recent work related to your 4th paragraph for those without a copy of Jech's book at hand?  It's the kind of thing that is very hard to write a good query to find.
Comment: Thanks. I don't understand how that can be.  If $\mathcal C$ is a collection of nonempty finite sets, then why can't we say that for each $S\in\mathcal C$ there is a bijection $f_S$ between $S$ and some nonempty initial segment of $\omega$, and then $c: S\mapsto f_S(0)$ is a choice function for $\mathcal C$?
Comment: @Arthur: It's lucky that I bought a tablet and I can use the internet in places which are not my own study room... Otherwise this answer would have been written in about an hour from now!
Comment: So the claim in my original post that ZF implies AC$_z$ was mistaken?


Fazer um desenho conforme entrada do usuário

Question: O exercício pede para que o programa receba um inteiro n e imprima um desenho de altura 2*n da seguinte maneira:
\    *    /
 \  ***  /
  \*****/
   \***/
    \*/
    /*\
   /***\
  /*****\
 /  ***  \
/    *    \

Fiz o seguinte até o momento:
void arte(int n)
{
    int i, barrasE, aux, espacobarrasE, ebE, espaco;
    aux = n;

    for(i = 1; i <= n; i++)
    {
        if(aux < n) //Espaços impressos antes das contra barras na parte superior.
        {
            espacobarrasE = n - aux;
            for(ebE = 0; ebE < espacobarrasE; ebE++)
                printf(" ");
        }
        for(barrasE = 1; barrasE <= aux; barrasE++) //Desenha as contra barras na diagonal na parte superior.
        {
            printf("\\");
            break;
        }
        for(espaco = 1; espaco < n; espaco++)
        {
            printf(" ");
        }
        aux = aux - 1;
        printf("\n");
    }
}

Mas isso só imprime as contra barras de cima e não sei como continuar. Gostaria de saber qual o melhor jeito de continuar.
Comment: só pra confirmar, nesse primeiro exemplo, n=5 correto ?
Comment: Sim, Rovann. n = 5 e foi impresso um desenho de altura 2n = 10.
Answer: Começando pela parte superior:
Qualquer linha pode ser formada a partir deste padrão: (espaço)(\)(espaço)(*)(espaço)(/)(espaço) e a questão fica em quantas vezes cada símbolo deve ser desenhado em cada linha.
Veja essa função:
void desenha(int qtd, char simbolo){
    int i;
    for(i=0; i<qtd; i++)
        printf("%c", simbolo);
}

Nessa função você passa um número qtd e um símbolo e este símbolo será impresso qtd vezes na tela. Por exemplo desenha(5, '*'):
O resultado será: *****
A primeira linha do seu exemplo (\    *    /)pode ser representada da forma
(0,espaço)(1,\)(4,espaço)(1,*)(4,espaço)(1,/)(0,espaço)
e uma linha qualquer por
(n1,espaço)(n2,\)(n3,espaço)(n4,*)(n5,espaço)(n6,/)(n7,espaço)
como n2 e n6 sempre serão 1 e n1 sempre é igual a n7 e n3 sempre é igual a n5, podemos escrever de forma simplificada
(N1,espaço)(1,\)(N2,espaço)(N3,*)(N2,espaço)(1,/)(N1,espaço)
Agora basta apenas definir como será feito o cálculo de N1, N2 e N3 e conseguirá desenhar a parte superior. A inferior será feita facilmente depois, apenas invertendo a ordem do cálculo.
Um modo que eu usei para fazer o cálculo foi:
N1 = i;
N2 = n - 2*i -1;
N3 = n - 2*abs(i-(n/2));

Porém tente criar sua própria lógica para realizar o cálculo. Obs: na lógica que eu usei, quando um número par é passado para a função o desenho sai um pouco diferente, porém também não foi especificado como deveria ser, tente corrigir isso também.
Código completo:
void desenha(int qtd, char simbolo){
    int i;
    for(i=0; i<qtd; i++)
        printf("%c", simbolo);
}

void arte(int n){
    int N1, N2, N3;
    int i;
    //Parte superior
    for(i=0; i<n; i++){
        N1 = i;
        N2 = n - 2*i -1;
        N3 = n - 2*abs(i-(n/2));

        desenha(N1, ' ');
        desenha(1, '\\');
        desenha(N2 , ' ');
        desenha(N3 , '*');
        desenha(N2, ' ');
        desenha(1, '/');
        printf("\n");
    }
    //Parte inferior
    for(i=n-1; i>=0; i--){
        N1 = i;
        N2 = n - 2*i -1;
        N3 = n - 2*abs(i-(n/2));

        desenha(N1, ' ');
        desenha(1, '/');
        desenha(N2 , ' ');
        desenha(N3 , '*');
        desenha(N2, ' ');
        desenha(1, '\\');
        printf("\n");
    }
}

int main(){
    arte(5);
    return 0;
}

Comment: Valeu Lucas! Sua resposta me ajudou bastante.


from an orthonormal basis of polynomials, my corresponding coordinate matrix is not orthogonal?

Question: how could I do it?  do I just put the coordinates of each orthonormal polynomial vector into a column, w.r.t. the standard basis?
for example, if my orthonormal basis is
$$\{1, 2x, 3x^2\}$$
Then is the first column of my orthogonal matrix just
$$[1,0,0]^t$$
the second column
$$[0,2,0]^t$$
and third column
$$[0,0,3]^t$$?
the matrix is obviously not orthogonal, just by inspection, but my basis is orthonormal for some specified inner product.  so this is confusing me...
Answer:
my basis $1,x,x^2$ is orthonormal for some specified inner product

is refuted in Is there a representation of an inner product where monomials are orthogonal?


How can I diagnose and fix frequent 100% cpu utilization from kernel?

Question: I have an Amazon EC2 micro instance running an old 2.6.16 kernel. It runs postfix, apache, and mysql. During normal loads, it's load average is around 0.05, and it runs this way 95% of the time or so. However, a few times a day (or so), the CPU usage will spike to 100% and the system becomes nearly unusable. This usually lasts for roughly 5 minutes, then the load returns to normal.
If I manage to take a look at htop while this happens (not easy -- the load is that severe), I see that no running task accounts for any significant cpu usage, leading me to believe this must all be taking place in kernel-land.
How can I diagnose the cause of this load and, more importantly, fix it?
Answer: What is the percentage of "iowait" and "steal" CPU time during these periods?
Iowait denotes the amount of time the CPU is spending waiting for IO requests to complete, and steal percentage denotes CPU time that your kernel requested, but was denied by the hypervisor.
EC2 t1.micro instances are very CPU and IO-constrained. They can burst for very short amounts of time, after which they're subject to severe CPU throttling. Next time this happens, pay attention to %wa and %st in the output of top. My bet is that one or both of these have high percentages of CPU time.
To mitigate, you'll need to find the source of the IO and/or CPU load or alternatively, resize your instance to an m1.small.
Comment: I suggest you edit your answer to include brief explanation of what %st means in the context of EC2/virtualization. Anyway, thanks!
Comment: Conveniently, this just happened again. %st is pegged at 98% or so.
Comment: @stephelton - yep, that's Xen's CPU throttling kicking in. That's one reason why `t1.micro` instance are no good for anything but the most light workloads, or applications where performance is a very low priority.
Comment: Yep. Related question: http://serverfault.com/questions/230495/what-does-st-mean-in-top


appcelerator dexer fails with Uncaught translation error when using module

Question: Using Appcelerator with Titanium SDK 6.2.2.GA (the same happens with any 6.x SDK).
I create a new project module, compile it (for 6.2.2) and install it in the SDK (6.2.2).
Then I create a new Mobile App project (Clasic, Single Window, No Cloud) and add the previously created module to it.
I compile to run and the result is :
[ERROR] :  Failed to run dexer:
[ERROR] :
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$anim;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$animator;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$attr;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$bool;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$color;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$dimen;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$drawable;
[ERROR] :  Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/compat/R$id;
[ERROR] :
[ERROR] :  UNEXPECTED TOP-LEVEL EXCEPTION:
[ERROR] :  java.lang.RuntimeException: Translation has been interrupted
[ERROR] :   at com.android.dx.command.dexer.Main.processAllFiles(Main.java:608)
[ERROR] :   at com.android.dx.command.dexer.Main.runMultiDex(Main.java:366)
[ERROR] :   at com.android.dx.command.dexer.Main.run(Main.java:275)
[ERROR] :   at com.android.dx.command.dexer.Main.main(Main.java:245)
[ERROR] :   at com.android.dx.command.Main.main(Main.java:106)
[ERROR] :  Caused by: java.lang.InterruptedException: Too many errors
[ERROR] :   at com.android.dx.command.dexer.Main.processAllFiles(Main.java:600)
[ERROR] :   ... 4 more

I have tried :
Other Java versions
Other android build tools versions
When doing the same with SDK 5.x.x.GA it works fine. The problem started when I installed Axway Appcelerator Studio, build: 188.8.131.52709271713 and attempted to compile my project with Titanium SDK 6.2.2.GA. (Before I was using 5.x.x).
Any ideas welcome.
Comment: what build tools version do you have? And what is your build target version?
Comment: Build tools is 23.0.3 but I have also tried 25. My module build.properties are titanium.platform=C:\\ProgramData\\Titanium\\mobilesdk\\win32\\6.2.2.GA\\android
android.platform=C:\\android-sdk-win\\platforms\\android-25
google.apis=C:\\android-sdk-win\\add-ons\\addon-google_apis-google-25
android.ndk=C:\\android-ndk-r10d and my app SDK target is 6.2.2.GA
Answer: Version 6.2.2.GA requires you to use Android SDK 26 and build tools 26. Before 6.2 you needed build tools 23.
You can force a version in the tiapp.xml file in the android manifest section
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23"/>

As always, check the Compatibilty matrix of Titanium
Comment: I have tried to complile for SDK 6.0.3 but the result is exaclty the same. Also I have checked the module build path and it is correct.
Comment: 6.0.3 SDK requires build tools 23, not 26
Answer: After uninstalling Appcelerator Studio, reinstalling and setting the path for NDK to use android-ndk-r11c and also installing GNU gperf the problem is fixed.
Comment: In the end this did not work permanently. I works when using ant but after using Publish in SDK for some reason the errror reapears. I think the best solution is to dump appcelerator all together because it suffers for so many bugs that is is unusable. I think it better to invest my time into porting my code to Xamarin than searching for days for a way to build my project.


How to prevent two users to edit one row from DB

Question: i am using Spring/Hibernate/ZK. In one tab i get object from DB for editing  by user, but second user can open the same tab and the same object for editing . I want to informed second user whit message like "This object is аlready open" and hide buttons for save.Тhus second user can see current data from DB to this object but can`t edint him.Is there a way to check session  for this object or another way to do that.
Comment: There are multiple ways. Add status column to Db with values EDIT for edited ones. Keep a reference on JVM (in context or in session). The main question is how to "release" the objects?
Comment: Yes the problem is how to "release" the objects . Every way I think I get to this dead end.
Comment: How about `editing_start_date` + `editor_id` field? If it's null or editing started e.g. 10 minutes ago another user can also start editing. For the first user we can show a warning that editing must be completed in 10 minutes (or create AJAX call by 1 minute timer refreshing the `editing_start_date`)
Answer: The best solution is to use Optimistic Concurrency Control with Versioning and when Hibernate throws Concurrency Update issue due to same row is being updated in two transaction then use one of below strategy

First Wins Strategy
Last Wins Strategy
Merge Conflicting Update Strategy

First Wins Strategy is not good solution as it leads to lost update and user will get frustrated that all his work is lost.
By Last Wins Strategy one of user will get error message that you are working on Stale data and  start your transaction again . By this way also user can get frustrated due to fact that now again he need to restart operation from beginning but his changes will not lost.
Instead go with Merge conflicting Update Strategy, when Hibernate throws Stale object exception reload screen with new data and user will see updated result and allow him to proceed with latest data. In this user changes will not loss and user will not get error message , just his screen reloads with fresh data and he can decide whether to proceed or not .
You can take example any e-commerce site and you will get one of result of either Last Wins Strategy or Merge Conflicting Update Strategy. Two user can start to by one item but one of user will get message in last screen that item is not stock.
Answer:
You may have additional field which indicates that column is being edited. When first user starts work, the field would be updated. The second user would query object with 'on hold' status and your code would handle this.
Other way - use Hibernate @Version field in your entity. It holds object version which is incremented after every update operation. If second user would save object after first one already saved, it would throw OptimisticLockException which you could handle in your code. More about optimistic and pesimistic locking: Chapter 5. Locking. Related discussions: Hibernate Automatic Versioning and When to use @Version and @Audited in Hibernate?
Comment: Hibernate @Version  will throw OptimisticLockException on save . I don`t want user to do some work and when hit save to get massage . For the other method if first user open the tab and after this he just  close the window or close browser  the field which traces for edited object  It will not be update.
Comment: You may use Javascript to detect page close and then execute a method which would update status field. Check https://stackoverflow.com/questions/13443503/run-javascript-code-on-window-close-or-page-refresh or https://stackoverflow.com/questions/14746851/execute-javascript-function-before-browser-reloads-closes-browser-exits-page
Answer: The other answers mostly look at the database, but if all users use the same zk application to access the database, you could keep track of opened objects in the Composer or ViewModel (depending whether you use MVC or MVVM; I'll just call it controller).
Your controller would need a static list of objects that are currently modified. If a user requests to open an object that is not in the list, everything is fine and your controller enables the fields and save button. Otherwise, those are disabled and/or you display a message.
The tricky part is clearing objects from that list. If a user presses the save button, you just remove the object from the list. But what if the user doesn't and just closes the tab or their session just times out? In this case you need a callback, or a mechanism that regularly checks whether the screen is still open.
You could achieve this by adding a zk timer to the tab that pings every now and then and updates the timestamp in your static list (so make it a map). If a new user tries to edit the object, check how old the last timestamp is. If it is old enough (i.e. the previous user saved it or abandoned the screen), allow them to edit it.
Still, you have to think about what to do if a user just keeps the screen open. How long are they allowed to keep the lock on the object? This is an issue in Microsoft Office as well. If multiple users try to open an Excel file from a network location, the first one gets to lock and the others cannot save until that user saves.