Unwanted carriage return when getting input from terminal

Question: I've just started learning Java and have come across a little quirk I'm not sure how to solve. It's the same as this question but the solution there doesn't work here. The problem there was thought to be the result of something to do with Netbeans, and compiling the code form the command line may solve the problem, but I am compiling and running from the command line.
Basically, when I run the following code (snipped for brevity)
    System.out.println("Number: ");
    line = in.readLine();

I get the following output:
Number:
//Input cursor is found here

I'm running the code using the Gnome Terminal that ships with Ubuntu. Does anyone know what's causing this?
Answer: Use print instead of println if you don't want the trailing line break:
System.out.print("Number: ");
try {
    line = in.readLine();
}

The Javadocs for println already say so:

Terminate the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
Answer: Use System.out.print() instead of System.out.println()


Pass and store interface implementation

Question: Let's assume we have interface selector_interface_t and implementation of this interface pin_selector_t.
class selector_interface_t
{
    public:
        virtual void select(uint8_t address) = 0;
        virtual void deselect() = 0;
};

class pin_selector_t : public selector_interface_t
{
    private:
        uint8_t mask;

    public:
        pin_selector_t(uint8_t mask);
        void select(uint8_t address);
        void deselect();
};

And now we want to pass object witch implements this interface to class myclass_t and store for future use by other myclass_t methods (eg. strobe).
class myclass_t
{
    private:
        selector_interface_t * selector;

    public:
        myclass_t(selector_interface_t & selector);
        void strobe(uint8_t pin);
};

myclass_t::myclass_t(selector_interface_t & selector) // : selector(selector)
{
    // ...
}

void myclass_t::strobe(uint8_t pin)
{
    this->selector->select(pin);
    this->selector->deselect();
}

The only way is pass implementation by pointer or by reference. I prefer second solution and pass by reference. But I cannot simply store this reference in myclass_t object because of lifetime of object with interface implementation. It would be better to make a copy. But I cannot have selector_interface_t field member. I can only have reference or pointer to this type. On the other way I'd like to avoid using malloc. What can I do with it?
Answer: If you are the one who creates the selector_interface_t type then you can store it inside a shared_ptr and have the myclass_t class hold a weak_ptr or shared_ptr to the interface.
If you are not the one who creates selector_interface_t then I assume you have other means of keeping the object alive, wrap it in a class that manages the lifetime and that object wrap in shared_ptr.
Answer: If you can't guarantee that the implementation has the right lifetime, then you need to manage it, which means dynamically allocating it. (Using new, not malloc.)
I would strongly suggest using either shared_ptr<selector_interface_t> or unique_ptr<selector_interface_t> - depending on whether or not you ever want to share implementation objects between clients. You then get correct code with very little effort.

Pass and store interface implementation


Upgrading to create-react-app version 4.0 with react-app-rewired: server start error

Question: I've been searching the Web and can't find this situation mentioned anywhere, although it must be not uncommon.
I've been using create-react-app (version 3.4.x) with react-app-rewired [primarily in order to enable decorator support (for MobX) without ejecting].
I recently tried to upgrade cra to the latest version (4.0), following the instructions, by running this command:
yarn add --exact firstname.lastname@example.com

However, now when starting my React server, I get this error:
yarn start
yarn run v1.22.5
$ HTTPS=true BROWSER=none react-app-rewired start --env=local
Cannot read property 'use' of undefined
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

If I remove react-app-rewired and change the start script back to using react-scripts, the server starts but I don't have decorator support anymore.
Questions: Does react-app-rewired support cra 4.0? Is there an alternative solution for enabling decorators without ejecting? Thanks for any input!
Comment: Hi @mjh ! Did you find a solution to the server start error?
Comment: Any other update on this issue?
Answer: Don't have an answer for rewired stuff, but in MobX 6 there is new thing that will probably allow you to drop decorators altogether, makeAutoObservable:
import { makeAutoObservable } from "mobx"

class Store {
  // Don't need decorators now
  string = 'Test String';

  setString = (string) => {
    this.string = string;
  };

  constructor() {
    // Just call it here
    makeAutoObservable (this);
  }
}

More info here
https://mobx.js.org/migrating-from-4-or-5.html
and
https://mobx.js.org/react-integration.html
Comment: Thank you, this is helpful and the direction we might have to go in. I thought decorators were pretty cool, though.


AngularJS Odd Directive Scope Behavior

Question: After describing my setup, my questions are below in bold.
index.html

    <user-picker placeholder="Type a name..."></user-picker>

Setup:
var app = angular.module('app', ['app.directives', 'app.controllers']);
var directives = angular.module('app.directives', []);
var ctrls = angular.module('app.controllers', []);

Controller:
ctrls.controller('MyCtrl', function($scope) {
  $scope.foo = 'this is a foo';
});

Directive:
directives.directive('userPicker', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      placeholder: '@'
    },
    templateUrl: 'file.html',
    link: function postLink($scope, ele, attrs) {
      console.log($scope);
      console.log('[ng] Scope is: ');
      console.log($scope.placeholder);
      console.log($scope.$parent.foo);
  }
});

file.html (the directive):

  <input placeholder="{{placeholder}}" type="text">

So what I want to end up with, is generally working:

  <input placeholder="Type a name..." type="text">

The placeholder attribute is correctly resolved.
Is this the right way to accomplish this? Note that the attribute ends up in two places.
Why this odd behavior:
Secondly, I am baffled by the results of console.log($scope). The console output reveals the accurately set placeholder attribtue on the $scope object. However, even still, the very next console.log($scope.placeholder) statement returns "undefined". How is this possible, when the console output clearly shows the attribute is set?
My goals are:

Move or copy the placeholder attribute from the parent down to the child <input> tag.
Have access to the template scope from within linking function.
Reference the parent MyCtrl controller that this directive sits within.

I was almost there, until I ran into the odd behavior noted above. Any thoughts are appreciated.
Comment: You're doing it right as far as I can tell. The weirdness with the console has to do with the asynchronous stuff Angular is doing behind the scenes. http://stackoverflow.com/questions/16571003/javascript-console-log-displays-different-values-on-same-object
Comment: Hmm, interesting. Do you know if there is a way to move attributes down to the children, rather than copying them (as I am ending up with above).
Answer: Instead of attempting to read this off the scope would reading the attrs work?
Some HTML

    <user-picker placeholder="Type a name..."></user-picker>

Some JS
var app = angular.module('app', ['app.directives', 'app.controllers']);
var directives = angular.module('app.directives', []);
var ctrls = angular.module('app.controllers', []);

ctrls.controller('MyCtrl', function ($scope) {
    $scope.foo = 'this is a foo';
});

directives.directive('userPicker', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            placeholder: '@'
        },
        templateUrl: 'file.html',
        link: function postLink($scope, ele, attrs) {
            console.log($scope);
            console.log('[ng] Scope is: ');
            console.log(attrs["placeholder"]);
            console.log($scope.$parent.foo);
        }
    }
});

A Fiddle
http://jsfiddle.net/Rfks8/
Comment: You're right, that does work. I don't know why I didn't think of that. Anyways, thank you! :)

AngularJS Odd Directive Scope Behavior


I'm planning on doing my first bathroom remodel DIY. What order should I do these things, and are they feasible for a beginner?

Question: Here is a picture of my current guest half bathroom: https://imgur.com/gallery/4tHOpt1
I'm planning doing these things, in order:

Remove the sink/drawers/Mirror/Lights
Remove the Toilet, clean around the flange
Attach wallpaper to all walls, and ceiling (open to suggestion if it could look better with one or more walls without the same wallpaper)
Attach a new toilet
Attach new sink/drawers/lights
Replace door/hinges

Does that seem like a reasonable order of steps for a DIY bath remodel? Also, should I use the same pattern for all walls and ceilings? This is my first home and don't really have an eye for this stuff.
Comment: Looks good except you forgot to remove the door:-)
Comment: Hard to say not knowing how handy you are
Answer: I'd remove the toilet first and re-install it last -- the vanity (industry term for the cabinet below a bathroom sink) will be easier to manage with the toilet out of the way.
Things to beware of:

the existing flooring may have been trimmed around the vanity. If the footprint of the new vanity does not match or exceed the existing one you'll have to figure out how to cover the difference. A small difference can be covered with baseboard, 1/4 round shoe molding, or a combination of the two but if the difference is significant you may be looking at installing new flooring too.
it happens all too often that people are lazy and don't paint or finish the wall well behind the toilet tank. You may have to deal with drips/runs/lumps in the wall paint if the new tank will be a different shape/size to the old one.
same potential for rough edges around/behind the mirror, vanity, and light bar. Surface irregularities are likely to show through wallpaper, so take the time to smooth any that you might discover.
confirm in advance that the shutoff valves for the toilet and sink water supplies work.
check the position of the sink supply and drain plumbing and consider how it'll work with the new vanity and sink position. It may be necessary to modify the vanity; in extreme cases a particular vanity just can't be made to work with the plumbing as-is.

I’m planning on doing my first bathroom remodel DIY. What order should I do these things, and are they feasible for a beginner?


OpenCPU not updating png

Question: OpenCPU doesn't update the graph when I call the hist function with a new dataset. It does change sometimes, but it is not reliable I am wondering why this is
METHOD = POST Endpoint : /R/pub/graphics/hist/png
PARAMS :
x, c(1,2,3)
output is a histogram with 1,2,3
then i do
METHOD = POST Endpoint : /R/pub/graphics/hist/png
PARAMS :
x, c(1,2,3,4,5,6,7)
Output is still the histogram of 1,2,3 I refreshed the page and tried to call it again,
Please tell me what is happening here
Additional Note:
I can do a /save as output then use the object returned to view the object it works, but it would be nice if I didn't have to make two REST calls to get the plot
Answer: Sounds like a caching problem. Which browser are you using? Do you have opencpu-cache installed?
Comment: No i dont have opencpu-cache installed. I installed it now. I will read about the features this has.

OpenCPU not updating png


Adding new row in DataGridView doesn't add to BindingList

Question: I've a little problem using a DataGridView with AllowUserToAddRows set to True that is binding to a list (BindingList<State>).
When adding a new row through the GUI, the row isn't added to the BindingList.
I've a entity which contains a collection with other entities. For example: Country contains States. So, the new row in datagridview isn't added in the StateCollection on country object.
That's is how I add the BindingList to the DataGridView:
var bl = new BindingList<State>(country.StatesCollection.ToList<State>());
grdData.DataSource = bl;

Properties:
EditMode is set to EditOnKeystrokeOrF2

