What to do with confounding variables?

Question: I need to do an experiment. First let me describe present situation. The company that I work for is a cinema. It has a gaming section where people who are waiting for movies can pass time by playing games. People can pay only by using prepaid membership card. Unfortunately this gaming section is not generating enough sales. We are trying to find the cause(s).
My hypothesis is if we accept cash as payment, sales will increase.
My plan is to have experimental group and control group. The experimental group will accept cash payment, the control group doesn't. The sales of both groups are tallied before and after the experiment.
The difficult thing about this is that I can't find a way to isolate the 'cash payment' factor from other factors:

When the movie playing in the cinema is good, more people will come and sales will also increase
Each cinema only has one gaming section, I can't split it into two sections (one accepts cash, the other doesn't)
If several sites accept cash and several others don't, I don't think I can compare the results directly because the visitors are different, the number of gaming units are different

I'm looking for suggestions to isolate this 'cash payment' variable, or maybe another approach altogether.
Comment: How many cinemas are there, roughly?
Comment: Oops sorry, five, one doesn't have gaming section
Answer: Here are some suggestions relating your to bullet points above:

What about using the daily takings as an explanatory variable?

What you need to do is form an equation where you predict gaming sales given a number of other factors. There factors will include things you are interested in such as whether they used a prepaid card. However, you need to also include factors that you aren't interested in but have to adjust for, such as daily takings. Obviously, if the film is a blockbuster then gaming sales will increase.

Suppose you have N cinemas. Select N/2 cinemas and put them in group A and rest go in Group B. Now let Group A be the control group and B the experimental group. If possible, alternate this set-up, i.e. make Group A the experimental setup for a few weeks.
If you can mix over groups (point above) then this isn't problem. Even if you can't you can include a variable representing the number of gaming units.

The statistical techniques you will probably need is multiple linear regression (MLR). Essentially, you build an equation of the form:
<code>Gaming sales = a0 + a1*Prepaid + a2*Takens + a3*<other things>
</code>
where

a0, a1, a2 are just numbers
Prepaid is either 0 or 1
Takens are the daily takens.

MLR will allow you calculate the values of a0-a2. So if a1 is large this indicates that Prepaid is important.
Comment: I'm not clear about using the daily takings, can you elaborate on that please?
Comment: @endy_c Does that help?
Comment: OK so instead of trying to eliminate bias from the movie, I can include it in the experiment, got it, thanks!
Answer: How about comparing the before and after you introduce the cash option across the two groups? Say you assign half the cinemas to the cash option (treatment) and half continue with no-cash (control). Now, you can compare how sales changed in the treatment group following the introduction of the cash option, and also compare how sales changes in the control group. If indeed the cash option is effective, then the change in the treatment group will be bigger than the change in the control group.
I recall reading an interesting statistical analysis done by Prof Ayala Cohen at the Technion's statistical lab for assessing the effect of removing advertising boards from a major highway in Israel on accidents in a similar fashion: to control for other factors that changed during this period, they compared the reduction in accidents before/after to a parallel highway where advertising boards remained there throughout the period.
Comment: (+1) I was going to suggest something similar. This is sometimes known as a 'difference in differences' estimator
http://en.wikipedia.org/wiki/Difference_in_differences
Comment: I suppose the treatment cinema and the control cinema should be as similar as possible for this method? They are spread in 3 different cities and may play different movies.
Comment: @endy I am not sure those differences matter. The suggestion is to use *change in gaming sales* in treatment relative to control and not baseline sales as an indication of treatment effectiveness. Thus, while different cinemas, different movies etc may have different baseline gaming sales, the change in gaming sales would be a function of the presence or absence of the treatment.
Comment: Sorry I'm still not clear, the movies are not just different between cinemas, the movies change too. If one cinema starts playing a new interesting movie while the others haven't, this one cinema may have bigger change in gaming sales, no?
Answer: Aside from my practical statistical suggestion, I wanted to raise a slightly different issue: I realize that the cinema's goal is to maximize revenues, and of course the analysis (and strategy) can be geared towards that goal. However, I would like to suggest a broader, holistic view that companies as well as analysts should consider: the overall benefit. In this case, we can consider the value of the gaming addition to cinema goers. Are they happier or more satisfied with the overall experience? (this can be evaluated, e.g., via a quick questionnaire). Or, if the gaming is educational, for instance, then perhaps there is added benefit to those playing? I recall that in several cinemas in the U.S. there are word games on the screen before a movie starts. These can be perceived as fun and educational and could therefore be value added. In fact, if movie goers perceive the gaming service as value added, then they will likely choose this cinema over others and perhaps even visit it more frequently.
What I am trying to say is that it is useful to define "success" in a broad manner and to think big. In the end, success will depend also on the wellness of the "customers" and the impact of "treatments" on society, culture, the environment, etc.
Sorry if this is too philosophical, but I have had so many MBA students maximizing short-term financial gains and too few thinking of issues that are not monetary. Yet, data mining and statistics can be used for broader causes.
Comment: The preferred approach to answering questions is to provide one answer per question. Ideally, any new material should be integrated with an existing answer. You may want to look at this discussion on the meta site: http://meta.stats.stackexchange.com/q/635/28 FYI- the meta site is the place to go to if you need to know how the site works, have any questions about the site's functioning etc.
Comment: Thanks for the reminder Galit, we will keep the big picture in mind.

What to do with confounding variables?


Variational calculus with pointwise constraint involving derivative

Question: I am looking for the Euler-Langrange equations for the following problem:

Find the extremal points of the functional
$$ \mathcal{F}(u)=\int_\Omega F(x,u(x),D(u)(x)) dx $$
under the the pointwise constraint $G(D(u))=0$.
Here, $u:\Omega\subset\mathbb{R}^n\to\mathbb{R}^m$ and $F:(\Omega,\mathbb{R}^m,\mathbb{R}^{m\times n})\to\mathbb{R}$. Furthermore $D(u)$ denotes the Jacobian of $u$.