If more data is needed, please ask me.
Comment: If I remember correctly, there is a `RowAdded` event or something similar. You might need to react to that.
Comment: Hi, if i catch the RowsAdded event, the DataBoundItem is null, and is fired when is clicked new Row...
Comment: There is a [`UserAddedRow`](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.useraddedrow%28v=vs.110%29.aspx) event, that might be what you're looking for.
Comment: You mean when you click on the new row with * on the left, its not letting you edit?
Comment: rageit: yes, in that row
Comment: With UserAddedRow, has the same behavior that RowsAdded
Comment: Check if your gird is not enabled and see what is the EditMode set.
Comment: If your grid or any of its containers are not Enabled keystrokes will not work. But other than that everything looks good to me. You should be able to type on the new row to add text to the fields.
Comment: i can add new row, but that row isn't added to the binding list.
Answer: Following your code, I initialized context.MyEntities with 3 MyEntity objects.
After binding, the DataGridView shows the 3 rows as well as the expected * NewRow. Thus:
context.MyEntities.Length == 3 // .Count or .Length depending on data structure
((BindingList<MyEntity>)grdData.DataSource).Count == 3
grdData.Rows.Count == 4

After entering data into the NewRow within the GUI, the DataGridView now shows 4 rows as well as the expected * NewRow. Thus:
context.MyEntities.Length == 3
((BindingList<MyEntity>)grdData.DataSource).Count == 4
grdData.Rows.Count == 5

Adding an item to the DataGridView did indeed add the object to the BindingList source, but not to the actual context.MyEntities source, which I assume is where you are expecting to see this new item added.
The reason you are seeing this behavior is because of this line:
var bl = new BindingList<MyEntity>(context.MyEntities.ToList<MyEntity>());

You are declaring a new object for your binding. Even if context.MyEntities is also a BindingList<MyEntity> (I doubt since that would negate the reason for the above line of code), it will not be updated with the new entry. For the desired behavior, you have two options:

Change context.MyEntities type to BindingList<MyEntity>, then simply change your binding to:
grdData.DataSource = context.MyEntities;

Handle DataGridView.RowsAdded and manually update context.MyEntities by a) adding the new item or b) refreshing the original object:
private void grdData_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    var source = ((BindingList<MyEntity>)grdData.DataSource);
    context.MyEntities = // source converted to the correct Enumerable type
}

Comment: Thanks for the explanation.... but i made a mistake when i wrote the question... so sorry. Right now, i'm editing the question.... i don't used the context directly.
Comment: No problem.  Aside from property name changes, it appears your question is essentially the same and barring the same name changes in the answer it should still be applicable.


Many to Many Relation with Lookup table Entity Framework

Question: I am trying to create many to many relation with a Lookup table. Suppose i have a table "Course" that has 3 possible courses :
Course
Id | Name
1  | History
2  | Maths
3  | Science

I have another table Students where I will create Students such as :
Student
Id | Name

I have a mapping table which is StudentCourse:
StudentCourse
ID | StudentId | CourseId
1  |   1       | 3

Here is my Student & Course class:
public class Student : Entity<Student,int>
{
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course : Entity<Course,int>
{
    public virtual ICollection<Student> Student { get; set; }
}

Finally, here is the configuration code:
   modelBuilder.Entity<Student>()
                .HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentId");
                            cs.MapRightKey("CourseId");
                            cs.ToTable("StudentCourse");
                        });

When i create Student entity from view , the user selects the course from Course table and sends it to entity framework and EF should make entry to only Student and StudentCourse table .
But in my scenario, the course table is getting new entries for the selected courses. So I end up with duplicates in course table.
How do I tell entity framework to not make entry in Course table as it already has all the possible courses ... Please help !!
Comment: Use either Distinct or a Group By to remove duplicates.
Comment: Avoid passing entities to/from your view, use ViewModels with the relevant IDs.When you get back to the server, create your Student entities and retrieve the relevant Courses based on the selected IDs then associate those to the new Student entities via their Courses collection, add the Students to the context DBSet and SaveChanges. The alternative if you are passing "Course" entities is that you'll need to remember to associate them to the DbContext where you are adding your students, otherwise you'll end up with these duplicates. IMO, leave the Entites at the service/controller level.
Comment: a code sample can help ? I am new to entity framework ..
 @jdweng how do i code Distinct ?
Comment: Just add .Distinct() to end of query.
Comment: Which query ? I am using entity framework ...
Comment: `.Distinct()` will only hide the problem. Your issue is you are getting duplicate records because EF doesn't realize they already exist. Need to see your code where you do the update, but see [this](http://www.entityframeworktutorial.net/EntityFramework4.3/update-many-to-many-entity-using-dbcontext.aspx) for guidance on how to update many to many.
Answer: the issue was that I was populating my object in presentation layer and hence dbcontext under unit of work did not know about the nested objects.That is why it will always try to re create the Course even if it already exists. To fix this, populate Course object under same unit of work dbcontext.
ex:
  student.Course = UnitOfWork.Repository.FindById(id);
  var model = UnitOfWork.Repository.Add(student);


Is there a group that can act as a foundation of mathematics?

Question: Implication is not associative. This results in quite a bit of structure that can be used in set theory with things like ZFC, but I'm curious if it is necessary, as the parentheses can be annoying to deal with. While prefix and postfix forms are options, they often aren't very readable.
Are there any sets of axioms that seem to have enough structure to act as a mathematical foundation while having only associative operators?
Because multiple associative operations can be composed to simulate implication (and thus not be associative), I think I'm looking for a single associative operator that is sufficient to simulate ZFC. If we are going that route, we might as well require inverse and identity as well so we can use group theory. This results in the formal question (thanks to @NoahSchweber):

Is there a finitely generated computably presentable group $G$ on generator set $A$ and a computable function $f$ from first-order formulas to words on $A$ such that $\mathsf{ZFC}\vdash\sigma\leftrightarrow\tau$ iff $f(\sigma)$ and $f(\tau)$ represent the same element in $G$?