Motivation:
I am looking for a trajectory $u(t,p)=(x(t,p),y(t,p))$ under the constraint $|u_p|=1$.
Known related results: I know that for pointwise constraints of the form $G(u)=0$, the above can be achieved by introducing Langrange multipliers and simply finding the extremal points of $F(x,u(x),D(u)(x))+\Lambda(x)\cdot G(u(x))$, however I am unsure if the results can be extended to the case involving the derivatives of $u$.
I would appreciate your help or references to e.g. a textbook. Thank you very much in advance. :-)
Answer: Observe that after a Taylor expansion, and choosing $v(x)\in C_c^{\infty}(\Omega)$,
$$\lim_{\varepsilon\to0}\frac{1}{\varepsilon}\left(\int_{\Omega}\Lambda(x)G(D(u(x)+\varepsilon v(x))dx\int_{\Omega}\Lambda(x)G(D(u(x))dx\right)
=-\int _{\Omega}D(\lambda(x)u(x))G'(D(u(x)))v(x)dx
$$
means
$$\frac{\delta\mathcal{F}}{\delta u}=\mathrm{Usual\ stuff}-D(\Lambda(x)u(x))G'(D(u(x)).
$$
Comment: But is it so straightforward that $F+\Lambda G$ is indeed the correct functional in this case?
Comment: Yes. And this would still work if G depended on any derivative of u (as long as everything is smooth enough). Why do you doubt it?
Comment: I followed the proof for this kind of constraint ($G(u)$) and the extension to $G(u,D(u))$ was not obvious at all.


Adding a 'Add New Listing' (Create Content) Link on Local Tasks Menu

Question: I am working on making user pages for a certain type of user who can add/edit/delete content on my Drupal site. I've figured out how to use Views to create a 'Manage Listings' tab which appears on the user's profile, now I need to make another Local Task tab (or any kind of link) that allows the user to add new content.
I tried just adding a header to the view using basic markup text that contains:
Add New Listing

But because the link is displayed from the 'users/admin/' page, the link ends up bringing them to 'users/admin/node/add/' which doesn't exists (obviously). How can I create a create content link without messing up the path?
I would provide a screenshot, but my reputation isn't high enough to do so. Thanks.
Answer: Add a forward slash at the beginning:
Add New Listing


"This SqlTransaction has completed; it is no longer usable."... configuration error?

Question: I've been working on this for about a day and a half now, and searched numberous blogs and help articles on the Web.  I found several questions on SO related to this error, but I didn't think they quite applied to my situation (or in some cases, unfortunately, I couldn't understand them well enough to implement :P).  I'm not sure I can describe this well enough for help... but here goes:
We have a .NET app to track our resources.  There's an export function to copy a resource to the time tracking system and the billing system; this accesses a stored procedure that links to the time and billing databases.
I recently moved the billing system database to a new server (original server: Server 2003 SP2, SQL 2005; new server: Server 2008 R2, SQL 2008 R2).  I have a Linked Server set up that points to the 2008 databases.  I updated the stored procedure to point to the 2008 server, and then I got an error about MSDTC and RPC (http://www.safnet.com/writing/tech/archives/2007/06/server_myserver.html).  I enabled 'rpc/rpc out' on the Linked Server and set MSDTC to allow Network Access (something like this: http://www.sqlwebpedia.com/content/msdtc-troubleshooting).
Now I'm getting the above, when I try to run the export function: "This SqlTransaction has completed; it is no longer usable." What seems odd to me is that when I just run the stored procedure (from SSMS), it says it completes successfully.
Has anyone seen this before?  Have I missed something in the configuration?  I keep going over the same pages, and the only thing I found was that I didn't reboot after making the MSDTC changes (mentioned in here: http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/7172223f-acbe-4472-8cdf-feec80fd2e64/).
I can post part or all of the stored procedure, if it would help... please let me know.
Comment: http://stackoverflow.com/a/15923556/900284
Answer: I believe this error message is due to a "zombie transaction".
Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.).  Does the .Net code commit the transaction after the SP has already committed it?  Does the .Net code roll it back on encountering an error, then attempt to roll it back again in a catch (or finally) clause?
It's possible an error condition was never being hit on the old server, and thus the faulty "double rollback" code was never hit.  Maybe now you have a situation where there is some configuration error on the new server, and now the faulty code is getting hit via exception handling.
Can you debug into the error code?  Do you have a stack trace?
Comment: looks like that's on the right track... I found another tool (dtctester) and my original error was due to a misconfiguration (I thought I'd checked the firewall on the new server... guess that's what I get for assuming).  Looks like my new error matches what you're saying, "Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 2."  I'll have to do a little more digging and get back to you.
Comment: I'm assuming there was a duplicate in the code... I commented out the Rollback Transaction in the stored procedure, and it looks like everything's working now.  I'm waiting for the user to test, but it's getting past the point where it was erroring before. :)  Thanks for the input!
Comment: I've run my code like 300 times during debugging today and this is the first time I've seen this error...
Answer: I had this recently after refactoring in a new connection manager.  A new routine accepted a transaction so it could be run as part of a batch, problem was with a using block:
public IEnumerable<T> Query<T>(IDbTransaction transaction, string command, dynamic param = null)
{
  using (transaction.Connection)
  {
    using (transaction)
    {
      return transaction.Connection.Query<T>(command, new DynamicParameters(param), transaction, commandType: CommandType.StoredProcedure);
    }
  }
}

It looks as though the outer using was closing the underlying connection thus any attempts to commit or rollback the transaction threw up the message "This SqlTransaction has completed; it is no longer usable."
I removed the usings added a covering test and the problem went away.
public IEnumerable<T> Query<T>(IDbTransaction transaction, string command, dynamic param = null)
{
  return transaction.Connection.Query<T>(command, new DynamicParameters(param), transaction, commandType: CommandType.StoredProcedure);
}

Check for anything that might be closing the connection while inside the context of a transaction.
Answer: Had the exact same problem and just could not find the right solution.
Hope this helps somebody.
I have an .NET Core 3.1 WebApi with EF Core. Upon receiving multiple calls at the same time, the applications was trying to add and save changes to the database at the same time.
In my case the problem was that the table that the data would be saved in, did not have a primary key set.
Somehow EF Core missed when the migration was ran from the application that the ID in the model was supposed to be a primary key.
I found the problem by opening the SQL Profiler and seeing that all transactions was successfully submitted to the database (from the application) but only one new row was created. The profiler also showed that some type of deadlock was happening but I couldn't see much more in the trace logs of the profiler.
On further inspection I noticed that the primary key identifier was missing on the column "Id".
The exceptions I got from my application was:

This SqlTransaction has
completed; it is no longer usable.

and/or

An exception has been raised that is likely due to a transient
failure. Consider enabling transient error resiliency by adding
'EnableRetryOnFailure()' to the 'UseSqlServer' call.
Comment: I had the same symptoms ("This SqlTransaction has completed; it is no longer usable" error) in .NET 5 with EF Core 5.06.  But in my case the error started when I changed a table from a primary key of INT [Id] to a **composite key**. (Yes, the composite key was explicitly defined via Fluent API declaration.) When rapid operations were performed on the composite key table, about 10-20% of calls would fail with that error. **Going back to a single numeric key eliminated the error**.  Just posting this in case it helps anyone.
Comment: This is absolutely the right answer. I never thought that not having primary key can trigger this issue, even though the column was identity. Added primary key and this problem is gone. Thanks a lot @Danny.
Comment: I am glad my answer helped you @PrashantGupta!
Answer: I have the same problem. This error occurs because conection pooling.  When exists two or more users acess the system the connetion pooling reuse a connetion and the transation too. If the first user execute commit ou rollback the transaction is no longe usable.
Comment: This seems to be my problem too as it only occurs when more than one user is in the application.  Any ideas how to fix this?
Answer: I have recently ran across similar situation. To debug in any VS IDE version, open exceptions from Debug (Ctrl + D, E) - check all checkboxes against the column "Thrown", and run the application in debug mode. I have realized that one of the tables was not imported properly in the new database, so internal Sql Exception was killing the connection, thus results into this error.
Gist of the story is, If Previously working code returns this error on a new database, this could be database schema missing issue, realize by above debugging tip,
Hope It Helps,
HydTechie
Comment: Thanks for the tip, going through a REALLY Baroque (Wheels within wheels within wheels .....) legacy application and this helped narrow down the issue
Comment: In my case this was due to an error occurring in a stored procedure call embedded in another stored procedure.
Answer: Also check for any long running processes executed from your .NET app against the DB. For example you may be calling a stored procedure or query which does not have enough time to finish which can show in your logs as:

Execution Timeout Expired. The timeout period elapsed prior to
completion of the operation or the server is not responding.

This SqlTransaction has completed; it is no longer usable.

Check the command timeout settings
Try to run a trace (profiler) and see what is happening on the DB side...
Comment: This was our case.
Answer: Here is a way to detect Zombie transaction
SqlTransaction trans = connection.BeginTransaction();

//some db calls here

if (trans.Connection != null) //Detecting zombie transaction
{
  trans.Commit();
}

Decompiling the SqlTransaction class, you will see the following
public SqlConnection Connection
{
  get
  {
    if (this.IsZombied)
      return (SqlConnection) null;
    return this._connection;
  }
}

I notice if the connection is closed, the transOP will become zombie, thus cannot Commit.
For my case, it is because I have the Commit() inside a finally block, while the connection was in the try block. This arrangement is causing the connection to be disposed and garbage collected. The solution was to put Commit inside the try block instead.
Answer: In my case the problem was that one of the queries included in the transaction was raising an exception, and even though the exception was "gracefully" handled, it still managed to roll back the entire transaction.
My pseudo-code was like:
var transaction = connection.BeginTransaction();
for(all the lines in a file)
{
     try{
         InsertLineInTable(); // INSERT statement might fail and throw an exception
     }
     catch {
         // notify the user about the error on line x and continue
     }
}

// Commit and Rollback will fail if one of the queries
// in InsertLineInTable threw an exception
if(CheckTableForErrors())
{
    transaction.Commit();
}
else
{
    transaction.Rollback();
}

Answer: In my case, I've some codes which need to execute after committing the transaction, at the same try-catch block. One of the codes threw
an error then try block handed over the error to its catch block which contains the transaction rollback.
It will show a similar error. For example, look at the code structure below :
SqlTransaction trans = null;

try{
 trans = Con.BeginTransaction();
// your codes

  trans.Commit();
//your codes having errors

}
catch(Exception ex)
{
     trans.Rollback(); //transaction roll back
    // error message
}

finally
{
    // connection close
}

Hope it will help someone :)
Answer: For what it's worth, I've run into this on what was previously working code.  I had added SELECT statements in  a trigger for debug testing and forgot to remove them.  Entity Framework / MVC doesnt play nice when other stuff is output to the "grid".  Make sure to check for any rogue queries and remove them.


Compactness of sum of line segments in $\mathbb{R}^3$

Question: Let $f,g : \mathbb{X} \to \mathbb{R}$, where $f,g$ are continuous, and $\mathbb{X}$ is compact. Let $I_{x}$ be line segment with endpoints $(\cos(f(x))$, $\sin(f(x)),0)$ and $(0,0,g(x))$. Prove that $Z= \bigcup_{x \in X }$ $I_{x}$ is a compact subset of $\mathbb R^{3}$.
I only know that continuous functions on compact set has extreme values. Cos and sin are bounded functions. But what else? It isn't enough to the compactness
Answer: Hint: What is the general form for an element of $Z$? What parameters does your formula depend on? What topological spaces do those parameters come from? Does this turn $Z$ into the image of some function? What can you say about this function?
Comment: This formula depends on two continuous functions and element of compact set. You mean that image of compact set under continuous function is a compact set?
Answer: The most important thing for you here is that compactness pushes forward under continuous maps. Also each individual line segment in your construction is compact. But then you're dealing with this infinite union $Z$, and the arbitrary union of compact things needn't be compact.
So here's a hint: see if you can rewrite $Z$ as the image of a map continuous $h: \mathbb{X} \times [0,1] \to \mathbb{R}^3$. (The $[0,1]$ stands in for a line segment.)
Comment: You mean  t*$(\cos(f(x))$, $\sin(f(x)),0)$ + (1-t)* $(0,0,g(x))$?
Comment: That would do the trick.
Comment: But this is a formula for one line segment. What else?
Comment: I see a formula in both $t$ and $x$ right there!
Comment: Yes, because x belongs to $X$ and t belongs to $[0,1]$
Comment: So you've defined the map $\mathbb{X} \times [0,1] \to \mathbb{R}^3$
Comment: And that's all to show the compactness of Z?
Comment: You have a continuous map $h$. What topological property does its domain have? What is its image? What topological property can you conclude about its image?
Comment: A domain is a product of two compact spaces, image is an image under continuous map so it is... compact?
Comment: The product of compact spaces is compact. The continuous image of a compact set is compact.


Free database for Entity Framework in WPF MVVM

Question: I want to use a free database to do some databinding (storage) in my WPF Application (PixelSense).
I have already used SQL Server 2010 with Visual Studio 2010 and it works very fine.
I've heard also that Entity Framework does not work great with MySQL due to some incompatibility issues, and SQLite doesn't support Booleans.
What do you suggest for me in this case ?
Edit
Thank you, I've choosed Microsoft SQL Server 2008 R2 Express
Why : Free, by Microsoft, almost the same as SQL Server
Comment: Have you tried the express edition of sql-server?
Comment: Have you looked at this post? http://stackoverflow.com/questions/76488/using-mysql-with-entity-framework
Answer: In microsoft world, you can use :

Sql Server Express

10Gb per DB size limitation

Sql Local DB, which is the replacement for Sql Server User Instance. It's part of Sql Server Express.

10Gb per DB size limitation

Sql Compact

4Gb per DB size limitation

As it's Microsoft products, you will have less probability of issues.
My preference goes to Sql Compact because of its low binaries footprint. There are however some limitation (ntext not supported very well), at least in the version I used some years ago.
Good to know, Access database are not supported. While Access has not a good reputation, for local app it make senses.
Outside Microsoft World, SqlLite has a good reputation.
Comment: It also depends on the amount of data that you are working with. Compact addition has 4GB size limit vs 10GB for Express. Here is an article that compares all 3 mentioned above side-by-side: http://blogs.msdn.com/b/jerrynixon/archive/2012/02/26/sql-express-v-localdb-v-sql-compact-edition.aspx
Comment: I removed SQLLite as you have found an issue (boolean not supported)
Comment: Do not hesitate to tell us which DB you choose and why
Comment: @Dmitriy: it's a community wiki. Feel free to update the answer directly
Comment: I don't have enough rep yet :(. Feel free to copy my comment to your answer. Thanks for pointing this out.


Is an advantage for a left-handed to play vs a right-handed tennis player?

Question: I often listen to the tennis matches that a left-handed has an advantage to play tennis.
What would be the reasons of this "skill"?
Answer: Lefties play a style of tennis that is almost mirror image to that of a righty. For instance, their forehand (usually their stronger shot) is on the side of the court where a righty's backhand (usually their weaker shot) would be. When they hit a slice serve it curves to the receiver's left rather than their right.
Since lefties are fairly uncommon in the game, players get accustomed to the way that righties' serves curve toward or away from them, and they feel safe hitting to certain areas of the court (usually the backhand side of their opponent). Players form these habits playing righties, to the point where it is almost unconscious. When they play a lefty, they have to mentally override these tendencies, which can be difficult and lead to more unforced errors.
Another commonly brought up advantage that a lefty has is that their better serving side (when they serve across their body) is the ad side. This is where most of the important points of a match are played from (since the only time you can win a game on the deuce side is at 40-15; you can win a game from the ad side at 40-0, 40-30, or any ad point from deuce onward).
To prepare for playing a lefty, professional players will often practice with a lefty the day before or the day of their match. This allows them to get accustomed to returning their serve and how to construct points in baseline rallies.
Comment: I'm fairly sure that at the professional level the advantage of "unaccustomed" has passed. [This link] (https://summerofjeff.wordpress.com/2011/02/12/the-prevalence-of-lefties-in-mens-tennis/) had the same thought as I did (that it's an advantage at entry level, which leads to lefties being encouraged by success and therefore making them more likely to stick it out and become pro), but the data set wasn't really big enough to prove it.
Answer: Another note on lefties serving to righties: When the lefty serves on the ad side (to a righties backhand), the returner must move further out since it harder to reach with backhand than with forehand on a service return. The righty doesn't have the same advantage when serving to a lefty (on the deuce side), because they have less experience doing it. Also jamming a returner with a serve to their body will naturally cause the returner to return to a lefty servers forehand, due to defensive habit. These body serves are particularly effective for a lefty on the first serve. In my experience players rarely practice with handedness in preparation for USTA competition. Such practice would be a good idea, but would require more commitment than a few days before a match. Instead, righties should find lefty friends to compete with for season after season. A righty needs to learn how to return the lefty serve and how to serve to a lefty. Left handed players often struggle playing other left handed players because of lack of experience too.
Comment: Excluding the experience of the player, the last sentence is ambiguous as a lefty against another lefty would both be in the same situation


What to do to improve bass resonance in mid sized piano?

Question: Got myself a mid sized piano (110 height). Great tone in upper area but lower area is collapsed compared to a full size piano (of course).
Has anyone tried to reduce acoustic shortcuts in smaller pianos, using bass-reflex or passive radiators?
UPDATE
Not that it covers my original idea about fixing the shortcut in the resonance-plate but good advices at:
https://www.pianobuyer.com/article/how-to-make-a-piano-room-sound-grand/

Avoid wall-to-wall placement (avoid fluttering)
Explore open angle to back wall
Open doors to adjacent rooms
Comment: Where it is in the room will also have an important bearing.
Comment: Yeah I mean putting it in a corner might be your best bet
Comment: Have you tried playing with top open or the front panel off?
Comment: Thanks, found many hints at https://www.pianobuyer.com/article/how-to-make-a-piano-room-sound-grand/ that I'll start off with.
Answer: This might be a bit overkill but some may find it of interest..
A solution could be to pick the sound of the piano, EQ it in order, for instance to boost a bit the bass, and broadcasted in the room thanks to very clean loudspeakers...
If the electronic broadcast part bothers you, or if you want to add a bit of caché to your room you can also use an acoustic resonator ;).
Comment: Ah, an acoustic resonator could be it! Very interesting! :)
Comment: @Teson I am sure you will have more chance / easier time, playing with the room and panels, but I thought it was worth mentioning. Good luck!


Prove that if B−C ⊆ $A^c$ then A∩B⊆C

Question: This is my proof:
let x ∈ B - C
which means: x ∈ B and x  ∉ C and $A^c$ = B ∪ C
and because x ∈ B , B−C ⊆ $A^c$ .
and because x  ∈ B and x  ∉ A: A ∩ B = ∅ ⊆ C  because ∅ is a subset of any set.
Did I prove this correctly?
Answer: Your proof starts with $x\in B-C$ and then $A^c = B\cup C$ which doesn't follow.
You're trying to show if $B-C\subset A^c$, then $A\cap B\subset C$. Here's an approach:
$B=(B\cap C)\cup (B-C)$, so $$A\cap B = A\cap((B\cap C)\cup (B-C)) = (A\cap (B\cap C))\cup (A\cap B-C)$$But $B-C\subset A^c$ by assumption, so $A\cap B-C\subset A\cap A^c = \emptyset$. Therefore, $$A\cap B = A\cap (B\cap C) = A\cap B \cap C\subset C$$
Alternatively, suppose $x\in A\cap B$ and $x\not\in C$, then $$x\in A\cap B\cap C^c = A\cap (B\cap C^c)\subset A\cap A^c = \emptyset$$Contradiction, so $A\cap B\subset C$
Comment: I don't get B=(B∩C) part of B=(B∩C)∪(B−C)
Comment: In words, $B$ as a set consists of elements that are in both $B$ and $C$ ($B\cap C$) and elements in $B$ that are not in $C$ ($B-C$) (kind of an excluded middle argument). So $B$ can be written as the union of both of these sets.

Prove that if B−C ⊆ $A^c$ then A∩B⊆C


How do I add a foreign key in SequelPro?

Question: I'm using Sequel Pro 0.9.9.1 Build 3408.
I want to add a foreign key to a table and also on delete cascade.
I can't find anything in the GUI that allows me to add foreign keys.
Anyone know how to do this?
Answer: You can either declare your table completely in SQL, and just add it that way.
Or you can declare the columns in the table so that it is defined. Then select the table and click on Relations. Using the + at the end of the screen will allow you to specify a table and column and if you want cascade behaviour on the update/delete.
The image below may help orient you, it's a bit crude but hopefully shows you where to click.


Can somebody help me with this mathematical induction proof?

Question:
It's a recursive equation and I'm not sure how to demonstrate it through mathematical induction.
Comment: Well, given that you are handed the final form, an inductive proof should be straight forward.
Comment: @lulu thank you, I honestly have no idea how to do it
Comment: What have you tried? The way to do induction is like this: Assume for some value $n$ the claim holds, i.e. $a_{n} = 2+\frac{n(n+1)(2n+1)}{12}$ and use that to prove that the formula holds for $a_{n+1}$. Then if it holds for $n=1$ this implies it holds for $2$, $3$, and so on. Which part are you stuck on?
Answer: Let $a_n$ be defined as in the problem, and for convenience let $f(n) = 2 + n(n+1)(2n+1)/12$. You're being asked to prove, by induction, that $a_n = f(n)$ for all $n\ge0$. By the definition of induction, that means proving the following two statements:

$a_0=f(0)$ (this should be easy); and
for every $n\ge1$, if $a_{n-1}=f(n-1)$, then $a_n=f(n)$.

Do you have an idea how to prove those statements?
Comment: thanks @Greg Martin . No, I honestly don't know how to prove those statements. I'm completely lost on this subject :/

Edit: I mean, a0=f(0) I guess I can just change n to be 0 and calculate it but not sure if that's even a way to prove it?
Comment: Also, it should be for all n that are equal or greather than 1 so the first one should be a1 = f(1) according to your explanation ?
Answer: First you provisionally assume that the following statement is true for some $k$:
$a_k =2 + \frac{k(k+1)(2k+1)} {12} $
Then  you use the recursion rule to prove (not assume!) that the next term follows the pattern, i.e.:
$a_{k+1} =2 + \frac{(k+1)(k+2)(2(k+1)+1)} {12} $
The algebra basically amounts to showing (this has to be shown!) that:
$2 + \frac{k(k+1)(2k+1)} {12} + \frac{(k+1)^2}2 = 2 + \frac{(k+1)(k+2)(2(k+1)+1)} {12} $
which is elementary algebra, so you should be able to handle this yourself.
And you only need to end with the base case, which is simply establishing that $a_0$ is indeed $2$ as stated, which is basically showing that $2 + \frac{(0)(0+1)(2(0)+1)} {12} = 2$, which is trivial.
If you cannot follow why this process works this way, you really should go back to your study materials and refresh yourself on mathematical induction. It helps to think of it as dominoes: you first show that if you pick a domino anywhere in a long (infinite) line and topple it, the next one will surely fall also. That establishes that all dominoes from that point on will just keep falling. Then you show the base case - that the first domino in the chain definitely falls to start with. Now you've proven that all dominoes definitely fall. That's the best elementary metaphor for mathematical induction I can come up with. Hope it helps.
Comment: @Natalia Most welcome. Sometimes a different way of stating it is all that's needed to give someone a sudden spark of insight. :)
Comment: thank you @Deepak !


consonant skips in 2nd species counterpoint

Question: From The Complete Musician by Laitz

Consonant skips are motions by a third.

Well, I think we have a confusion here because by saying 'consonant' I suppose Laitz implied that both vertically and horizontally consonant; in other words, both the intervallic distance between the CF and the counterpoint melody and the intervallic distance between the current note of the counterpoint melody and the preceding tone should be consonant (m3,m6,P5,P8). I drow on that conclusion depending on the definition of 5-6 technique on the same page (see the photo below)
However, when I applied the definition of consonant skips to the instance given (please see the second photo below) we don't have a vertically consonant weak-beat. Therefore, I think Laitz's definition of consonant skips lacks information, doesn't it? What's the exast rule for that consonant skips, please?

On the same page, however, there is a P4 in the melody which is not a consonant interval. But Laitz's definition orders that 'To skip or leap, the weak-beat note must be consonant with both the preceding melody note and the CF.'
Comment: If I read this right, here you would use a consonant leap up a fourth to F because that is consonant the the CF while E is not
Comment: I agree, but what I do is applying the author's definition without questioning it and as you see, it fails -if I'm not mistaken.
Answer: Laitz is saying that "skips" are thirds. That is, "steps" are seconds; "skips" are thirds; and "leaps" are anything a fourth or larger. Two sentences after the one quoted, Laitz writes:

To skip or leap, the weak-beat note must be consonant with both the preceding melody note and the CF. (emphasis mine).

When Laitz writes "consonant skips are motions by a third," he's really just defining what a "skip" is and does not mean "all motions by third are consonant skips".
Fourths are sometimes consonant and sometimes dissonant, depending on context. In the case of Laitz's Example 2.15, the fourth is consonant. For an explanation of the treatment of fourths, see