I could imagine that question being answered in a non-constructive way, so a constructive answer is preferred. In words, I'm asking for an infinite group that has enough structure to correspond to the standard kinds of things discussed in mathematics. Unlike the classification of finite simple groups, we still don't have a good handle on all infinite groups, and there are plenty of infinite groups with undecidable decision problems on them (for example), so it's conceivable that there are some that are expressive enough to work.
I've been looking through alternate metamath axiom sets, but all of them so far seem to require some form of implication or other operator that isn't associative.
Comment: Well, negation and disjunction are already enough to get all propositional connectives, and disjunction is associative (and negation is unary, so there's nothing to talk about there). Implication is just shorthand: $A\rightarrow B$ is $(\neg A)\vee B$. Keep in mind that associative operations can be combined to produce non-associative operations.
Comment: Polish notation requires no parenthesis.
Comment: It's unclear to me what your goal is, which makes it hard to decide how to approach an answer to your title question. "Parentheses can be annoying to deal with" makes it sound like maybe you'd be satisfied by a parenthesis-free notation like [prefix notation](https://en.wikipedia.org/wiki/Polish_notation). But taking you at the rest of your words that you do want a foundation with only associative stuff, I'm not sure what it would mean to have a "foundation of mathematics" that can't simulate things like implication or entailment. I'm genuinely curious about your question, but a bit lost.
Comment: @Phylliida Also incidentally, you may be interested in [this result](https://mathoverflow.net/questions/88368/can-a-group-be-a-universal-turing-machine) - it's not about equality of group elements, but still within the broader "can there be a 'computationally rich' group?" topic.
Comment: @NoahSchweber your last question in your answer is actually what I was asking. It forces identity and inverse as well, but that's probably okay. Sorry for being unclear.
Comment: @Phylliida We actually need finite generation as well to make this question nontrivial (see my edit).
Comment: @Phylliida I've thought a bit about this question and I think it might be appropriate for [MathOverflow](https://mathoverflow.net/) if more focused (namely, if you just ask whether there is a finitely generated computably presentable group such that [stuff]). Would you be interested in asking it there? If not, would you be comfortable with me asking it there?
Comment: Sure, feel free to give feedbacks or suggest edits for the title https://mathoverflow.net/q/369106/49223
Answer: EDIT: The followup question below/above was asked and answered affirmatively at mathoverflow.

In classical logic, implication doesn't need to be included as a primitive operation: we can define it in terms of the operations of negation and disjunction, which are respectively unary and associative, as $$A\rightarrow B\quad:\equiv\quad (\neg A)\vee B.$$ Indeed, the set of Boolean operations $\{\neg,\vee\}$ is functionally complete. So we can rewrite (say) all the $\mathsf{ZF}$ axioms using only disjunction and negation.
(You may also be interested in cylindrical algebras, which provide an algebraic semantics for first-order logic whose basic operations are all either unary or associative.)
Of course, taht doesn't actually solve the notation problem you mention: we still need parentheses to distinguish between e.g. $(\neg A)\vee B$ and $\neg(A\vee B)$. Basically, the problem is that associative operations can be combined to produce non-associative operations. If what we actually want is to avoid parentheses, then instead of changing our basic logical connectives we should instead (as Asaf Karagila comments) adopt something like Polish notation. For instance, the parentheses-laden expression $$p\rightarrow\neg(q\rightarrow r)$$ would be written as $$CpNCqr.$$ This, though, has the drawback of (at least in my experience) generally being less readable for long expressions, especially when quantifiers enter the picture.

You separately ask, however, a question about structures, e.g. whether there is

a certain infinite group that has enough structure to correspond to the standard kinds of things discussed in mathematics.

It's unclear to me exactly what this means, but there are certainly some observations we can make which seem relevant. Most obviously, we have on the one hand the set of first-order formulas modulo $\mathsf{ZFC}$-provable equivalence, and on the other hand - given a computably presentable group $G$ - the set of words on the generators of $G$ modulo equality given the presenting relations of $G$, and we could ask for an appropriate correspondence. The coarsest question is:

Is there a finitely generated computably presentable group $G$ whose word problem is as complicated as the problem of telling whether two sentences are $\mathsf{ZFC}$-provably equivalent?

The answer is yes: we can in fact find a finitely presentable group $G$ such that the halting problem is many-one reducible to the word problem for $G$, and $\mathsf{ZFC}$-provable equivalence is many-one equivalent to the halting problem.
On a more algebraic note, we could ask:

Is there a finitely generated computably presentable group $G$ on generator set $A$ and a computable function $f$ from first-order formulas to words on $A$ such that $\mathsf{ZFC}\vdash\sigma\leftrightarrow\tau$ iff $f(\sigma)$ and $f(\tau)$ represent the same element in $G$?

I believe that the answer is yes - and in fact that we can use the same $G$ as before - but I don't know.
I added the "finitely generated" bit since without it the question is trivial: take a generator $a_\sigma$ for each formula $\sigma$ and consider an appropriate set of relations making $a_\sigma=a_\tau$ iff $\mathsf{ZFC}\vdash\sigma\leftrightarrow\tau$.
Comment: Ah yes, you raise a good point that parenthesis matters when you try and simulate implication with multiple different associative primitives. We need to use a single associative operator (or multiple that play nicely, but it's probably better to just use one). Because neither NAND or NOR are associative I was fiddling with trying to come up with a more than two parameter Boolean universal gate that is associative, and considering going into multivalued or ternary logic to achieve that. Regardless, I think your final question is a very precise formulation of exactly what I was asking for.
Comment: As the last question is the one I am interested in and a great formalization of what I'm asking, I'm not going to accept this answer until it is answered, but thank you, this was very insightful
Comment: @Phylliida Glad to help! (I think you should edit that into your question, then - it will make it much clearer.)


How do I assign a value using = when a setter is passed?

Question: I am write a compatibility layer over a legacy library function whose internal signature looks like —
function legacyLibraryFunction(context) {
  context.foo.bar = "data"
  return context
}

The new system however, doesn't recommend assigning custom properties directly to context and instead recommends using the context.set() method.
How do I pass context from the new system to the old one so that context.foo="data" ends up called context.set('foo', data) instead?
I'm guessing I can use Object.defineProperty for this, but I don't really understand how.
Comment: what version of javascript are you working with?
Comment: is this for a setter in particular or any setter that might be used on the context object? The latter requires proxies.
Comment: @Paarth This particular one. I need to handle only one property in the legacy function's signature
Answer: Using a setter:
You can use a setter for this:
var wrappedContext = {
    set foo(val) {
        context.set('foo',val);
    }
}

Note: I'm assuming context.foo instead of context.foo.bar because the second part of your question does not quite match the example code.
This will create an object (wrappedContext) that will have a foo property that will call context.set() when you assign a value to it. So then you can do:
legacyLibraryFunction(wrappedContext);

Using a proxy:
Since you're using node 6.6 you can also use a proxy:
var wrappedContext = new Proxy(context,{
  set: function(obj, prop, value) {
    obj.set(prop,value);
  }
});


Question for UI/UX designers re: prototyping UI animation

Question: I am a motion graphics designer (previously: motion graphics for TV, games, etc), but more recently, I worked on prototyping UI motion for an app - which I really enjoyed!
I have mainly used After Effects up until this point and have read that quite a few UI/UX designers use this to prototype transitions and interactions.
As I move into this field, for those already working in it, do you see a use for someone to come in, like myself, on a freelance basis to prototype motion in AE? What other tools do you find beneficial for this?
I have read about Quartz Composer, which apparently has a rather steep learning curve - but would like to learn if that would be a desirable skill to have?
Answer: First, I applaud anyone showing an interest in focusing on the interaction side of design. In corporate UX groups, I find that the one thing that often does fall through the cracks is the interaction design (often due to waterfall development processes). The UI may look stunning, the back end, tight and responsive, but then you put them together and things still feel clunky because no thought was put into the transitions, or hovers, or animated reveals, etc.
So, any UX team that would have you, would be an excellent UX team to be a part of as there is clearly consideration for this.
As for what tool to use, that's where I get a little more skeptical of anything but the actual medium one is working in. I'm a strong advocate that if you're working on prototyping motion for a web app, use the medium of HTML, CSS, and JS to do it. If it's a native iOS app, grab Quartz Composer and use native animations.
That's not to say After Effects isn't a great tool, though. Ultimately, it's the person behind the tool that's key. That said, when only the tool is used, teams can get overly reliant on the interactions that exist only within that tool. For example, a team that only uses Axure may end up unknowingly creating web sites that simply feel like default Axure interactions.
SharePoint is another good example...it takes a herculean effort to build a SharePoint site that doesn't 'feel' like SharePoint because you're stuck within the medium of SharePoint.
In summary:

do you see a use for someone to come in, like myself, on a freelance basis to prototype motion in AE?

Do I? Absolutely! And hopefully other UX teams do as well.

What other tools do you find beneficial for this?

I'd start playing with jQuery. Get your hands dirty with some JS and CSS3. Even if you don't ultimately work in that, it will give a lot of great context to take back to better create your After Effects work.
Other popular tools that include different forms of interaction prototyping that UX teams use:

Axure
iRise
Muse
InVision
and (again) HTML, CSS and JS.
Answer: DA01's answer was fantastic and thorough. I'd like to applaud you for making the transition as well!
Getting comfortable with the code itself is incredibly valuable because it will allow you to understand and communicate with developers and SWEs in ways that allow your ideas to come to fruition in production. Additionally, it can decrease production time dramatically because you can exert ultimate control (and reduce the number of production code iterations) over your transitions and animations.
I'd like to note that some open-source tools like Framer have fairly low overhead and will allow you to move empower yourself to move towards more code-based design. If you're composing static mocks yourself or working with designers who like different tools (Photoshop, Illustrator, Sketch, etc.), you don't need to press them to change their workflow to create polished motion designs.
Answer: I used to work in a firm where they really tried to encourage the use of animation in user interfaces. Their belief was that animation should be defined roughly at the very earliest stages of prototyping. Hence, it was the duty of the UX people to enhance their wire-frames with animations.
So when they searched for a tool that even UX people with no graphic or visual design training, they found out that the most cost-efficient tool was in fact MS PowerPoint. Remember, this was for low-fidelity prototyping purposes, and PowerPoint just excelled at that (no pun intended). The learning curve is very quick, the effort required is light, and the results get the general animation idea across.
Answer: This is a complicated question that touches on several important issues. I will attempt to answer by focusing on two core issues.

Do you see a use for someone to come in, like myself, on a freelance basis to prototype motion in AE? What other tools do you find beneficial for this?

Absolutely. There is a large demand for freelancers to provide speciality services in areas outside of core business offering for businesses of all kinds and sizes. Check out Freelancing on Stack, Freelancers Union to learn about being a freelancer, learn about Business Models (you will be a business owner of one) to map out all the pieces of owning a business and read Design is a Job for practical application of your craft. You will need to discover a market (Scientific Visualization, Game Design, etc.), align your pitch, learn about competitive rates in this area, then do honest hard work.
Since you are asking a UX crowd, we can prototype with verbal stories, paper, white boards, story boards, tools like AXURE and Basalmiq, or hi-fi protos in HTML/CSS/JS or native environments. The key here is determining what to test and who to test. The goal is to validate assumptions about what problems need solving and the best way to solve them as cheap and quick as possible for consumer products - may be different for research settings. However hifi protos are meant to test complex interactions as they will be in the wild.

There might not be a substitute for AE. If you are fast and good, applying a prototype process like RITE can help you be a rock-star animation prototyper. Ask yourself why should you choose other methods? Maybe you need to partner with a usability research group that needs a rockstar AE animator.
Find a way to apply your passion. That is the beauty of being a freelancer. You choose your own way.


In England: ground or air based heat pump?

Question: Weather is not too extreme in southern England, will not need a/c. Want to install central heating for the first time in an old Victorian house. There are no radiators, no base board units, no under-floor heating, nothing. Well, a lot of chimneys and wood/coal stoves in fireplaces. Will be doing all the right things re. insulation and windows.  Want to be as green as possible, also independent of net if possible. Looking into geo-thermal but am not sure if govt. incentives make it worthwhile. Any advice welcome.
Comment: Such an open-ended question might better be addressed at a site like http://www.greenbuildingadvisor.com/qa
Comment: thanks for that tip but it is impossible to register with that site given their contradictory password directives.
Comment: I have an account... If I could do it, so can you!
Answer: A ground-source heap pump is a custom-made-site-specific piece of equipment, and as such, will be more expensive and failure-prone. On the plus side, it will be more energy-efficient than the compressor of an air-source heat pump system. With today's super-efficient air-source heat pumps, you'd be looking at a coefficient of performance (COP) of ≤ 3 for air-source and ≤ 4 for ground-source. Both are very good. In general, I would favor an air-source heat pump due to lower upfront costs, higher reliability, and greater ease of maintenance and replacement.
But the real question for your situation will be distribution. You say you're installing central heat and are talking about heat pumps; I assume this means you'll be adding ducts. But even with ducts for distribution, a victorian house with a lot of small rooms and multiple stories will be much more comfortable to heat using modern equipment if you also super-insulate it. You should pay very close attention to your air-sealing and insulation details, and budget more than you think for this.  And buy better windows than you think you need. Definitely triple pane. Better to spend more on the building envelope and less on mechanical equipment than the reverse!
If you want to be "net zero" you need all your mechanicals to be electric (no gas or oil), and you'll want to keep your interior electric load as low as possible. LED lights, no huge plasma TVs, etc. And you'll need a lot of solar PV to generate the electricity required to run everything. In cloudy England, that will be quite a lot! To deal with this, you might want to look into solar-trackers, per-panel micro-inverters, and even residential wind turbines. You'll need to have a net metering arrangement with your municipal electric company/service as well.
Comment: No, don't want air ducts. So I guess the air-source heat pump would be wrong way to go.  Or, can an air-source heat pump also deliver heat to under-floor coils, which I might put in in the area of the house most used, the big kitchen. And, unfortunately, being the northern twin, there is not a lot of south-facing roof for pv. I am not aware that wind turbines are pemitted within residential neighborhoods in England. So, it looks like I may just have to give up and go with a gas-fired boiler and radiators. Pity.
Comment: If you don't want ducts, you have two options: 1. multiple point-source ductless mini-split heat pumps, or 2. a boiler or air-to-water heat pump to feed a hydronic heating system.
Comment: And there's no reason to avoid heat pumps just because offsetting their electricity consumption with PV would be difficult. Depending on your local gas and electricity rates, it may actually be cheaper to use electric heat pumps than gas. For example, a heat pump with a coefficient of performance of 3 will generate roughly 10,000 BTUs of heat per kWh. If one kWh costs you $0.10, and a therm of natural gas costs you $1.00, then the costs are roughly equal (assuming a 97% efficient boiler; with a worse boiler, the heat pump would be cheaper).
Comment: Any thoughts on multiple point-source ductless mini-split heat pumps (the first time I hear of something like that) to heat under-floor coils?
Comment: The multi-head ductless mini-split units are part of an air-to-air system; they blow air rather than heating water. However you would get air conditioning for free with ductless mini-split heat pumps. Heating water for radiators or radiant floor tubes would be accomplished with a single central unit (boiler or air-to-water heat pump) with zoned coils.
Comment: In the meantime have discovered that geology (thick clay deposits) makes an open-loop GSHP impossible. So, I'm still working on a vertical closed-loop option. Forced air systems architecturally impractical, and a/c un-called-for here. Feasibility probe for GSHP would cost about $600, but county facility might want to share expense. On the house, work begins Monday! Is it wise to install under-floor heating and radiators, with heat source -- whether GSHP or gas boiler -- to be worked out later?
Comment: No. Most people with under-floor radiant heat never use it because the floor isn't really the right place for it--especially with high mass floors of concrete. If you're sure you want radiant heat, stick to radiators or radiant hydronic panels on the walls. A GSHP hooked up to hydronic radiant heaters will be very nice, but of course, very expensive.
Answer: I think it depends on both the outside and the inside layout of the house.
I would approach it like this: I guess you have 4 main options, two for the source and two for delivering the heat.
Practicality may decide the source for you.
On delivery, to get hot water as well as space heating from a heat pump system, you must deliver the heat to water.
While the greenest most efficient option is your goal, when choosing, also keep in mind that electricity costs more than gas and the efficiency of the system depends on the difference between the source and delivery temperatures.
Perhaps consider a combination of systems, if there is not a single ideal fit for your house.

Ground Source
Pros:
Source temperature is higher than air source in the winter, making the system more efficient for heating in the winter and more suitable for producing hot water in the winter.
No outside noise.
Cons:
Requires sufficient garden area and digging up the garden to install/refurbish. Buried equipment cannot be inspected.
Alternatively requires borehole(s) if garden is relatively small. I don't know how hard it is to gain permission for those, even if the tube trains don't go under your house.
Source temperature is lower than air temperature part of the year, but heating load will be smaller at these times.
Requires floor space for hydronics unit.
Higher cost.

Air source
Pros:
Typically easier installation.
All equipment can be easily inspected/serviced.
Lower cost.
Cons:
Source temperature is low in the winter (less suitable for hot water); check that your model will at least give enough power for heating at -10C, where the effective COP including defrosting cycles may be around 2 (on par with a gas boiler in efficiency).
Noise. Modern units are very quiet, barely above suburban background noise.
No problem in the heating season with closed windows. However, noise may be an issue if used year round, early morning to produce hot water.
Noise levels must still fit within permitted development levels or planning permission will be required.

Delivery to air
Pros:
Takes no floor space.
Instant heating - full power within a couple of minutes.
Low delivery temperature - not much above 20C.
Lower cost.
Cons:
Very quiet, fan noise is not a problem on a decent unit, but of course noisier than a silent radiator.
Multiple units and/or thoughtful placement of them needed. For example, to cover several rooms in a storey, a unit might be placed in and heat a corridor more than you otherwise would. Or you may want two units in the main storey and just one in the corridor to give a bit of heat to bedrooms upstairs.
You cannot get subsidies for units that are able to cool also.

Delivery to water
Pros:
Can produce or help produce hot water although this requires high delivery temperature.
Low delivery temperature for underfloor coils.
Best possibility for integration with solar thermal (or combined thermal/photovoltaic panels).
Cons:
High delivery temperature required for radiators - reduces efficiency.
Works best with large radiators (with lots of ribs).
Requires space for hydronics unit/water tank.
Higher cost.

I like air-source as there are no ground loops to dig in/up and maintain.
I like the idea of delivery to water as you can use it for hot water too and potentially integrate with solar panels later, plus you can adjust heating room by room as normal with radiators, thus you can turn the heating down in rooms in your 3 storey mansion you don't use etc.
But I also like delivery to air as it is simpler/cheaper, comes on virtually instantly, ie. you can heat 100% on demand and it is very efficient (SCOP > 4) except for the worst part of winter. But even then a proper system is not less efficient than an A rated condensing boiler, although at the coldest times it may cost more to run.
If the house layout works for air to air, then it is perhaps also worth considering that in connection with a combi boiler for hot water, unless you want to avoid gas completely (obviously a yearly heat pump service and a yearly gas boiler service is approx. twice the cost of just one of the two).
That would be both a fairly simple and not too costly system - radiators plus hydronics will also cost, plus my feeling is you will be using a good deal of electricity to heat water from air source.
In theory you can recover that with solar panels, but they also cost to begin with.


Submanifold : Proof a catenoid is a submanifold using cylindrical parametrization.

Question: Let's consider the cylindrical coordinate :
$P:(r,\theta,z)\rightarrow (r\cos(\theta),r\sin(\theta),z)$, with $r>0$ , $\theta,z\in \mathbb{R}$.
We define a particular catenoid by $C=P(\left\{ (r,\theta,z)\in ]0,\infty[\times\mathbb{R}\times]-3,3[                   ,r=\cosh(z)\right\}$)
How to proof it is a two dimensional submanifold ?
What i have tried is to define a local parametrization  like $X(\theta,z)=(\cosh(z)\cos(\theta),\cosh(z)\sin(\theta),z)$, but i don't manage to choose and apply correctly a proper submanifold definition..
Answer: I do not think we need cylindrical coordinates, let us work with Cartesian coordinates instead. Consider the smooth map
$$F : \mathbb R^3 \to \mathbb R^3, F(x,y,z) = (x\cosh z, y \cosh z, z) .$$
Then your set $C$ is nothing else than
$$F(S^1 \times (-3,3)) .$$
Here $S^1 = \{(x,y) \mid x^2 + y^2 = 1\}$. Clearly $S^1 \times (-3,3)$ is a submanifold of $ \mathbb R^3$.

$F$ is injective: This is obvious because $\cosh z \ge 1$.

$F$ is surjective: Given $(a,b,c) \in \mathbb R^3$, we have $F(\frac{a}{\cosh c}, \frac{ba}{\cosh c}, c) = (a,b, c)$.

Thus $F$ is a smooth bijection. Its Jacobian at $(x,y,z)$ is
$$J_{(x,y,z) }F = \begin {pmatrix}
\cosh z & 0 & x\sinh z \\
0 & \cosh z & y\sinh z \\
0 & 0 & 1 \\
\end {pmatrix}$$
having determinant $\cosh^2 z$ which is non-zero. Thus $F$ is a diffeomorphism.
Therefore $C  = F(S^1 \times (-3,3))$ is a submanifold.
Update:
Why does a diffeomorphism send a submanifold onto a submanifold?
There are many equivalent definitions of the concept of a submanifold, see e.g. Equivalences of definitions of submanifolds in $\mathbb{R^n}$. Let us take the definition in Practical interest of Differential Submanifold definition by "Parametrisation", example of practical use.
So let $S \subset \mathbb R^n$ be a submanifold with dimension $p$ and $\phi : \mathbb R^n \to \mathbb R^n$ be a diffeomorphism. We want to show that $\phi(S) \subset \mathbb R^n$ is a submanifold with dimension $p$.
We know that for each $s\in S$ there exist an open set $U \subset \mathbb{R}^n$ containing $s$, an open set $V \subset \mathbb{R}^p$ containing $0_{\mathbb{R}^p}$ and an immersion $P : V\rightarrow U$ such that $P(0_{\mathbb{R}^p})= s$ and $P$ maps $V$ homeomorphically onto $U\cap S$.
Now consider $s' \in \phi(S)$. Let $s = \phi^{-1}(s')$ and choose $U, V, P$ as above. Define $U' = \phi(U)$ and $P' = \phi \circ P : V \to U'$. Clearly $P'$ is an immersion because the differential $d_x P' = d_{P(x)}\phi \circ d_xP$ has rank $p$ in all $x \in V$. Here we use the fact that $\phi$ is a diffeomorphism. Moreover $P'(0_{\mathbb{R}^p})= \phi(s) = s'$ and $P'$ maps $V$ homeomorphically onto $U'\cap \phi(S) = \phi(U \cap S)$.
Comment: Can you give an argument to explain a diffeomorphism sends a submanifold on a submanifold ? i can't find this theorem in any course.. or maybe you could give a reference where such a property would be given.. And also , can this property help to determine the dimension of the image submanifold generated ?
Comment: @KevinFredolster I can explain it, but you have to tell me which definition of a submanifold you are using. And perhaps you should ask a new question because this is of general interest.
Comment: There are many that are given in an equivalent way most of the time , but one of them could be referenced here https://math.stackexchange.com/questions/4109684/practical-interest-of-differential-submanifold-definition-by-parametrisation
Comment: @KevinFredolster Are you fine with definition (5) in my answer to https://math.stackexchange.com/q/3828888 ?
Comment: sorry , been a bit busy. What confuses me a bit is that in most "versions" that really looks like this one , there is a condition like the diffeomorphism "sends x on $0$" or a condition of this kind and it does not appear in the 5th. authors i see defines the "V open subset" containing $0$ with the same kind of needs.. I don't know if i'm clear... i would be satisfied with a source mentionning the property that a diffeomorphism sends a submanifold on a submanifold (and i would deal with eventual different definition) with  a proof would be nice.
Comment: @KevinFredolster There is no need to require that the diffeomorphism $h$ sends $x$ to $0$. But what is implicit in $(5)$ is that $h(x) \in \mathbb R^{n,k}$. Nevertheless we can assume w.l.o.g. that $h(x) = 0$. Given any $h$ as in $(5)$, it can easily be modified in that sense. See the remark after $(5)$. So my definition $(5)$ is equivalent to the stronger variant with $h(x) = 0$.


Looking for a more efficient way to generate/print a "progress bar" in C++

Question: I am working on some grid generation code, during which I really want to see where I am, so I download a piece of progress bar code from internet and then inserted it into my code, something like:
std::string bar;

for(int i = 0; i < 50; i++)
{
    if( i < (percent/2))
    {
        bar.replace(i,1,"=");
    }
    else if( i == (percent/2))
    {
        bar.replace(i,1,">");
    }
    else
    {
        bar.replace(i,1," ");
    }
}

std::cout<< "\r" "[" << bar << "] ";
std::cout.width( 3 );
std::cout<< percent << "%     "
    << " ieration: " << iterationCycle << std::flush;

This is very straightforward. However, it GREATLY slows down the whole process, note percent=iterI/nIter.
I am really get annoyed with this, I am wondering if there is any smarter and more efficient way to print a progress bar to the screen.
Thanks a million.
Comment: If your high-performance code spends most its time rendering a progress indicator, something is wrong :-)
Comment: Are you suggesting that the integer division in calculating how much is done is greatly slowing down your calculation?
Answer: Firstly you could consider only updating it on every 100 or 1000 iterations. Secondly, I don't think the division is the bottleneck, but much rather the string operations and the outputting itself.
I guess the only significant improvement would be to just output less often.
Oh and just for good measure - an efficient way to only execute the code every, say, 1024 iterations, would be not to see if 1024 is a divisor using the modulo operations, but rather using bitwise calls. Something along the lines of
if (iterationCycle & 1024) {

would work. You'd be computing the bitwise AND of iterationCycle and 1024, only returning positive for every time the bit on the 10th position would be a 1. These kind of operations are done extremely fast, as your CPU has specific hardware for them.
Answer: You might be overthinking this. I would just output a single character every however-many cycles of your main application code. Run some tests to see how many (hundreds? millions?), but you shouldn't print more than say once a second. Then just do:
std::fputc('*', stdout);
std::fflush(stdout);

Comment: Thanks, it is just for test, once my code works, I will eventually comment this out.
Answer: You should really check "efficiency", but what would work almost the same ist boost.progress:
#include <boost/progress.hpp>
...
boost::progress_display pd(50);
for (int i=0; i<=60; i++) {
 ++pd;
}

and as Joost already answered, output less often
Comment: OOPS, progress.hpp file not found, sorry, newbie here, not sure what your code means. :(


Fail to Call R in the MATLAB

Question: I followed this post http://neurochannels.blogspot.com/2010/05/how-to-run-r-code-in-matlab.html, to install R(D)Com server in order to call R from the MATLAB, but i get error messages:
Error using openR (line 68)
Cannot connect to R.
Error using COM.StatConnectorSrv_StatConnector/Init
Error: Object returned error code: 0x80040013

What is going here? Are there any other ways to call R in MATLAB? I was told that
system

can bee used to call other execution programmes, but how?
Answer: After using R(D)COM and Matlab R-link for a while, I do not recommend it. The COM interface has trouble parsing many commands and it is difficult to debug the code. I recommend using a system command from Matlab as described in the R Wiki. This also avoids having to install RAndFriends.

Fail to Call R in the MATLAB


How do I get more response until I get the correct solution?

Question: I asked a question and waited for an answer for more than 8 hours. I have got one answer, but that answer doesn't resolve my issue. Nobody is responding to my question because it appears somewhere in second or third page.
I know of bounties, but I have to wait for two days before I can set a bounty for my question.
How do I get more responses?
Comment: I'm asking in general, it will help me in future
Comment: Related : http://meta.stackexchange.com/questions/7046/how-do-i-get-attention-for-old-unanswered-questions
Comment: The [last question you asked](http://drupal.stackexchange.com/questions/70768/how-to-group-fields-with-select-option) was over a month ago (April 22nd), so is eligible for bounty right now. If you haven't needed to revisit that question in over a month I'd say the 2-day waiting period on bounties is incidental. Do you have a link to the question in question, or are you just asking in general?
Answer: If you're not getting appropriate answers, your question isn't good enough <code>:-)</code>.
What you should do is to edit your question and supply more details. You may take the opportunity to add material that makes it clear why the answer(s) already provided does not provide a solution.
Editing the question also bumps it back on the active page.
Answer: As you have already an answer, you can simply leave a comment to the user who answered, explaining that what proposed as solution is not working for you. It could be that user misunderstood what you were asking, or needs more information to answer the question correctly. In the case you are asked more information, add the information into your question, rather than adding it in a comment for the user. In that way, the question will be bumped to the front page, and more users will notice it.
Keep in mind that editing too much times a post makes it a Community Wiki; if you have to edit your question, makes your edits substantial, and avoid editing it just to make it bump.


PHP - GET tag from url

Question: I want to get a specific tag from url, from example:
If I have this content:

And I want to get all divs with the id "hey", ( i think its with preg_match_all ), How can I do that?

The content inside the tag can be changed.
Comment: @Daniel just a note that `id` values should be unique
Comment: FYI, `id`s are supposed to be single use. If you want to apply styles to multiple elements, you should be defining them to have the same `class`. Having multiple elements with the same ID can cause issues with JavaScript, forms, etc.
Comment: I'm not exactly sure what you're asking for here.  Are you saying you want to pass in an ID via a query string parameter and then search for that parameter in the page content?  Or are you passing that HTML string via a query parameter and you need to parse that?  Also, your HTML markup is invalid so you'll likely have a tough time programmatically parsing it under any conditions.
Comment: To be clear "from URL", it appears you mean "Given a webpage (whose URL I know) how do I scrape the contents from inside a particular HTML tag?"  As it is, it is hard to tell what is being asked, particularly because "GET" (in all caps) in relation to URLs normally refers to a method of form-data encoding.  (e.g. `http://example.org/?field1=value1` is a URL which could result from a GET form)
Comment: To get url ( for example $url ) and to print only the content inside the divs which I want to print ( like "hey").
Answer: I recommend use DOMDocument class instead of regular expressions (is less resource consumer and more clear IMHO).
$content = '

';

$doc = new DOMDocument();
@$doc->loadHTML($content); // @ for possible not standard HTML
$xpath = new DOMXPath($doc);
$elements = $xpath->query("//div[@id='hey']");

/*@var $elements DOMNodeList */
for ($i=0;$i<$elements->length;$i++) {
    /*@var $curr_element DOMElement */
    $curr_element = $elements->item($i);

    // Here do what you want with the element
    var_dump($curr_element);
}

If you want to get the content from an URL you can use this line instead to fill the variable $content:
$content = file_get_contents('http://yourserver/urls/page.php');

Comment: You should probably also suppress errors on the `loadHTML()` call, otherwise the DOMDocument will complain loudly about the multiple elements with the same `id`.
Comment: @AgentConundrum, I test with the HTML with same ids and surprisingly none problems arise, but just in case I add the @ to that line.
Comment: What are your error reporting settings? It issues an `E_WARNING` for me: `Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: ID hey already defined in Entity, line: 5`
Comment: I set as the initial line `error_reporting(E_ALL);` and nothing appears. I will check again.

PHP - GET tag from url


14.04 - Disable SSID broadcast on Wifi Hotspot on Ubuntu Laptop

Question: I have created a Wifi Hotspot following the instructions given in this post.
But is there any way to stop it from broadcasting its SSID ? I have had a look in /etc/NetworkManager/system-connections/hotspot-name file but there is no setting to stop it broadcasting the SSID.
I am not interested in the fact that this does not improve security I just want to decrease the visibility of the hotspot.
Comment: [This older post](http://askubuntu.com/q/554307/37165) and [even older post](http://askubuntu.com/q/44747/37165) suggest that it is not possible to hide SSID.
Comment: @clearkimura So no way to hide my SSID AT ALL ? Then what are hidden WiFi networks in Ubuntu ?
Comment: If you mean by "Connect to Hidden Wi-Fi Network..." in indicator menu, that is for connecting to modem router. The ability to hide SSID can be found in modem routers, but not for typical laptop/PC running Ubuntu as hotspot device.
Answer: SSIDs in 802.11 protocol are defined as 0-32 byte octets. It is indeed possible to "hide" your hotspot and the process is as simple as setting 0 length SSID in your beacon frames. According to the protocol, clients should not show SSIDs with "null" or "zero length" names.
Regular routers have that option in their control panels as "Don't broadcast SSID" or "Ignore broadcast SSID". By hand the same can be achieved by looking for the following in your hostapd files:
<code># Send empty SSID in beacons and ignore probe request frames that do not
# specify full SSID, i.e., require stations to know SSID.
# default: disabled (0)
# 1 = send empty (length=0) SSID in beacon and ignore probe request for
#     broadcast SSID
# 2 = clear SSID (ASCII 0), but keep the original length (this may be required
#     with some clients that do not support empty SSID) and ignore probe
#     requests for broadcast SSID
ignore_broadcast_ssid=2
</code>
Read more about hostapd at gentoo wiki and its configuration here


Are Lightning & Amodar viable allies?

Question: I am considering purchasing the DLC to fight these two. However, given the large amount of monsters already in the game that make great allies, the purchase won't be worth it for me unless Lightning & Amodar are actually practical to use.
Are either of these two characters top tier allies for their roles? Are either of them the best allies (for their respective roles) in the game?
Answer: Lightning can get 6 atb charges and is a very good ravager. better than cloudburst or pretty much any other ravager.
Amodar has very high hp but i find him rather slow but he does great against certain opponents like yomi.
Answer: Albino Lobo also has 6 ATB bars for a Ravager, and has been very very good for me, despite giving him very mediocre infusions. I'm planning to do a Blue Chocobo for my final Ravager slot for Colosseum battles and such. Pre-DLC Blue is supposed to be, hands-down, the best Ravager monster. If he's hands down better than Lobo, which is really strong, I can't see Lightning being a whole lot better.
Chichu has 6 ATB bars as a Commando, and he's incredible. It's easy to break 1.1-1.2k STR with him (I have 1116 and I did -not- use all Power while leveling him, and again have mediocre infusions. Even 1300+ should be np with proper infusion, and using all Power upgrades, as opposed to mixing in Potent or Vitality.)
If you're only interested in the DLC for the potential new allies, I wouldn't bother. If you want a chance for a new high-level fight, snap it up.

Are Lightning & Amodar viable allies?


Statistics - Z-score confusion.

Question: For z score, you are taking the sample value subtracting population mean and dividing it by std deviation. Is that correct so far?
Now, the "sample value" is defined by an equation. In my scenario, I have a bunch of stores that are reviewed by their customers. The customer amount varies. One store has 2 customers who give review while other store has 19 people who give reviews. For the 1st store in my example, both customers give 5/5. while the 2nd store customers, avg score given by all 19 customers is 4.
Sample value is calculated as score/customer count. So for the 1st store, it will be 5/2 while the other store will be 4/19. If I use that in z score eq. it will mean that first store is doing much better than the last store. I would like to know how to make the score "proportional""normalized""fair" etc...

Oh my many gods, I can't believe I ended like that. Thanks for pointing that out.
Comment: "If I use that in z score eq. it-" - is there more?
Comment: @user1569220 : If you click on "edit" below your question, you can edit it further.  You stopped in the middle of a sentence.
Answer: The $z$ score in your context is the sample mean minus the population mean divided by the standard deviation of the estimate which in your case would be the standard error of the mean which is the population standard deviation divided by the square root of the sample size $n$.  The motivation for calling this a standard normal random variable is that the sample mean is either normally distributed or approximately normally distributed by the central limit theorem.
Technically the population standard deviation must be known. In the case where a sample estimate is used and the data are normally distributed the statistic formed would actually have a student $t$ distribution with $n-1$ degrees of freedom. However if $n$ is large the $t$ will be close to a standard normal.  For small $n$ it will be symmetric about $0$ but have heavier tails than the standard normal.
Another issue in the computation is whether or not you are considering a straight average from the observed data or a weighted average. This all depends on what you consider the population to be. The definition of the population can affect the population mean and the population standard deviation.
Comment: Sample value = Score/Count; Mean = Avg of Sample Value of the entire population; Std Dev = Stddev of Sample Value of the entire population...if I understand this correctly, the average is based on observed data.
Comment: @user1569220 I just meant that since the individual stores have differing number of customer responses do you want to weight the customers equally over are the stores or do you want to weigh the stores evenly inspite of the imbalance in number of customers.
Comment: I would like to weigh the customers equally. I think it would be more fair rather than just making each store equal.
Comment: Okay That is generally what is done.
Comment: So again sorry, what do you recommend I should do?
Comment: I think it makes sense to weigh the customers equally.

Statistics - Z-score confusion.


How to set up Launchpad to import from GitHub?

Question: I'm setting up my first Launchpad project.
In this case I would like to import from the Master branch from my GitHub project - the default branch is not Master - it is a release branch currently called "Release-0.6"
On Launchpad I have set up to automatically import:

As you can see, the import failed - the error log states:

2013-01-07 14:45:11 INFO    Starting job.
2013-01-07 14:45:11 INFO    Getting exising bzr branch from central store.
2013-01-07 14:45:14 INFO    [chan bzr SocketAsChannelAdapter] Opened sftp connection (server version 3)
2013-01-07 14:45:17 INFO    [chan bzr SocketAsChannelAdapter] Opened sftp connection (server version 3)
2013-01-07 14:45:17 INFO    291 bytes transferred
2013-01-07 14:45:18 INFO    No branch found at remote location.

This is strange since my GitHub project is obviously at the correct web-location.
Thus - what have I done wrong in my configuration?
i.e. how should I have set up my Launchpad project to import from Github?
Answer: You need to use the "read-only git location" as shown on github. It is the same as the web URL (which you have used), but with .git appended to the end. You need to add this to the end of your URL.
To import a non-master branch, you must also append ,branch=branchname to the end of the URL.
Also, I think you may be confusing the term "master branch" with "branch named master" in this case. For your project, pulling https://github.com/fossfreedom/coverart-browser.git will give the contents of what you are calling release-0.6. I think omitting the ,branch=name piece will give what you want. However, when trying to branch your repository in bzr, I get the following error:

bzr: ERROR: Unknown extra fields in <Commit 3f47f3ed4e9e6f15a6c5229bf36d061ae4d86605>: ['gpgsig', '', '', '', '', '', '', '', '', '', ''].

This may cause importing to fail on Launchpad as well.
Comment: My default branch is not "Master" - so this will not work?
Comment: I'll test - but according to this bug report may not be possible - https://bugs.launchpad.net/launchpad/+bug/1000852
Comment: There are two bugs, the UI issue described in that bug, and the other issue which another user describes in his comments. He really should file a separate bug.
Answer: Launchpad supports importing git code directly since 16-10-2016, see the doc for setup instructions.
A note: if 1084403 bug still open when you're reading this, don't forget to clean your bzr import settings from old setup or you couldn't set a recipe for git code even if it's there.
Answer: A workaround for the unsupported ,branch=branchname is to create a fork on github first with with the default branch set to the branch you want to import.


Hydro Plant not allowing water flow through

Question: In my city, I have a hydro plant that is sitting across a river quite near my city. This dam holds back all of the water and there is a significant drop in water level before and after. When I say significant difference, I mean that on the up-river side the river is lapping at the edges of the river and at the down-river side, the river is totally empty.
However, my problem is that the hydro plant doesn't let any water through, and therefore is not generating any power (0MWh out). I can't for the life of me work out why this is happening, and it's bugging me because I don't want to have to buy another solar plant just yet.
The river in question runs out of a lake, joins with another river and then runs out into the sea. Although I do have water pumps on the upriver side of the dam, they are not consuming anywhere near enough water to totally drain the river.
Are there any ideas as to why I can't get my free river power?
Edit:
Comment: Have you checked which way the dam is facing? Maybe show us a screenshot
Comment: Read the [3 first results](https://www.google.ca/?gfe_rd=cr&ei=-ssjVZ7DB9LBgATmx4DgCg&gws_rd=ssl#q=cities+skylines+hydro+dam+not+operating), good hints on why a dam won't work. If anything fix this, please write up a answer, I also plan on getting a dam eventually.
Comment: Yes, this was the first thing I checked. The dam is definitely oriented the correct way. Love to show a screenshot but I'm at work.
Comment: Thanks for the pic. Can you check the water map if the river is still flowing? Maybe it's placed to close to the source it does no longer move. Also try to connect it to the power network and connect a road. Wait for about 5 minutes(real time) with x3 speed. That's waht i found so far.
Comment: Connected to the power, no movement on the river however. Why would placing it too close to the source cause an issue.
Comment: Might be because your dam is too high.
Answer: Since we figured it out in the comments here the answer:

Your dam is placed to close to the water source so your river has
  stopped flowing.

Apparently the the system works this way: There is a source point which generates water until it reaches a certain level. If that level is reached it stops producing water.
So when you build your dam your water level has risen above that threshold and there is no more water being produced, hence you created a new lake. Congratulations on that. ;)
Move your dam further along the river to fix the issue.
Comment: That sounds like a bug to me.  Hopefully that'll get fixed.


jQuery fill the body with images

Question: 1) We have , it's height and width varies (different resolutions).
2) Many blocks with images inside it, can be more than 50 blocks.
3) width and height are equal for each block.
How can we fill the body with all available images, that can be visible on current resolution, and hide others?
There should be no horizontal/vertical scrollbars.
For example, we have 50 blocks inside . 1024x768 can accommodate only 20, so we show them and hide others. If person changes browser window size to 1280 - we show more blocks and so on.
Actually I don't ask you to write the full script. I need the links on some similar scripts that are already work.
Its better if blocks can change themselves (like slideshow).
Thanks.
Answer: I'm trying to figure out an algorithm:
1) get the width of container containing the blocks (container should be relative, so that it expands when you resize the window). To get the width use .width or .outerWidth
2) divide the width of the container by the block's width, floor it. Now you know how many blocks fit in one row.
3) To calculate the height, this can be tricky because you may have a header or navigation etc. which cuts the vertical space down. So do this:
3.1) Get the height of the window $(window).height();
3.2) Get the container's top offset $('#container').offset().top
3.3) Subtract the offset from the window height - now you have the "real" height available
(note: if you have a footer etc. you have to subtract this reserverd space, too)
4) Divide the real available vertical space through the block's height (spend attention on margins/paddings) and floor this number. Now you know how many rows may fit in your space.
5) multiply max. rows and max. columns we've calculated, that's the maximum amount of blocks that fit in.
6) Get your blocks like $('.block') and iterate thru it $('.block').each(function(index) { ... });  now if the index is bigger than the max. number of blocks we've calculated, hide them!
7) Attach an event handler to $(window).resize(function() { }) and do the steps above on resize
Answer: Put them inside a block which has the CSS overflow:hidden property set. That way you can display them all, but the use will only see as many as will fit into the block. No code required.
Comment: you could see a part of the blocks which don't fit in!
Comment: @sled - in which case, a small bit of Javascript to resize the box to the nearest multiple of the known image size. Still relatively easy.