How can a perfect fourth interval be considered either consonant or dissonant?
Comment: No @Aaron Laitz already defined P4 interval as dissonant in the book, several times, no doubt about that. But it's a great topic to discuss, in general. However, I don't understand why the comments I wrote to your answer were deleted and who deleted them.
Comment: @orhantorun In that case, Laitz is either misleading or incorrect. P4 is considered dissonant in some situations and not in others. See the linked post for a more detailed explanation.
Comment: Regarding the deletion of comments, if you click on the flag icon next to a comment, you'll see a list of reasons why a comment might be deleted. When a post is flagged, it is then up to the site moderators to decide on whether or not to actually delete the post.
Comment: @orhantorun I wonder if part of the issue is that P4 is always dissonant against the CF in first species counterpoint. Perhaps Laitz's defitions that you mention are in that context.
Comment: the problem is that there is nothing about the previous comments, including flags.
Comment: No, for 2nd species counterpoint as well. It's not just Laitz's point though.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/138515/discussion-between-aaron-and-orhan-torun).
Answer: Blame it on Laitz.  I do.  He is using the term consonance in two very different contexts and only one of them is right.  Consonance is...

consonance and dissonance, in music, the impression of stability and repose (consonance) in relation to the impression of tension or clash (dissonance) experienced by a listener when certain combinations of tones or notes are sounded together. (source - emphasis mine)

Put simply, if you play two keys on the piano at the same time and they sound nice to you, they are consonant.  If they make you cringe, they are dissonant.  I think the misunderstanding is Laitz's claim that

The weak-beat note must be consonant with both the preceding melody note and the CF.

It's confusing because he's using consonance to describe two successive notes in the first part of his instructions, and to describe to simultaneous notes in the second part.
First Part
The weak-beat note must be "consonant" with the note just before it.  This has nothing to do with the CF note and everything to do with making your melody something that is reasonably idiomatic to sing.  In species counterpoint melodies are supposed to follow certain specific guidelines.  Intervals wider than a fifth are not to be used, neither are intervals requiring an accidental (sharp or flat) or intervals forming a "tritone" (augmented fourth or diminished fifth).  So in this first idea, he's simply saying that your second melody note should be a second, third, perfect fourth, or perfect fifth away from the first melody note.  This is not the standard definition of consonance, nor are these intervals the same as the consonant ones you would use in writing against the CF.
Second Part,
Laitz is saying that the weak-beat note must be consonant with the CF.  This is the expected definition of consonance.  Your weak-beat note must be a third, perfect fifth, sixth, or octave away from the CF.
For the step/skip/leap business, Aaron is right that

"skips" are thirds. That is, "steps" are seconds; "skips" are thirds; and "leaps" are anything a fourth or larger.

A further misunderstanding here is that many other texts refer to movements of thirds, fourths, or even fifths within a CF note as consonant skips.  As far as I know, his use of the term consonant leap to denote a consonant skip of a fourth is unique to him.
From all of this, let's look at the examples you posted.
Measure 6 in 2.15
The CF is on A, the melody moves from C to F.  C to F is a perfect fourth, which is a perfectly normal interval to sing and doesn't break any rules.  C is consonant with the CF, as is F, so this is completely correct.  He could have used E instead for either note of the melody an it would be equally correct.  C-E would give melodic motion of a third, E-F of a second.
Your image with F as the CF note
The CF is on F, the melody moves C to E.  C to E is a major third, which is also a fine interval to sing.  No problem there.  But it forms a seventh against the CF, which is a dissonant interval.  So this won't work.  Here you have two choices.  Either move your melody C-D, a major second that forms the intervals 5-6; or move your melody C-F, sounding a perfect fourth and forming the intervals 5-8.  Of the two choices, C-D is much better because C-F are both perfect consonances.
Answer: In the blue circled measure the A and C are ambiguous or incomplete; the leap to the F is consonant if one assumes that there was an implicit F below the A and C forming F-A-C. Had there been an A-C-E (or A-E-C) vertically then the leap to a F would be a dissonance. But given only A and C that is not known until an E or F sounds; A and C could be a root position A-C-E or a first inversion A-C-F.
Comment: I would say that within the realm of species counterpoint in 2 voices, there is nothing truly ambiguous about it.  The CF is A, and its consonances above are C, E, F, and A.  The notion of a triad isn't important until there is a third voice.  Indeed ANY interval brings with it some ambiguity with two voices.


Jquery toggle input/span value not working

Question: I created a simple test script to get the value of the span text and populate the value into input:
http://jsfiddle.net/mujaji/8a923n0t/6/
<code>$('.panel-body input').val($('.panel-body span').text());

$('button').click( function(){
    $('.panel-body span, .panel-body input').toggleClass('hidden');
    $('.panel-body span').text($('.panel-body input').val());
    $(this).children('i').toggleClass('glyphicon-floppy-disk');

    if ($(this).children('span').text() == "Check Out") {
        $(this).children('span').text("Save")
    }
    else {
       $(this).children('span').text("Check Out");
    }
});
</code>
This isn't the problem. This is working fine.
...but once I implemented it into my actual environment, I'm not getting the values back. There's so obvious differences between the two, but it seems be slightly off. I'm not getting any errors so I'm guessing my syntax is off somewhere.
Here's the "real-world" version. Click "Check Out" to see it in action:
http://jsfiddle.net/mujaji/uL1c8owv/
<code>$('.patient-data.stacked li input').val($(this).next('span').text());

$('.nav-tools li a').click( function(){
var valueToggle = $(this).closest('.panel-heading').next('.panel-body').children('.tab-content').children('.tab-pane.active').find('.patient-data li');
valueToggle.children('span, input').toggleClass('hidden');
valueToggle.children('span').text(valueToggle.children('input').val());

if ($(this).children('span').text() == "Check Out"){
    $(this).children('span').text("Save");
    $(this).children('i').toggleClass('fa-pencil-square-o fa-floppy-o');
}

else {
    $(this).children('span').text("Check Out");
    $(this).children('i').toggleClass('fa-pencil-square-o fa-floppy-o');
}
</code>
});
Can anyone tell me what I'm doing wrong?
Comment: Did you remember `document.ready`, as jsFiddle adds that automagically for you !
Comment: I'm guessing I'm pointing to the wrong tag or something, but I can't see the issue
Comment: Is this what you want -> **http://jsfiddle.net/uL1c8owv/1/**
Comment: yes!! thanks adeneo! -did I only need to add function and return?
Comment: No, I added a lot more, and rewrote parts of your script !
Answer: Adeneo was able to help answer my question. Part of the problem was I did not add a return for the first part of the code: $('.panel-body input').val(). Also, there were slight adjustments made to the click event to toggle the children within the following: .patient-data li.
Here's the updated code along with a fiddle showing the fix:
<code>$('.patient-data.stacked li input').val(function() {
    return $(this).next('span').text();
});

$('.nav-tools li a').click( function(){
var valueToggle = $(this).closest('.panel-heading').next('.panel-body').children('.tab-content').children('.tab-pane.active').find('.patient-data li');
    valueToggle.children('span, input').toggleClass('hidden').text(function() {
        return $(this).siblings('input').val();
    });

    if ($(this).children('span').text() == "Check Out"){
        $(this).children('span').text("Save");
        $(this).children('i').toggleClass('fa-pencil-square-o fa-floppy-o');
    }

    else {
        $(this).children('span').text("Check Out");
        $(this).children('i').toggleClass('fa-pencil-square-o fa-floppy-o');
    }

});
</code>
http://jsfiddle.net/uL1c8owv/1/


Inverse of a symmetric using Cayley-Hamilton theorem

Question: Let $A$ be a symmetric positive definite matrix. I am interested in finding a general expression for the $A^{-1}$. Using the Cayley-Hamilton Theorem (https://en.wikipedia.org/wiki/Cayley%E2%80%93Hamilton_theorem), we have that $A^{-1}$ can be expressed as
\begin{aligned}A^{-1}={\frac {(-1)^{n-1}}{\det A}}(A^{n-1}+c_{n-1}A^{n-2}+\cdots +c_{1}I_{n}),\end{aligned}
I am bit puzzled finding the coefficients $c_i$, when $A$ is symmetric and positive definite. Also, would it be possible to avoid evaluating the $det{A}$, that is finding a expression equivalent to it?
Answer: $$\det(\lambda I-A)=\lambda^n+\beta_1\lambda^{n-1}+...+\beta_n,$$ where
$$\beta_i=(-1)^i( \text { the sum of the principal minors of A of order }i),1 \le i \le n.$$ Note that $\beta_n=(-1)^n\det(A).$The easiest way to evaluate a determinant, whether $\det(A)$or any other of the principal minors of $A$ is by pivotal condensation, which is automatic row-reduction.However, there is an alternate formula, due to Bocher, for evaluating the $\beta_i$ $$\beta_1=-\text {trace}(A),$$
$$\beta_i=\frac{-1}{i}[1,\beta_1,...,\beta_{i-1}]\bullet [\mu_i,\mu_{i-1},...,\mu_1],2 \le i \le n,$$ where $\mu_i=$trace$(A^i),1 \le i \le n.$ Note that the most efficient way to calculate such an expression as $$A^3+\beta_1 A^2+\beta_2A+\beta_3I$$ is by "synthetic division" $$A(A(A+\beta_1I)+\beta_2I)+\beta_3I$$ working outwards from the innermost parenthesis  and calculating successive powers of $A$, the $\mu_i$ and the $\beta_i$ recursively. Bocher's formula is valid over any field of characteristic 0 or of characteristic > $n.$


Android ListFragment in Tabs not showing on back button return

Question: I have a (relatively) simple drill down application.
It has one Activity (MainActivity) that contains and transitions Fragments.
public void goToPartnumbers(){
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_left);
    ft.replace(R.id.container, new IdentifierFragment()).addToBackStack("partnumber").commit();
}

IdentifierFragment is a tab layout a la http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
public class IdentifierFragment extends Fragment implements ActionBar.TabListener {
private ViewPager viewPager;
private FragmentStatePagerAdapter mAdapter;
private ActionBar actionBar;
private MainActivity mContext;
// Tab titles
private String[] tabs = { "Part Numbers", "OEM Numbers" };

public IdentifierFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.partnumber_list, container, false);
    // Initialization
    mContext = (MainActivity) getActivity();
    viewPager = (ViewPager) view.findViewById(R.id.pager);
    actionBar = mContext.getSupportActionBar();

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    resetAdapter( new IdentifierFragmentAdapter(mContext.getSupportFragmentManager()) );

    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }
    ...I can show you the rest but I don't think it's relevant

    return view;
}