jQuery fill the body with images


How to get a count of Repetition of specific Table of Strings which are used in another table ? (MS Access)

Question: I have a table name "CompanyID"
ID  | Name
_____________
AAA | Semsung

BBB | NoKeea

CCC | JOKER

DDD | Papa

now I have another table "DETAILS"
Product | Company | Date
_________________________
asdfasdf| AAA     | asdfd

asdfasdf| AAA     | asdfd

asdfasdf| BBB     | asdff

asdfasdf| BBB     | asdff

asdfasdf| BBB     | asdff

asdfasdf| BBB     | asdff

asdfasdf| CCC     | asdfd

asdfasdf| CCC     | asdfd

asdfasdf| CCC     | asdfd

Now I want to get a count of how many AAA,BBB,CCC,DDD are there
ID | TotalCount
_______________
AAA| 2

BBB| 4

CCC| 3

DDD| 0

I tried using conditions like CompanyID.ID = Details.Company
but with that, I also get results like
AAA 2

AAA 0

AAA 0

AAA 0

BBB 4

Please Help Me
Comment: Please, provide the body of query you use...
Comment: You would appear to have values that look like duplicates in the first table but are subtly different.
Answer: You need a LEFT join of the tables and aggregation:
SELECT c.ID, COUNT(d.Company) AS TotalCount
FROM CompanyID AS c LEFT JOIN Details AS d
ON d.Company = c.ID
GROUP BY c.ID

Answer: Where as @Forpas answer is enough, you can also try-
SELECT CompanyID.ID, DCount("[Company]","[DETAILS]","[Company]='" & CompanyID.ID & "'") AS [Total Count] FROM CompanyID;


angularjs routing behaviour of content and function calls

Question: I'm new to Angular.js which is why I have a basic question regarding routing. I figured out how to create routes and inject specific .htmls by $routeProvider
var app = angular.module('test', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider
    .when('/', {
       templateUrl: 'routes/view2.html'
    });
});

but what I really don't get is how content or function of view2.html are handled in Angular.
Lets take view2.html. It has a
 with some text in a specific color. Nothing to special. But also it has a little slideshow which is called by $('slideshow').cycle() function.
All what happens is it displays me the
 tag in a different color and no slideshow function is called on my rootsite of the app.
Could you give me some approach how to actually solve this?
Thanks
Comment: Where did you put `$('slideshow').cycle()`?
Comment: actually it is in the `view2.html` where the related pictures are in. But I guess I'm having a logical problem about how angular is working.
Answer: Just load required view and then compile it. During compilation Angular processes all directives in view.
If you want to do this proper(Angular) way you should put such code like $('slideshow').cycle() inside of directive. And then use it like

angular.module('myModule', [])
  .directive('mySlideshow', [function () {
    return {
      restrict: 'A',
      link: function (scope, element) {
        element.cycle();
      }
    }
}]);