@Override
public void onDetach(){
    super.onDetach();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    resetAdapter(null);
}

public void resetAdapter(FragmentStatePagerAdapter adapter){
    actionBar.removeAllTabs();
    viewPager.removeAllViews();
    mAdapter = adapter;
    viewPager.setAdapter(mAdapter);
}

...
}

The two child fragments are both ListFragments with CursorLoaders. When a row is selected, the IdentifierFragment is replaced using the following method:
public void goToGallery(){
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    galleryHandle = new GalleryFragment();
    HashMap<String,String> selection = new HashMap<String, String>();
    for (HashMap<? extends String, ? extends String> c : mCriteria){
        selection.putAll(c);
    }
    galleryHandle.setSelection(selection);
    ft.replace(R.id.container, galleryHandle).addToBackStack("gallery").commit();
}

When I move into the IdentifierFragment, it works fine. I can then select a row and go into the detail view. It's when I attempt to use the back button from the detail view that I get the ViewPager, but no ListViews!
Obviously I can supply whatever other code is needed. I just supplied what I thought was immediately relevant.
I'm at a loss, and would very much like any help. Thanks in advance!
Answer: Isn't it because you replace the current fragment.
Perhaps if you use .add() instead of .replace() when you go to a new gallery
public void goToGallery(){
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    galleryHandle = new GalleryFragment();
    HashMap<String,String> selection = new HashMap<String, String>();
    for (HashMap<? extends String, ? extends String> c : mCriteria){
        selection.putAll(c);
    }
    galleryHandle.setSelection(selection);
    ft.add(R.id.container, galleryHandle).addToBackStack("gallery").commit();
}

Comment: It's not that. If I do that, then the tabs are removed (like I had gone into the Gallery) but the listview is still front and center (it doesn't respond to actions though).


DROP vs REJECT DDoS

Question: I asked somewhere else, and I got this response:

Using DROP turns any type of DDoS attack into a SYN flood, because your server expects ACK responses which it will never get. Even if you can fine tune your tcp timeout options some of the settings are hardcoded into the kernel. A REJECT is very quick and takes tiny bandwidth. For more information Google "drop vs reject".

I researched on what he said and he seems correct, but I just want to make sure.
Comment: Whoever said that is an idiot.  Dropping SYNs doesn't create a SYN flood attack, because the dropped incoming SYN never reaches the TCP stack, and thus doesn't consume any resources.
Answer: Using DROP makes him wait for a timeout (the packet is dropped before it reaches your application). You don't send anything back.
Using REJECT you send a RST packet, saying the port is closed.
Using DROP is better for DoS protection, since you don't send anything out. Using REJECT is a "nicer", since someone connecting to you by mistake, knows the port is closed immediately, and does not have to wait for a timeout.
A syn flood is when someone sends alot of syn packets to start alot of connections (fake or not), and you reserve resources for each connection, while there are no real users to use them. Since you use up all your resources, legit users cannot use your service.
Comment: Well, it's not a 'real' synflood. But you really do only get syn packets. So using REJECT would be a SYN&RST "flood". A  real SYN floopd would be, if you reserved resources and waited for the real connection to happen.
Comment: What about his comment that using DROP turns any type of DDoS into a SYN flood?
Comment: Okay, thanks for the info. So in essence the quote in my question is wrong?
Comment: In a "normal" way.. yes. But if you put the DROP in your input chain, and dont allow established connections, and if you then connect to (let's say) 220.127.116.11, you'd send a SYN, 18.104.22.168 would respond with a SYN/ACK, which you would then DROP, causing 126.96.36.199 to wait for an ACK. But that's with you having a (very bad) DROP rule, and 'DoSing' the other guy (very poorly).
Comment: ...actually "DoSing" yourself too, since your application would wait for his SYN/ACK too :)

DROP vs REJECT DDoS


Product level authentication (AAD) for Azure API Management

Question: We are managing more 400 APIs in Azure API Management. We are also having an approval flow for approving the API subscription request, where a permission would be assigned to the API client app registration for authentication.
Problem
Since we have lots of APIs we are having as many API client app registrations and app registrations for each users subscribing the application. Also these API app registrations are available in three environments (DEV, QA and PROD). It became very difficult to manage the App Registrations. Also all these API client app registration have distinguished roles.
We would like to reduce the number of app registrations and thinking to do a product level app registrations. Also instead of app registrations for each users, we want to have single app registration for each product subscription from a team .
Here we are not sure about how to manage roles for each APIs as each API has different Roles. And an API based app registration will have all roles, how do we assign these roles to each Users.
eg: We have a product ProductA , it has 10 APIs under it. We create one APP registration ApiAppA for this product and this app registration can be used for AAD authentication. It has two App Roles Api1.Read and Api2.Write for two APIs say Api1 and Api2. Now as a subscriber, we will have another app registration say ClientAppB. We are planning use the client credential flow from ClientAppB to connect to the ProductA via ApiAppA app registration. So when a User say John want to subscribe to an API under ProductA. He only wants Api1.Read for ApiAppA. Also another user Tom wants to subscribe to another API under Product A, where he need access to Api2.Write role. How do we assign it? We are using client credential flow.
Answer: Since you are using Client Credentials flow, you can provide the client apps with application permissions exposed in the app registration for each product. You could technically have just one App Registration for all APIs as well and expose each as a separate application scope.
Every client App Registration will have to be assigned application scopes based on the APIs that they need access to.
To validate permissions, you could add checks at the product or API level policy documents in APIM to check for the required app scopes.


Data label Google spreadsheet Column chart

Question: I have created a column chart in Google spreadsheet, but it is not showing data label explicitly.

I need data value to be shown on top of each bar of column chart. Currently, that is showing only as tool tip, but I require it to be always visible.
I have not used any script just created it directly, please provide some way either by script/direct to implement data labels. only direct / apps script but no java script as I only need to view it on my spreadsheet.
here is link of sheet:   https://docs.google.com/spreadsheets/d/1a95DrTeLA52Xmycq3IUlWgfqASQWJQla7xEXx5-KWGE/edit?usp=sharing
Comment: @Mogsdad I have not used any script just created it directly, please provide some way either by script/direct to implement data labels. only direct / apps script but no java script as I only need to view it on my spreadsheet.
Comment: I've updated your question with the additional info you provided. Good luck!
Comment: Show your code. There are several ways to implement charts.
Comment: You're going to have to explain your question better, to show exactly what you mean. Pictures would help immensely. At this time, it's not clear what your problem is. (For example - have you tried right-clicking on the chart, and setting the Axis titles?)
Comment: @Mogsdad I need data value to be shown on top of each bar of column chart. Axix title is not solving it. view image as below link                                   https://www.facebook.com/photo.php?fbid=10206793982756507&set=a.2549242818734.144291.1483753528&type=1&theater
Comment: Thank you for this nice presentation
Comment: It would be helpful (for us) if you can add a sample (shared) spreadsheet with the chart. The answer can be viewed then and there.
Comment: @Vasim Please find link https://docs.google.com/spreadsheets/d/1a95DrTeLA52Xmycq3IUlWgfqASQWJQla7xEXx5-KWGE/edit?usp=sharing
Answer: You may have found the solution by now but just in case it might be helpful to others, here's my response.
Your sharing of sheet was useful in helping you with your question. Here are the steps to get the values for the data labels on the top of your columns.

Right click on the chart.
Click on Advanced Edit. (This will open a new window named "Chart Editor")
Click on "Customization" tab.
Drag the bar and keep going down until you see "Data Labels" with a drop down below it.
Click on the drop down. (This will open a list of options)
Choose "value" from this list of options.
Click "Update" and you'll see the change in your graph.

Let me know if you have any questions.
Comment: I did this, but it still wouldn't show any Data Labels. In fact, *nothing* changed.
Comment: Having this same problem. Data Labels are set to value in my Column chart, but nothing displays on the chart. Columns are showing a count of occurrences of various values in a single column.
Comment: I too have run into this and what I've noticed is that if you choose to "Aggregate column X", currently under the "Charts types" tab, then the values will disappear.  The bar chart will properly aggregate the values, reset grid lines and set the bar heights properly, but it seems to forget to pass the new aggregated values to the data labels.  Lame.
Answer: I figured out a solution. If you create a pivot table and graph that data, the values will show.
Comment: Perhaps it would be helpful to add some steps to this answer, as @Gitanjali did.


Copy FORTRAN (called via F2PY) output in Python

Question: I am using some fortran code in python via f2py. I would like to redirect the fortran output to a variable I can play with. There is this question which I found helpful.
Redirecting FORTRAN (called via F2PY) output in Python
However, I would also like to optionally have the fortran code write to the terminal as well as recording it. Is this possible?
I have the following silly class which I cobbled together from the question above and also from
http://websrv.cs.umt.edu/isis/index.php/F2py_example.
class captureTTY:
    '''
    Class to capture the terminal content. It is necessary when you want to
    grab the output from a module created using f2py.
    '''
    def __init__(self,  tmpFile = '/tmp/out.tmp.dat'):
        '''
        Set everything up
        '''
        self.tmpFile = tmpFile
        self.ttyData = []
        self.outfile = False
        self.save = False
    def start(self):
        '''
        Start grabbing TTY data.
        '''
        # open outputfile
        self.outfile = os.open(self.tmpFile, os.O_RDWR|os.O_CREAT)
        # save the current file descriptor
        self.save = os.dup(1)
        # put outfile on 1
        os.dup2(self.outfile, 1)
        return
    def stop(self):
        '''
        Stop recording TTY data
        '''
        if not self.save:
            # Probably not started
            return
        # restore the standard output file descriptor
        os.dup2(self.save, 1)
        # parse temporary file
        self.ttyData = open(self.tmpFile, ).readlines()
        # close the output file
        os.close(self.outfile)
        # delete temporary file
        os.remove(self.tmpFile)

My code currently looks something like this:
from fortranModule import fortFunction
grabber = captureTTY()
grabber.start()
fortFunction()
grabber.stop()

My idea is to have a flag called silent that I could use to check whether I allow the fortran output to be displayed or not. This would then be passed to the captureTTY when I construct it, i.e.
from fortranModule import fortFunction
silent = False
grabber = captureTTY(silent)
grabber.start()
fortFunction()
grabber.stop()