Directives documentation
Much more comprehensive documentation


Target class [ProductController] does not exist

Question: web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::post('/products/{qty}/add', 'ProductController@addProduct')->name('addProduct');

products-list.blade.php
<form action="{{ route('addProduct', 1) }}" method="post" class="ui form">
  <input type="text" name="qty" value="1" />
  <button type="submit" class="btn btn-primary" type="button">Add</button>
</form>

app/Http/Controllers/ProductController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function addProduct(Request $request, $qty)
    {
        dd($qty);
    }
}

But the controller class exists?
Answer: Namespacing won't help in this scenario, because it's just a string:
Route::post('/products/{qty}/add', 'ProductController@addProduct')

This will work:
Route::post('/products/{qty}/add', [ProductController::class, 'addProduct'])

or you can do:
Route::post('/products/{qty}/add', 'App\Http\Controllers\ProductController@addProduct')

Comment: That's because you never named your route. You need `->name('addProduct')` on the route definition to use `route('addProduct', 1)` in the view. Route names and *function* names are not the same thing.
Comment: I now have to use this with `` to prevent a `route doesn't exist` error for an immediate fix.


Height and distance with directions

Question: From a point due south of a tower, a man observes the angle of elevation of the top of the tower to be 60°. He then walks 60m due west on the horizontal plane and observes the angle of elevation to be 30°. Find the height of the tower and his initial distance from the tower..
My attempt