I am not really sure how to go about implementing this. The obvious thing to do is:
from fortranModule import fortFunction
silent = False
grabber = captureTTY()
grabber.start()
fortFunction()
grabber.stop()
if not silent:
    for i in grabber.ttyData:
        print i

I am not a big fan of this, as my fortran method takes a long time to run, and it would be nice to see it updated in real time and not just at the end.
Any ideas? The code will be run on Linux & Mac machines, not windows. I've had a look around the web, but haven't found the solution. If there is one, I am sure it will be painfully obvious!
Cheers,
G
Clarification:
From the comments I realise that the above isn't the clearest. What I currently have is the capability to record the output from the fortran method. However, this prevents it from printing to the screen. I can have it print to the screen, but then cannot record it. I want to have the option to do both simultaneously, i.e. record the output and have it print to the screen in real time.
Just as an aside, the fortran code is a fitting algorithm and the actual output that I am interested is the parameters for each iteration.
Comment: @user1027686 ok, just saw your clarification. Then, my naive approach would be ask the fortran to print to both stdout and a log file. While you have the flag to control where you want to print, you can set your python to retrieve records from the log file as well.
Comment: What does the fortran output look like?  Is it an array of numbers?  If so, f2py should be able to pass that directly back as a numpy array.
Comment: maybe you don't like this idea, but what I usually do is simply to ask fortran write the output to a log file with frequent flushing, then ask python or other scripts to peek into the log.
Comment: @mgilson & nye17 I have clarified the issue a bit, see above. I think I may not have been the clearest in what my issue is.
Comment: I'm not sure if this would work or not -- but you could try `tail -F` on the temporary file.  (in `start`: `self.tail=subprocess.Popen('tail -F %s'%self.tmpFile)` and then in `stop` : `self.tail.terminate()` to make sure it gets shut down...) -- However, this may direct the output to your logfile twice.  I'm not sure.
Comment: @nye17 Thanks for the idea - I just tried it there. I had to modify it slightly, self.tail = subprocess.Popen('exec tail -f %s'%self.tmpFile,  shell = 'bash'). Without the exec it would fork the tail process and it would not be killed by the terminate() call. It doesn't work though: it doesn't print to the screen and confusingly adds mainly duplicate lines to the log file. Thanks for the idea!
Comment: @mgilson Opps! The above comment was meant for you. Can't edit it now.
Comment: @user1027686 It seems weird that the tail process wouldn't be killed by terminate.  It's not terribly weird that the output gets sent to the log twice -- apparently the child inherits the terminal descriptors of it's parent.  Out of curiosity, what happens if you send the output of tail to stderr instead of stdout? (`self.tail = subprocess.Popen('exec tail -f %s 1>&2'%self.tmpFile, shell = 'bash')`)
Answer: Have you tried something like this in the Fortran subroutine?  (Assuming foo is what you want to print, and 52 is the unit number of your log file)
write(52,*) foo
write(*,*) foo

This should print foo to the log file and to the screen.


I need to have a licence facility on my web site

Question: Hi I have a web site on my server that is used to plan events, authorised users log in and use the site.  I am in the process of selling the facility to a client 'on licence' But he wants the code/script on his server. Can anyone suggest a suitable way to go about protecting my code even if it is running on somebody else's server ? any pointers to articles etc would be much appreciated ..
thanks
Comment: possible duplicate of [Encrypt php code](http://stackoverflow.com/questions/764927/encrypt-php-code)
Answer: Zend has some 'encryption' software for PHP: Zend Encoder, IIRC.
Now called Zend Guard apparently. There's a tutorial on their website. Alternatively try IonCube.
A quick google said there were lots of alternatives ("php encoder" will bring them up), things have changed since I last looked! there must be quite a market for PHP encoding.


Octahedron Pyramid

Question:
So, each octahedron can be inscribed in a cube, so that
the corner points of the octahedron are in the midpoints of the side areas of the cube, am I right?
From the octahedron $ABCDS_1S_2$, shown in the image, the vertices
$A =(13 | -5 | 3)$
, $B =(11 | 3 | 1)$
, $C =(5 | 3 | 7)$
and
$S_1 =(13 | 1 | 9)$
are  given.
This octahedron is inscribed in the illustrated cube with the corners $P_1$ to $P_8$.
Now let
$E_0: 2x_1 + x_2 + 2x_3 + 9 * (2a-5) = 0, a ∈ ℝ$
be a set of planes $aEa$; Let $h$ be the line passing through the points $S_1$ and
$S_2 =(5 | -3 | 1).$

Now the task:
For $0 <a ≤ 1$, the plane $E_a$ intersects a pyramid of the octahedron
with the peak $S_1$:

I have to find the point of intersection $P_a$ of the plane $E_a$ with the line $h$ and then the volume $V_a$ of the truncated pyramid.

This is what I've done:
I have determined
$P_a=(13-4a|1-2a|9-4a)$
but how can I find the volume?
If anyone needs the math for determining $P_a$, please say so and I'll add my calculations.
Thx
Answer: For heaven's sake write points data as $A=(13,-5,9)$, and so on!$\quad$ [Note that $A=(13,-5,9)$ is a proposition, while $A(13,-5,9)$ is a function value.]
One finds that the center of the octahedron $O$ is at $M=(9,-1,5)$, so that $\vec{MS_1}=(4,2,4)$, which is orthogonal to the planes $2x_1+x_2+2x_3={\rm const.}$ It follows that all these planes intersect the axis $S_1\vee S_2$ of the octahedron orthogonally.
You have obtained $P_a=(13-4a,1-2a,9-4a)$ [I have not checked this], so that
$P_0=S_1$ and $P_1=M$. This allows to conclude that for $0< a<1$ the plane $E_a$ cuts off a small square pyramid $Y_a$ from $O$ with apex at $S_1$. The volume of this pyramid can be computed using elementary geometry. Note that the edge length $s$ of $O$ satisfies $s^2=|AB|^2=72$, and the height of the "upper half" $Y_1$ of $O$ is given by $h=|MS_1|=6$. It follows that ${\rm vol}(Y_1)={1\over3}s^2 h=144$. Since each $Y_a$ is similar to $Y_1$ with a linear factor $a$ we finally obtain
$${\rm vol}(Y_a)=144a^3\ .$$

Octahedron Pyramid


Does On Value Change based on framerate?

Question: If I use an event OnValueChanged for an UI element, for example a slider. Is it better (for performance) to listen the slider values change in an Update() or does the event is already based on the same framerate than Update()?
Comment: If there is an event, I guess it's better to use the event
Comment: The event is OnSliderValueChanged. I guess so, but I would like to be sure, I can't find this information in the manual
Comment: I don't know, but maybe you can print in the console with the two method and see which one respond first ? (or if one has more calls than the other
Comment: good idea! I'll try that
Comment: You can check Unity Documentation here [Slider.OnValueChanged](https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.Slider-onValueChanged.html)
Comment: It is not writed at which frequency is called the event
Answer: From the performance point of view, it is better for you to use the event rather than checking the value of the slider everything. Because in Update() your script is requesting the value of the slider and also checking the value of the slider because you want to check whether the value of the slider is changed or not, and an event will only be triggered when the value of the slider is changed.
And by a change in value I mean if you change the value of the slider either from a script or from the user sliding the sliding_head of the slider.
And this is true for all other Unity's UI elements that have OnValueChange() event for us to subscribe to.
I hope that this helps you sort out your confusion.
Comment: @Splinter It is called with the frequency in which a new value is assigned to the slider ...
Comment: Thank you for this info! and about the framerate, does OnValueChange() called at the same frequency that the framerate of Update() or at the frequency of the internal clock (processor) ?


event.preventdefault not working in Firefox

Question: I am using the below bit of jQuery to toggle hidden divs. Working in all but Firefox and I know the error is (ReferenceError: event is not defined) but I'm not sure where to define the event so if anyone is able to help that would be great. Thanks in advance!
Each button is written as:

VIEW TYRES

jQuery:
function toggle_visibility (id,el) {
    $('.btn_view a').html('VIEW PRODUCTS');
    event.preventDefault();
    $('.price-text').show();
    $('.model-price-sm').show();
    var e = document.getElementById(id);
    if (e.style.display == 'block')
    {
        e.style.display = 'none';
        $(el).html('VIEW ALL');
    }
    else
    {
        e.style.display = 'block';
        $(el).html('HIDE PRODUCTS');
        $(el).parent().parent().find('.price-text').hide();
        $(el).parent().parent().find('.model-price-sm').hide();
        //$(el).parent().prev('.price-text').hide();
    }

    hideAllBut(id);
}

function hideAllBut(id) {
    var lists = document.querySelectorAll('.reveal');
    for (var i = lists.length; i--; ) {
        if (lists[i].id != id) {
            lists[i].style.display = 'none';
        }
    }
}

Answer: In FireFox, you can pass the event object in as a parameter e.g.:

VIEW TYRES

function toggle_visibility (id,el, e) (then use e.preventDefault, just to make it separate to window.event in IE etc)
Although, as you are using jQuery, I would suggest doing what Sergio mentioned above/below.
Comment: http://stackoverflow.com/questions/16404327/how-to-pass-event-as-argument-to-an-inline-event-handler-in-javascript
Answer: Instead of using "event.preventDefault()" you could use "return false". It probably will solve your problem in Firefox.
Cheers
Answer: You have a typo:
.html('VIEW PRODUCTS');
                    ^

and also same typo here .html('HIDE PRODUCTS');
Apart from that its better to avoid inline script, so you could use:
$('.btn_view a').click(function(event){
    event.preventDefault();
    toggle_visibility (id,el)
});

Comment: Thanks for the quick reply. I need each button to open a different hidden div so not sure this works?
Comment: @fsylothian can you post your whole html?
Comment: @fsylothian, you can always add a data attribute to the anchors. Such as data-target-id="targetId".   Then in the click function above you would do toggle_visibility($(this).attr('data-target-id'), this);


How to add an entry to registry Run key via VS2008 setup and deployment

Question: I'm creating a VS2008 installer script for my project.
I want to add a value to HKCU\Software\Microsoft\Windows\CurrentVersion\Run to run my EXE at start up.
Is there a way I can specify a reference to my executable ("Primary output from Project"), so that the installer script inserts the correct value into the registry when it runs?
I don't want to have to hard code the path and name for the executable in the registry value.
Answer: To reference the executable, enter this string in the registry entry's value:
[TARGETDIR]YourProgram.exe
Answer: Windows Installer is a declarative programming language, not an imperative scripting language.  [#FileKey] will also do the trick. I suggest reading the following two MSDN topics.
Registry Table
http://msdn.microsoft.com/en-us/library/aa371168(VS.85).aspx
The registry table joins registry resources to their components.
Formatted
http://msdn.microsoft.com/en-us/library/aa368609(v=VS.85).aspx


Is there any performance issues in using Omega theme with Context, Delta and Panels modules?

Question: Is there any performance issues in using Omega theme with Context/Delta modules and Panels module too? (I mean the context standalone menu, not the one inside panels)
Is there any known issue? I´ve read about some issues with Omega and panels in the past, but now they work just fine.
And I need context for my homepage, to create a slighty different layout than the rest of the site.
Comment: Panels can override the home page; this is a built-in feature.  If you only need Context for the home page I would check if there is a way to do it in Panels.
Comment: Thanks for your reply! Yeah, I´m trying that, because having the other two modules just for the homepage kinda sucks :)
Answer: it depends on your site and server configuration. if you get alot of anonymous traffic that doesnt require users to login, you should be fine as the cache would handle alot of that load. Also be sure to turn on js / css aggregation. I've built many sites with those modules combined and they run fine. But if your all about performance, you can just do everything by hand and write your own templates/css and not use the bloated ones they have, but you'll be spending alot of time. in that effect you'll have total control over what gets outputted to the user.


C pthread mutex

Question: I've got a simple program that echoes out the character that was entered by the user. Two threads are created to run this echo function and I'm using pthread mutex to lock the critical code to one process at a time so that the character is properly printed out:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

char characterIn, characterOut;

void* echoCharacter()
{
    pthread_mutex_lock(&mutex);
    /* crital code start */
    characterIn = getchar();
    characterOut = characterIn;
    putchar(characterOut);
    /* crital code end */
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main()
{
    //spawn
    pthread_t id;
    pthread_t id1;
    pthread_create(&id, NULL, echoCharacter, NULL);
    pthread_create(&id1, NULL, echoCharacter, NULL);
    //wait
    pthread_join(id, NULL);
    pthread_join(id1, NULL);

    return 0;
}

However I'm not getting the correct output. It only echoes out the first character entered by the first thread, but the program stops after that and doesn't ask to enter another character:
>>a
>>a
>>

expected output:
>>a
>>a
>>b
>>b

Answer: If you're entering a on a line (followed by the ENTER key), that actually is two characters, the a and the \n.
If you enter ab with no intervening ENTER, you should see ab echoed back (once you hit ENTER afterwards, since your console is most likely in cooked mode).
A quick confirmation can be had by simply placing an extra getchar() to "swallow" the newline:
characterIn = getchar();
getchar();
characterOut = characterIn;

This is for debugging purposes, it's not really a viable solution. A viable solution would be to use line-based input, such as detailed here.
Comment: Oh wow I totally forgot about that. I thought it was an entirely different issue. Feel dumb now that it was that simple

C pthread mutex


LocationListener does not get killed

Question: I have a foreground service which implements LocationListener. When the Service is killed, it keeps on getting a fix. However this is what I call in the onDestroy()
@Override
public void onDestroy() {
    Log.e(getPackageName(), "Destroying GPSservice");
    super.onDestroy();
    running = false;
    stopForeground(true);
    locationManager.removeUpdates(EventService.this);
    locationManager = null;
}

Is there something I'm missing?
EDIT
More code. This is in the onCreate():
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            3000L, 15.0f, this);

Comment: add more info, how your locationListener is implemented?
Comment: I really don't want to sound snobby but: it's implemented like it should be. The GPS itself is working A-OK, but when the Service gets killed, I want the locationManager to remove the updates the Service has. Instead, it keeps on getting a fix. Otherwise, I have to copy past a LOT of code here..
Comment: post some more code to show how your location listener is implemented
Comment: Do you know if your `onDestroy()` method is being called? Do you have clients bound to your service?
Comment: I have a similar problem. In my case the issue has to do with the Activity lifecycle (http://developer.android.com/guide/components/activities.html#Lifecycle). Note how the activity can be killed without calling onDestroy, preventing the location listener from being registered.
Comment: Sorry, s/b "deregistered". Missed the 5 minute edit window.
Answer: use
locationManager.removeUpdates(Your_Location_Listener_instance);

instead of
locationManager.removeUpdates(EventService.this);

for more infromation see doc public void removeUpdates (LocationListener listener)
Comment: I have stated above that my LocationListener is implemented by the EventService. So that's my instance I think.
Answer: I have solved the problem. It turns out, the MyLocationOverlay binds to the LocationSensorThread too, and I was never turning that off. So that was keeping the GPS awake.

LocationListener does not get killed


IPv6 address as hostname

Question: With IPv4 I don't have to buy a domain name to make my website available to everyone. I can just give people my IP address, they type it into their browser and there it is.
Is that supposed to work at all with IPv6? When I try going to my IPv6 address all browsers just make a google search with no results.
Comment: You don't have to buy a domain for every server.  You can buy one domain and use it for millions of servers.
Answer: Yeah that is supported. Just use http://[IPv6-Address]. The [] must be included.

IPv6 address as hostname


JSON HttpServletRequest/HttpServletResponse

Question: I'm very new to the Java world and am having some trouble figuring out how to store the credential JSON string (see below) in a variable and then converting it to a JSON object that can then be displayed in the #welcometext div.
I looked through a lot of responses already and nothing has been working. If anyone could provide me with some help I would greatly appreciate it!
ActionServlet.java doPost:
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    String body = request.getReader().lines().reduce("", (acc, actual) -> acc + actual);
    String body = request.getParameter("data");
    System.out.println("Body is: " + body);

    JsonReader jsonReader = Json.createReader(new StringReader(body));
    JsonObject obj = jsonReader.readObject();
    System.out.println("obj is: " + obj);
    jsonReader.close();

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

  }
}

index.html:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Demo</title>

  <form id="form1">

AJAX Demo using Jquery and Servlets

    Enter your Info:

     <input name ="name" type="text" id="user" placeholder="name" />

     <input name="age" type="text" id="age" placeholder="age"/>

     <input type="button" id="submit" value="Ajax Submit"/>

  </form>

Answer: You call request.getParameter("data") which gets the value of a query string in the URL. However, your javascript does not appear to send a request to the server with a query string at all. It looks to me like the javascript sends a POST request with a body of {"credentials": {...}}. Use request.getInputStream() to read the body of the request.


CSS grid inside a grid

Question: I am using a 960 Grid System, I am trying to achieve something like the following  --
|-----| |-------------------|
|     | |  |--|  |-----|    |
|     | |  |  |  |     |    |
|     | |  |--|  |-----|    |
|     | |                   |
|     | |  |------|  |--|   |
|     | |  |      |  |  |   |
|     | |  |------|  |--|   |
|-----| |-------------------|

Is there a way of doing so? The only reason I need the second set of divs in my right column is because the left column is quite long and I dont want the space between the 2nd set of columns.
I would really appreciate any guidance if there is a better way of achieving this.
Answer: This capability is built into the Grid 960 system.  You just give the left and right nested grid items the classes "alpha" and "omega", respectively.
Here's an example:

Comment: Thanks Chris, -- That will help me get the first row of 2 divs in the 9 column grid. However the 2nd Row of divs still wouldn't get styled.
Comment: Just add the appropriate grid classes to the second row divs as well. My updated code would give you two rows of nested divs.
Answer: In case you're willing to consider other frameworks, here's how you achieve the desired result with Cascade Framework :

A grid element in Cascade framework is either

One of the following HTML elements : section, main, article, header, footer, aside or nav (these elements are polyfilled with the HTMLshiv for old IE in case you need it).
A div element with a 'col' class (can be used in old IE without a polyfill).

To add a width to a grid element, you add a class of the format 'width-XofY', where Y can be 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16 or 24 and X can be any value lower than X.
More concretely, here are some examples of valid classes you can use in Cascade Framework : 'width-1of2' (width : 50%), 'width-3of4' (width : 25%), 'width-2of5' (width : 40%), 'width-2of5' (width : 40%), 'width-2of7' (width:28.5714286%) and 'width-13of16' (width:81.25%)
Additional to these classes, you can also use the classes 'width-fit' and 'width-fill' that respectively fit to content and fill whatever remains of your 100% width. Or, you could just define your own classes and IDs and just add a custom width for those classes to do things the 'semantic' way.
If your builds include the responsiveness module (which is the case for the recommended builds), the width of all grid elements automatic resets to 100% on mobile. You can use classes like 'mobile-width-3of16', 'phone-width-3of7' or 'tablet-width-2of4' to customize the layout for different width ranges and the classes 'desktop-hidden', 'mobile-hidden', 'phone-hidden' or 'tablet-hidden' to hide content for a specific screen with range.

CSS grid inside a grid


Mock: when() requires an argument which has to be 'a method call on a mock'

Question: I am writing the unit tests for my REST-API and have some problems with the entities creation mocking. I don't know how can I mock the EntityManager. I tried the example below but I got an error.
My ControllerTest:
public class MControllerTest {

    private MockMvc mockMvc;

    @InjectMocks A a;
    @InjectMocks B b;
    @InjectMocks AController aController;
    @InjectMocks private AServiceImpl aServiceImpl;

    @Autowired WebApplicationContext webApplicationContext;
    @Autowired private FilterChainProxy springSecurityFilterChain;