I have the figure but I could not solve it to get the answer.  please anyone solve this figure.
solving the figure, the initial distance.from the tower to the man does not match. The initial distance between the tower and the man is 63.63m. Where is the error
Answer: Consider the figure below.

The man is initially at point $S$, standing a distance $d$ from the base $B$ of the tower, which has height $h$.  He measures the angle of elevation, $\angle BST$, to be $60^\circ$.  He then moves $60~\text{m}$ west from $S$ to point $W$, where he measures the angle of elevation, $\angle BWT$, to be $30^\circ$.
Then
\begin{align*}
\tan 60^\circ & = \frac{h}{d}\\
\sqrt{3} & = \frac{h}{d}\\
d\sqrt{3} & = h
\end{align*}
and
\begin{align*}
\tan 30^\circ & = \frac{h}{x}\\
\frac{1}{\sqrt{3}} & = \frac{h}{x}\\
x & = h\sqrt{3}\\
  & = (d\sqrt{3})\sqrt{3}\\
  & = 3d
\end{align*}
Moreover, since $S$ is directly south of the tower and $W$ is directly west of $S$, $\angle BSW$ is a right angle, so $\triangle BSW$ is a right triangle with hypotenuse $\overline{BW}$.  Hence, by the Pythagorean Theorem,
$$d^2 + (60~\text{m})^2 = (3d)^2$$
Can you take it from here?
Comment: The answer for the height of the tower is 36.74m
Comment: The answers I obtain for the initial distance of the man from the tower, the height of the tower, and his distance from the tower when he takes the second measurement are, respectively, $d = \sqrt{450}~\text{m} \approx 21.21~\text{m}$, $h = \sqrt{1350}~\text{m} \approx 36.74~\text{m}$, and $x = 3d  \approx 63.64~\text{m}$.  The book's answers are inconsistent.  Since the angle of elevation is initially $60^\circ$, the height of the tower must exceed the man's initial distance from the tower.
Comment: Taussig, what is his initial distance from the tower?
Comment: Edited.  His initial distance from the tower is $d$.
Comment: But the answer doesn't match. The answer in my book is 63.63m.
Comment: The number in the book appears to be his distance from the tower when he takes the second reading, which is $x$ in my drawing.  I suggest you edit your question to state the book's answers for his initial distance and the height of the tower.  That could attract renewed attention to your question, which could reveal an error in the answers you have already received (which agree) or in the text you are using.
Comment: What answer, if any, does the book give for the height of the tower?
Comment: Then which answers are correct?
Comment: I believe that my answer and those given by infinitely curious are correct, that the book's answer for the height of the tower is correct, and that the book's answer for the man's initial answer is incorrect.  Instead, the answer of $63.63~\text{m}$ the author(s) gave you is the distance from the position where the man measured the angle of elevation to be $30^\circ$ to the base of the tower.
Answer: Please consider the figure below.

Since the figure for this question will be formed in 3D and I have to adjust it in 2D I will have to represent the $90^\circ$ like that.
$$\tan 60^\circ =AB/BC$$
$$therefore~BC=AB/{\sqrt3 } \tag{1}$$
$$\tan 30^\circ =AB/DB$$
$$therefore~DB=\sqrt{3}AB \tag{2}$$
$${BC^2}+{DC^2}={DB^2}$$
$${AB^2}/{3}+3600=3{AB^2} (as\hspace{1 mm} DC=60m)$$
$$therefore\hspace{1 mm} AB=\sqrt {1350}=36.742m$$
$$BC=AB/{\sqrt3}~(eqn. 1)$$
$$therefore\hspace{1 mm} BC=21.21m$$
$$AB=height\hspace{1 mm} of\hspace{1 mm} tower=36.742m$$
$$BC = initial \hspace{1 mm}distance\hspace{1 mm} from \hspace{1 mm}tower = 21.21m$$
Comment: what is his initial distance from the tower, then?
Comment: BC I.e 21.21 metres

Height and distance with directions


Android actionbar tabs multiple fragments in one tab

Question: I am creating a tabbed application and the main activity for one of the tabs is a listing of departments. When you click on a department it starts a new activity that lists the documents in the department.
My issue is when it shows the document listing, the tabbed view goes away. And I would like to keep the tabs on the top constantly. I have attempted to extend the TabActivity to each of the activities that are started under the tab, but then the listviews create over eachother.
I have also attempted to create the tabs without a tablistener starting an activity, so I can only create the listener if it is the first time the tab is called, but that is not allowed.
Any help would be appreciated, maybe there is some method I am completely missing?
Thank you!
Answer:
And I would like to keep the tabs on the top constantly.

Then you should not be starting an activity when the user taps on tab. Your tab contents should either be fragments or something else manipulated by your TabListener. The concept of activities being the contents of tabs is now deprecated (and, IMHO, was a bad idea to begin with).

I have attempted to extend the TabActivity to each of the activities that are started under the tab, but then the listviews create over eachother.

You will notice that TabActivity is deprecated, specifically for the activities-as-the-contents-of-tabs concept.
Comment: @AaronSmentkowski: You would put the list of departments and the list of documents side-by-side in a single tab. Or, you would run another `FragmentTransaction` to replace the list-of-departments fragment with the list-of-documents fragment. Or, you would give the `ListView`, that originally held some sort of `DepartmentAdapter`, a `DocumentsForSomeDepartmentAdapter`. Or whatever floats your proverbial boat.
Comment: Okay I understand that fragments should be started by clicking a tab, but how do I start another fragment after clicking on the tab and then selecting a department from the listview? Wouldn't I need to start an activity to include the fragment in it's xml layout? And also by TabActivity I meant the activity I use to instantiate my tabs not the deprecated one. Sorry about the confusing question.
Comment: @AaronSmentkowski: You would put the list of departments and the details of the selected department side-by-side in a single tab. Or, you would run another `FragmentTransaction` to replace the list fragment with a details fragment.
Comment: It is another listview of documents that is being created, rather than the details of the department. So it would need to recreate the list with the documents in the selected department.
Comment: FragmentTransaction. Seems like the exact tool I need. Thank you.


Show that $(1-it)|\psi\rangle-it\langle x|\psi\rangle|x\rangle$ is $|\psi\rangle$ rotated into the $|x\rangle$ direction

Question:
Here $|\psi\rangle$ is an $n$ component unit vector with $|x\rangle$ being one of the unit basis vectors, i.e., $|\psi\rangle=a_1|x_1\rangle+a_2|x_2\rangle+\cdots+a_x|x\rangle+\cdots+a_n|x_n\rangle$ and $\exp(-iHt)$ is a unitary operator since $H=|x\rangle\langle x|+|\psi\rangle\langle \psi|$ is hermitian.
$$
H=|x\rangle\langle x|+|\psi\rangle\langle \psi|\quad\&\quad\exp(-iHt)\approx I-itH\\
\exp(-iHt)|\psi\rangle=(I-itH)|\psi\rangle=(I-it|x\rangle\langle x|-it|\psi\rangle\langle \psi|)|\psi\rangle\\
=(1-it)|\psi\rangle-it\langle x|\psi\rangle|x\rangle
$$
How can we interpret from $|\psi(t)\rangle=\exp(-iHt)|\psi\rangle=(1-it)|\psi\rangle-it\langle x|\psi\rangle|x\rangle$ that the vector $|\psi\rangle$ is rotated into the $|x\rangle$ direction by the action of $\exp(-iHt)$ ?
Reference : Page 257, Quantum Computation and Quantum Information by Nielsen and Chuang
My Attempt
$$
|\psi\rangle=a_1|x_1\rangle+a_2|x_2\rangle+\cdots+a_x|x\rangle+\cdots+a_n|x_n\rangle\\
\langle x|\psi\rangle=a_x\\
\langle x|\exp(-iHt)\psi\rangle=(1-it)a_x-ita_x=(1-2it)a_x=\frac{1-2it}{\sqrt{1+4t^2}}\times\sqrt{1+4t^2}\times a_x=e^{i\theta}\sqrt{1+4t^2}\times a_x
$$
Consider another state $e^{-i\theta}|\psi\rangle$ which has the same characteristics as the state $|\psi\rangle$ because having an overall phase does not change the probability which is the amplitude squared.
The angle between $e^{-i\theta}|\psi\rangle$ and $|x\rangle$ is such that $\cos\theta=\sqrt{1+4t^2}a_x>a_x\implies$ the angle is lesser than that between the original state $|\psi\rangle$ and $|x\rangle$.
Is it an explanation for the required statement in my reference?
Answer: You've left out or missed a very important piece of information: the Hamiltonian is defined as
$$H=|x\rangle\langle x|+|\psi\rangle\langle\psi|$$
They then truncate the expansion of the exponential Hamiltonian:
$$\exp(-i Ht)=\sum_{n=0}^\infty \frac{(-i)^n H^n t^n}{n!}=I-itH-\frac{H^2 t^2}{2}+...\approx I-itH$$
Then
$$\exp(-i Ht)|\psi\rangle\approx (I-itH)|\psi\rangle$$
Using this truncation and the definition of $H$ gives
$$(I-itH)|\psi\rangle=(I-it|x\rangle\langle x|-it|\psi\rangle\langle\psi|)|\psi\rangle=(1-it)|\psi\rangle-it \langle x|\psi\rangle|\psi\rangle$$

EDIT: So when they say its been rotated slightly in the $|x\rangle$ direction they mean
$$|\langle x|\psi\rangle|^2<|\langle x|\exp(-iHt)|\psi\rangle|^2$$
To see this, note that
$$\langle x|\exp(-iHt)|\psi\rangle\approx \langle x|[(1-it)|\psi\rangle-it \langle x|\psi\rangle|\psi\rangle]$$
$$=\langle x|\psi\rangle-it\langle x|\psi\rangle-it\langle x|\psi\rangle^2=a_x-it a_x-it a_x^2$$
However, note that we can multiply $|\psi\rangle$ by $e^{i\phi}$ for any $\phi\in\mathbb{R}$ without changing the overall absolute value. Thus, choose $\phi$ such that
$$a_x\in\mathbb{R}$$
Taking the absolute value of this (with $a_x=a$) gives
$$|a_x-it a_x-it a_x^2|^2=a^2 (1  + (1 + a)^2 t^2 )$$
while on the other hand we have
$$|\langle x|\psi\rangle|^2=|a_x|^2=a^2$$
Thus, to show we have rotated in the $|x\rangle$ direction we simply need to show
$$a^2  (1 +  (1 + a)^2 t^2 )-a^2  >0$$
This is equivalent to showing that
$$ (1 + a)^2 t^2 >0$$
which is always true unless $|\langle x|\psi\rangle|=1$. But this is fine since that would imply $|\psi\rangle$ was already pointed in the $|x\rangle$ direction so $H$ would have no effect on it.
Comment: Yeah, your proof looks good to me
Comment: Thanks for responding and sorry for not mentioning the hamiltonian. But i understand this math on how to reach $(1-it)|\psi\rangle-it\langle x|\psi\rangle|x\rangle$, my boubt is how do we say that it is $|\psi\rangle$ rotated into the $|x\rangle$ direction ?
Comment: I have edited the post to better explain my doubt, could you please comment on it ?
Comment: okay thanks for the edit. I have added a "my attempt" section in the post, can it be an explanation for the rotation towards $|x\rangle$ other than the magnitude squared which is the probability of obtaining $|x\rangle$ ?


Route match using GPS coordinates (Trace is not continuous)

Question: We have been using route matching using the following URL in order to do route match using GPS coordinates:
http://rme.api.here.com/2/matchroute.json
This has been working normally.
During the recent days we found out that some requests submitted to the API return the following error:
{"faultCode":"461d67da-d9ff-4c1e-a6a1-4df9ed3f4322","responseCode":"400 Bad Request","message":"Trace is not continuous. Please submit each trace individually"}
I understand that the set of coordinates submitted are not continuous and we should do a small data preparation/filtering.
This could be easier if we knew what are the criterias from the data to be continuous.
Knowing this  we could properly clean the data and resubmit it.
Any help please?
Answer: As per our research, we found that there is a new fraud detection mechanism which is accidentally kicking in here.
We're going to fix it before end of July 2021.
Please let us know in case the issue pops up again after July.


feedback on dual boot parition sceheme (ubuntu + windows7)

Question: I recently did some research in disk partitioning and came up with the below scheme for my 500GB HD (dual boot Ubuntu + Windows 7, with some scope for experimenting with other OSes). Would be great to get some feedback on the same. I came across these concepts UEFI, MBR, GPT etc but i'm still not sure how they impact me and was planing to just use defaults as i go.
<code>75GB  NTFS Primary [windows7]
20GB  NTFS Primary [experimenting with OSes that only install on primary partitions]
Extended Parition
  8GB  linux-swap [1xRAM]
  75G  Ext4 [For Ubuntu]
  50GB EXT4 [Another spare partition for another linux variant]
  125 GB NTFS data1 [NTFS because supported by most linux and windows]
  125 GB NTFS data2 [NTFS because supported by most linux and windows]
</code>
Answer: assuming that you boot in legacy mode, it looks good.
If you boot EFI mode, it is preferable to format the drive gpt. Then all partitions can be primary. The first partition needs to be a 500 MB partition formatted to FAT32 and flagged as ESP (EFI System Partition). This partition is where the boot loaders go for the EFI system to boot from.
Behind this partition you can add the rest as primary partitions sized as you have described.
Comment: How do we choose to boot UEFI mode? Is there some option in the windows/ubuntu installation process where we need to specify this?
Comment: in the computer system settings. if it is a computer that supports UEFI


Can Genji deflect melee attacks?

Question: I understand that Genji can deflect pretty much anything, save for beam weapons and a handful of lethal accessories. Can he deflect melee attacks though? I've been playing more Reaper lately, so I'm at a much closer proximity to characters, and normally if a Genji uses his deflect I stop firing to wait. Can I melee him safely, so that I'm not just moving around waiting for his deflect to end?
Comment: I disagree @StevenVascellaro. No where in the linked question does it ask about melee attacks, but you took it upon yourself to answer it as such.
Comment: Pretty sure his deflect will block them so that he doesn't take damage, but not actually reflect them. That's what happens for Reinhardt's hammer, anyway. Didn't make this an answer because I'm not sure about other characters.
Comment: @Kaizerwolf Fair point. I have retracted my duplicate flag.
Answer: He will nullify the damage from any melee attack with the exception of Dragonblade, but won't reflect it back to the attacker.
Comment: @Kaizerwolf It nullifies the damage of Primal Rage, but not the knockback.
Comment: To add to this, Genji can't stop the melee attack of an enemy Genji using his ult Dragonblade.
Comment: So this counts for Reinhardt/Winston's Primal Rage melee attacks, as well as the punch/kick/gun-hit of other characters?
Comment: @Kaizerwolf I have not specifically tested Primal Rage, but definitely works with Reinhardt.

Can Genji deflect melee attacks?


How do I insert my form datas into my phpmyadmin database?

Question: I'm having problems with inserting my form data into the database. Help!!
if($_SERVER["REQUEST_METHOD"] == "POST" ){
    if(!empty($_POST)){

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "data";

        $conn = new mysqli($servername, $username, $password, $dbname);

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        $sql = "INSERT INTO cases (name, email, case, phone, address) VALUES ('{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}',
        '{$conn->real_escape_string($_POST['message'])}', '{$conn->real_escape_string($_POST['phone'])}', '{$conn->real_escape_string($_POST['address'])}')";
        $insert = $conn->query($sql);

        $conn -> close();
    });

Comment: You cannot use functions within a string like that, even with the braces. You need to break out of the string completely and use concatenation. But I'd recommend dropping that completely and instead use [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php) to prevent both SQL injection and pesky quoting/concatenation issues like this one.
Comment: What exactly is the problem? Are you getting an error? The wrong data?
Comment: Possible duplicate of [PHP parse/syntax errors; and how to solve them?](https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them)
Comment: By the way, phpmyadmin is not a database. It's an interface package to access the database, and has nothing to do with your code here.
Comment: You also have a syntax error with `});` It should be `}}`
Answer: Case is a MySQL reserved word. You have to enclose it in back ticks `. Changed to prepared statement.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try{
    $db = mysqli_connect($host, $user, $pass, $db);
}catch (Exception $e){
    $error = $e->getMessage();
    echo $error;
}
$sql = '
INSERT INTO cases
 (name, email, `case`, phone, address)
VALUES
  (?,?,?,?,?)
';
try{
    $stmt = $db->prepare($sql);
    $stmt->bind_param('sssss',$_POST['name'],$_POST['email'],$_POST['message'],$_POST['phone'],$_POST['address']);
    $stmt->execute();
} catch(Exception $e) {
    var_dump($e);
}

Comment: If you enabled MySQLi errors then why do you catch them? This is just making your code bloated unnecessarily.


Converting an array of objects (with string array elements) into a nested tree

Question: I've been trying to solve a problem with arrays and objects for some time now - but I still can't find the right solution.
This is my starting position:
list = [
{
    lastItemData: {data:"root"},
    path: ["Root"]
},
{
    lastItemData: {data:"level2_Summer"},
    path: ["Root", "Level2_Summer"]
},
{
    lastItemData: {data:"Level3_Monday"},
    path: ["Root", "Level2_Winter", "Level3_Monday"]
},
{
    lastItemData: {data:"Level4_Morning"},
    path: ["Root", "Level2_Spring", "Level3_Tuesday", "Level4_Morning"]
},
{
    lastItemData: {data:"Level3_Sunday"},
    path: ["Root", "Level2_Autumn", "Level3_Sunday"]
}]

and this is what i need:
result = [
{
    text: "Root",
    lastItemData: {data:"root"},
    Items:[
        {
            text:"Level2_Summer",
            lastItemData: {data:"level2_Summer"},
            Items: []
        },
        {
            text:"Level2_Winter",
            Items:[
                {
                    text: "Level3_Monday",
                    lastItemData: {data:"Level3_Monday"},
                    Items: []
                }
            ]
        },
        {
            text:"Level2_Spring",
            Items:[
                {
                    text: "Level3_Tuesday"
                    Items: [
                        {
                            text:"Level4_Morning"
                            Items:[],
                            lastItemData: {data:"Level4_Morning"},
                        }
                    ]
                }
            ]
        },
        {
            text:"Level2_Autumn",
            Items:[
                {
                    text: "Level3_Sunday"
                }
            ]
        },
    ]
}]

I'v try something like this (code is based on user jonas answer from my deleted post)
const property = list.reduce((previous, current, index) => {

            let acc = {}; //the accumulator that will go deep into the object
            const result = acc; //our result will be the top level object

            debugger;

            //Now we iterate over our array
            for (var i = 0; i < current.stringPath.length; i++) {
                debugger;
                //add the string part
                acc["level" + (i + 1)] = current.stringPath[i];
                //Add the children array
                acc["Items"] = [{}];
                //And go into the object
                acc = acc["Items"][0];
            }

            console.log(result)

            previous.push(result);

            return previous;

        }, []);

        console.log("property", property);

But unfortunately the result does not correspond to the desired structure. Can anyone help me?
Comment: Why would you delete a post about the same topic that already has an answer? This is rude towards the person that spent time answering you.
Comment: @Tomalak: Indeed, if it was the OP that deleted it rather than the community. Isabelle - If appropriate, you can find the previous post by going to [your profile > Activity > Questions](https://stackoverflow.com/users/3736673/isabelle-diez?tab=questions), scrolling to the bottom, and clicking [deleted recent questions](https://stackoverflow.com/users/recently-deleted-questions/3736673) (I think that's the right link), undelete it, and then either ask for clarification on existing answers to it (and delete this question) or, if this is a new question, link to that question in the text.
Comment: That does not show up for me, unfortunately.
Comment: I asked the question last time - but it was not very clear, the formatting of the code was wrong and in general unclear. One user asked me to delete the question and ask it again. What i did. But there was no solution to the question. Otherwise, I wouldn't ask the same question twice.
Answer: This is a far more complex problem as it looks like, because you have to build a nested structure with a given name (text property) and you need to check if that name exist or not. If not create a new object and push it to the parent array.
This solution features a hash table where all nested hashes for each level are collected and maintained. The result is an array with the wanted tree.
It works as follows:
First have a look into the root of the hash table and check if the path value exists. If not, create a new node with the information and push it to the hash collector, denoted with _. Then return that node and go on with iteration of the given path.
At the and of the path use lastItemData for the wanted object.

var list = [{ lastItemData: { data: "root" }, path: ["Root"] }, { lastItemData: { data: "level2_Summer" }, path: ["Root", "Level2_Summer"] }, { lastItemData: { data: "Level3_Monday" }, path: ["Root", "Level2_Winter", "Level3_Monday"] }, { lastItemData: { data: "Level4_Morning" }, path: ["Root", "Level2_Spring", "Level3_Tuesday", "Level4_Morning"] }, { lastItemData: { data: "Level3_Sunday" }, path: ["Root", "Level2_Autumn", "Level3_Sunday"] }],
    tree = function (array) {
        var result = [],
            hash = { _: { Items: result } };

        array.forEach(function (object) {
            object.path.reduce(function (o, p) {
                if (!o[p]) {
                    o[p] = { _: { text: p, Items: [] } };
                    o._.Items.push(o[p]._);
                }
                return o[p];
            }, hash)._.lastItemData = object.lastItemData;
        });
        return result;
    }(list);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comment: Thank you, Nina! I would never have found such a solution. I'm gonna try this right now.