    @Autowired
    @InjectMocks
    private EntityManagerFactory entityManagerFactory;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                                 .addFilter(springSecurityFilterChain)
                                 .build();
    }

    @Test
    public void postATest() throws Exception {

        a.setDDDD("XXX");

        EntityManagerFactory entityManagerFactory = webApplicationContext.getBean(EntityManagerFactory.class);
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        when(this.entityManagerFactory.createEntityManager()).thenReturn(entityManager);

        when(aServiceImpl.createEntity(isA(A.class))).thenReturn(a);

        b.setCCCC;
        a.setMovieTranslations(Arrays.asList(b));

        when(aServiceImpl.createEntity(isA(B.class))).thenReturn(a);

        mockMvc.perform(post("/path")
               .andExpect(status().isOk())
               .andReturn().getResponse().getContentAsString();
    }

The createEntityMethod:
public Object createEntity(T t) {
    try {
        entityManager.persist(t);
        return t;
    } catch (IllegalArgumentException | EntityExistsException | ...
}

The error log:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

    at com.x.server.controller.MControllerTest.postATest(MControllerTest.java:121)

When I don't inject a mock object on the EntityManager, I got a nullpointer exception by the persist method with this error log:
java.lang.NullPointerException: null
    at com.x.server.serviceImpl.AManageServiceImpl.createEntity(AManageServiceImpl.java:45)
    at com.eza.server.controller.MControllerTest.postATest(MControllerTest.java:123)

Can someone help me?
Comment: I wonder why you mix Spring an Mockito like that. Either you need these "real" beans, then you're creating an integratoin test and you most likely don't need mockito. Or you're creating a unit test where every dependent bean is mocked.
Comment: you are right. Thanks. You comment solve my problem. It is working now. I only use mockito right now.
Comment: Glad to hear. Please write an answer with your now working code and what you've changed, so future readers can learn from it :).
Answer: Solve it. I just removed some line of code with the entitymanager interface and it works.
public class MControllerTest {

    private MockMvc mockMvc;

    @InjectMocks A a;
    @InjectMocks B b;
    @InjectMocks AController aController;

    @Autowired WebApplicationContext webApplicationContext;
    @Autowired private FilterChainProxy springSecurityFilterChain;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                                 .addFilter(springSecurityFilterChain)
                                 .build();
    }

    @Test
    public void postMovieTest() throws Exception {

        a.setDDDD("XXX");
        b.setCCCC;
        a.setMList(Arrays.asList(b));

        mockMvc.perform(post("/path")
            .content(asJsonString(a))
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .andExpect(status().isOk())
            .andReturn().getResponse().getContentAsString();
    }

asJsonString is by me self write method to convert object in json
Cheers
Comment: not able to understand, what you changed. can you please explain a bit more.


Como inserir legenda em mapas do ggplot?

Question: Como faço para inserir a legenda e para mudar a escala do mapa para graus?
library("rgeos")
library("maptools")
library("ggplot2")
library("mapproj")

cores1 = c('brown2', 'aquamarine2', 'darkgray','darkolivegreen1', 'floralwhite')

ggplot() + geom_polygon(data=mapa, mapping=aes(x=long, y=lat, group=group),
                        color="black", fill=cores1[mapa$tb]) +
           coord_map() +
           labs(y="latitude", x="longitude") +
           theme(plot.title=element_text(hjust = 5))

Answer: O ggplot não está incluindo a legenda porque você está atribuindo cores como atributo e não como mapping. |Definir atributos não inclui novas informações no gráfico (mapa), apenas muda aspectos visuais. Por este motivo não precisam de legenda.
Já mapear uma variável em algum aspecto estético (dentro do aes(...) é adicionar informações ao gráfico (mapa), para esta informação poder ser decodificada, ela necessita de legenda.
Ao simplesmente incluir o fill = tb dentro do aes(...), o próprio ggplot já cria a legenda.
Recriando os dados
utilizei este objeto mapa para construir como mapas abaixo:
mapa <- map_data("state")
mapa$tb <- factor(sample(1:5, size = nrow(mapa), replace = TRUE))

Plotando os mapas
Ao simplesmente remover o fill=cores1[mapa$tb] e incluir fill = tb dentro do aes()
ggplot() +
  geom_polygon(data=mapa, mapping=aes(x=long, y=lat, group=group, fill = tb),
               color="black") +
  coord_map() +
  labs(y="latitude", x="longitude") +
  theme(plot.title=element_text(hjust = 5))

Mas nesta solução perdemos as cores que você desejava. Para reinclui-las com a metodologia proposta, temos que adicionar uma escala manual de cores com a função scale_fill_manual(). O argumento que será passado para esta função é justamente o vetor com as cores que você escolheu. O argumento valuesdeve ser explícito. Assim temos:
ggplot() +
  geom_polygon(data=mapa, mapping=aes(x=long, y=lat, group=group, fill = tb),
               color="black") +
  coord_map() +
  labs(y="latitude", x="longitude") +
  theme(plot.title=element_text(hjust = 5)) +
  scale_fill_manual(values = cores1)

Comment: Já havia resolvido, mas de toda forma agradeço a explicação.


Erro ao pegar imagem do perfil do facebook

Question: Pessoal estou tentando pegar a imagem do perfil do fb mas retorna o seguinte erro
java.io.FileNotFoundException: No content provider: https://graph.facebook.com/--Aqui--esta--o--id--/picture?width=150&height=150
Meu código esta assim
  Bitmap tempBitmap;
        tempBitmap = Util.getBitmapFromURL(Preference.getUserPhoto(getApplicationContext()));
        Drawable drawable = new BitmapDrawable(getResources(), tempBitmap);
        System.out.println("TempBitMap "+ tempBitmap );
        System.out.println("drawable "+ drawable );
        aux.setIcon(drawable);

Classe preference metodo getUserPhoto
 public static String getUserPhoto(Context c){
    SharedPreferences prefs = c.getSharedPreferences("myPref", 0);
    return prefs.getString("url", "url");
}

Minha url eh essa
url: https://graph.facebook.com/IDESTAACQUI/picture?width=150&height=150
Medoto para pegar a photo
 public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.connect();

        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);

        return myBitmap;
    } catch (Exception e) {
        // Log exception
        return null;
    }
}

Resultado do bitMap e do drawable
TempBitMap null
 drawable android.graphics.drawable.BitmapDrawable@22b0eb58
Comment: A foto do perfil que você está tentando obter é privada? (Privacidade da foto está somente eu ou somente amigos que podem visualizar)?
Comment: Não esta como privada, o estranho é que quando eu jogo o link no browser aparece a foto mas no meu codigo quando vou tentar converter para bitmap ele da esse erro
Answer: Não é recomendado usar o ContentResolver para obter conteúdo da internet, a forma correta seria utilizar um URLConnection ou usando uma bibliotecas de carregamento de imagens, porque elas eliminam código boilerplate e tem toda expertise para tratar de cache e redimensionamento de imagem.
Observando o comportamento da url do facebook, ele realiza um redirect para a url real que está atrás de um provável CDN. Para isso, é preciso tratar o redirecionamento manualmente.
Usando o URLConnection:
public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.connect();

        conn.setInstanceFollowRedirects(true);  //you still need to handle redirect manully.
        HttpURLConnection.setFollowRedirects(true);

        // normally, 3xx is redirect
        int status = conn.getResponseCode();
        boolean redirect = false;

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP
                || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            return getBitmapFromUrl(conn.getHeaderField("Location"));
        }

        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);

        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}

Fonte: http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/
Caso use uma biblioteca third-party, é bem mais simples:
Usando Glide:
Glide.with(context)
     .load(url)
     .into(imageView);

// ou
Glide
    .with(context)
    .load(url)
    .asBitmap()
    .into(new SimpleTarget<Bitmap>(100,100) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
            // Bitmap disponível
        }
    });

Usando Picasso
Picasso
    .with(context)
    .load(url)
    .into(imageView);

// ou

private Target target = new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        // Usar o bitmap
    }

    @Override
    public void onBitmapFailed() {
        // Erro
    }
}

Picasso
    .with(context)
    .load(url)
    .into(target);

É claro que cada uma delas tem uma forma de configurar cache.
Mas é bom avaliar antes se vale a pena incorporar essas bibliotecas em seu projeto. Se for para um uso pontual, o overhead que ela trás pro tamanho do APK pode não compensar... Ai é bom verificar caso a caso.
Comment: Wakim vlw pela ajuda, usei seu primeiro exemplo HttpURLConnection para não precisar usar libs mas esta retornando null para meu tempBitMap.
Comment: Show, está dando algum erro na requisição que gerou alguma Exception? Pode verificar se teve algum erro no console?
Comment: Vou atualizar minha pergunta com o código que estou usando agora, mas não deu nenhum erro no console porém retorna null
Comment: A url esta descaracterizada? Ao abrir a imagem pelo Browser deu um erro.
Comment: Então essa url que postei eu tirei o id mas se passar o id ela abre a imagem normal no browser
Comment: @roque, pelo que eu entendi, está havendo alguns redirecionamentos ao acessar a url. Para isso tem que tratar isso manualmente. vou atualizar a minha resposta em breve.
Comment: Blz, se for ajudar essa é a url completa  https://graph.facebook.com/806488489468071/picture?width=150&height=150
Comment: Tentei tratar esse redirecionamento mas nao deu muito certo, parece que tem uma criptografia


How do you modify modules/templates without waiting for the cache?

Question: I'm a beginner at both php and drupal, I know some PHP, at least enough to modify templates and add/remove content from modules, but what irks me is that I always have to wait around 60 seconds for the changes to be visible.
Now I've heard about using the Admin Menu to flush all caches, I've tried every single module that claims to flush the cache, but I still have to wait 60 seconds for the changes to appear
I've also tried disabling the cache by modifying settings.php, to no avail.
As I've said, I'm a beginner at both php and drupal, is this a browser-side cache? or am I missing something?
Comment: Probably it is related to the server settings.
Answer: This most likely is a server-side-cache related issue. I have also experienced this with my hosting. Try contacting your hosting provider about this issue or try to find a setting to turn off the server cache in your hosting's admin panel.
Comment: I'm using the Bitnami Drupal stack


What is the syntax for the 'Query string value' in a view argument input?

Question: down vote favorite
share [g+] share [fb] share [tw]
In Views (3.3) you have the possibility to provide an argument input once you set up a relationship and a contextual filter. One option is to get this argument from the Query string value.
I tried it with visiting a link like this:
....url_to_view_page?argument=foo

and also
....url_to_view_page?foo

and even
....url_to_view_page?q=foo

But it doesn't seem to work. What is the correct syntax for this in the URL?
Comment: I have never heard about this before. I can't find any choice for query string in the arguments section.
Comment: It really exists; if you select 'From context' (at the argument input window) and look under 'Token replacements' you should see 'Current page: Query string value'.
Comment: I've got Views 3.3 and am not seeing this option - screenshot might help here?
Answer: Syntax depends on your view display path, e.g. for page displays.
For example, if your page display path is url_to_view_page/% then the syntax is:
url_to_view_page/foo.
If you do not have a path, then you'll always fall back on the contextual filter not provided behavior, this is always the case for blocks.
Answer: when Clean Url is enable all Urls converted to foo/bar/... structure,The views contextual filter address is  pageurl\arg1\arg2\.... So if you view page url is url_to_view_page\% then the Url can be like url_to_view_page\foot.
( also you can use ?q=url_to_view_page/foo)