Play: JSON Writes is not respected when class extends case class

Question: I have the following hierarchy of classes
case class A(id: String,name:String)
object A {
   implicit val reads:Reads[A] = Json.reads[A]
   implicit val writes:Writes[A] = Json.writes[A]
}

class B(id:String,name:String, val other:Int,val another:Vector[String]) extends A(id,name)
object B {
   implicit val reads:Reads[B] = Json.reads[B]
   implicit val writes:Writes[B] = Json.writes[B]

   def apply(id: String,name:String, other:Int, another:Vector[String]) = new B(id,name,other,another)
   def unapply(b: B):Option[(String,String)] = Some {(b.id,b.name,b.other,b.another)}

}

the result when serialising B only includes the state of its parent class A and is the following:
{
  id:"some value",
  name: "some other value"
}

what should be the configuration of the Reads and Writes in order for the ones in the subclass to be respected and all the included key value pairs to be appropriately serialised. The result I expect is the following:
{
  id:"some value",
  name: "some other value",
  other: 4,
  another: ["a","b"]
}

I want no fancy custom serialisation of the key value pairs. I would only include the reads and writes in the subclass B if only the compiler did not complain that the parent class is missing read and write implicits.
Comment: It is generally discou aged to extend case classes due to some odd behavior resulting from it. Try using a trait or abstract class for your base class.
Comment: Your code doesn't compile for me, since `Json.reads[B]`already complains about not having an apply method.
also if you only call `Json.toJson(new B(...))` the implicit resolution would be ambiguous.
Sorry, I just might not understand how you want your code to look like in the end.
Comment: I cannot use a trait since I need arguments. If i use an abstract class I would need to create an apply and unapply method based on Play's convention. In order to create an apply method I would need some kind of constructor. What kind of constructor am I supposed to use in an abstract class? It is abstract.
Comment: From Play's docs:
The macros work for classes and traits meeting the following requirements.

* It must have a companion object having apply and unapply methods.
* The return types of the unapply must match the argument types of the apply method.
* The parameter names of the apply method must be the same as the property names desired in the JSON.
Comment: You're right. While trying to adjust the original code I removed the apply and unapply methods.
Comment: I can't reproduce your result where it only produces a json with A's values. And I can only serialize a B with explicitly passing the Reads[B] to Json.toJson. It might be a little bit more boilerplate but having serperate case classes might be the easiest. Also A doesn't need apply/unapply since case classes already implement that.
Comment: The thing is that this is just a part of a nested structure thus I can't just pass  this to `Json.toJson` . I have to pass the entire structure which is formed from the companion objects of Bs. Could you please submit the code that works for you?
Comment: I only used your code and a Json.toJson(new B(...)) to test it. All of it would be avoided if you don't use inheritance.
Answer: Just use this library like this
sealed trait A

object A {
  implicit val oformat: OFormat[A] = julienrf.json.derived.oformat(adapter = NameAdapter.snakeCase)
}

case class B(x: String, y: String) extends A {}

and everything works smoothly... To be honest Play's approach on working with JSONs is still quite primitive - compared to Spring for example.


Question on definite integral

Question: How to compute the following:
$$ \int_{0}^{\infty} \frac{\tan^{-1}(ax)}{x(1+x^2)}dx $$
If you could, please, solve it completely, for, I am afraid, a hint won't do for me.
Answer: Set $$\vartheta(a)=\int_{0}^{\infty} \frac{\tan^{-1}(ax)}{x(1+x^2)}dx$$
Differentiate and use partial fractions to integrate.
Spoiler

 $$\vartheta '(a) = \int_0^\infty  {\frac{1}{{1 + {a^2}{x^2}}}\frac{1}{{1 + {x^2}}}} dx$$

and

 $$\frac{1}{{1 + {a^2}{x^2}}}\frac{1}{{1 + {x^2}}} = \frac{1}{{1 - {a^2}}}\left( {\frac{1}{{1 + {x^2}}} - \frac{{{a^2}}}{{1 + {a^2}{x^2}}}} \right)$$

Then use that

 $$\int_0^\infty  {\frac{{dx}}{{1 + {x^2}}}} = \frac{\pi}2$$

to obtain

 $$\vartheta '(a) = \frac{1}{{1 - {a^2}}}\left( {\frac{\pi }{2} - a\frac{\pi }{2}} \right) = \frac{{1 - a}}{{1 - {a^2}}}\frac{\pi }{2} = \frac{\pi }{2}\frac{1}{{1 + a}}$$

And I guess you can take it from there.
ADD Note I missed a detail on the integral $$\int_0^\infty  {\frac{{{a^2}}}{{1 + {a^2}{x^2}}}dx} $$ If $a>0$, we have that $$a\int_0^\infty  {\frac{1}{{1 + {{\left( {ax} \right)}^2}}}d\left( {ax} \right)}  = a\int_0^\infty  {\frac{1}{{1 + {t^2}}}dt}  = \frac{{\pi a}}{2}$$ but if $a<0$ $$a\int_0^\infty  {\frac{1}{{1 + {{\left( {ax} \right)}^2}}}d\left( {ax} \right)}  = a\int_0^{ - \infty } {\frac{1}{{1 + {t^2}}}dt}  =  - \frac{{\pi a}}{2}$$ Thus in any case $$\vartheta'(a)=\frac{1}{{1 - {{\left| a \right|}^2}}}\left( {\frac{\pi }{2} - \left| a \right|\frac{\pi }{2}} \right) = \frac{\pi }{2}\frac{1}{{1 + \left| a \right|}}$$
Comment: This works for $a>0$. I would add that since $I(a)$ is odd as a function of $a$, we can extend it easily to negative values of $a$.
Comment: @Jean-Sébastien Why would it not work for $a<0$?
Comment: take for example $a=-2$, you'd get $0$ with $I(a)=\pi/2\ln(|a+1|)$
Comment: @Jean-Sébastien I have found my mistake-.
Comment: Works perfectly that way as well +1
Answer: Let $\displaystyle I(a) = \int_{0}^{\infty}\frac{\tan^{-1}(ax)}{x.(1+x^2)}dx$
Now Diff. both side w.r.to $a$ , We Get
$\displaystyle \frac{dI(a)}{da} = \int_{0}^{\infty}\frac{1}{(1+a^2x^2).x.(1+x^2)}.x.dx$
$\displaystyle \frac{dI(a)}{da} = \int_{0}^{\infty}\frac{1}{(1+x^2).(1+a^2x^2)}dx$
$\displaystyle \frac{dI(a)}{da} = \frac{1}{(a^2-1)}\int_{0}^{\infty}\left(\frac{a^2}{1+a^2x^2}-\frac{1}{1+x^2}\right)dx$
$\displaystyle \frac{dI(a)}{da}= \frac{a}{(a^2-1)}.\frac{\pi}{2}-\frac{1}{(a^2-1)}.\frac{\pi}{2}$
$\displaystyle \frac{dI(a)}{da} = \frac{\pi}{2}.\frac{1}{a+1}$
Now $\displaystyle \int \frac{dI(a)}{da}da = \frac{\pi}{2}\int\frac{1}{a+1}da$
$\displaystyle I(a) =\frac{\pi}{2}.\ln |a+1|+C$
Comment: Peter, to be fair, juan posted this only 8 minutes after you posted yours.  It looks like it took a lot longer than 8 minutes to put this together, so I would give him the benefit of the doubt.
Comment: Did you see my answer?
Comment: Use $I(0)=0$ to clear that $C$
Comment: No Peter Tamaroff I have not see yours answer, when I post my answer after then i have seen it. If i have seen yours answer that i will not post it,Thanks Jean-Sébastien I missed it.
Comment: No problem! ;) ${}{}$
Comment: @RonGordon Sorry if I came out as accusing. That wasn't the intention.
Comment: Hey man, it's all good.
Comment: This works for $a>0$. I would add that since I(a) is odd as a function of a, we can extend it easily to negative values of $a$.

Question on definite integral


Should I transform my count response variable to continuous response variable for mixed models (glmms)?

Question: I conducted an experiment where I counted the number of infected leaves per plant. There were four replicate plants per treatment (total two treatments). So my response variable is positive count data, ranging from 0-392. I'm going to use generalized linear mixed models to see the effect of weather variables and mulching status on disease development (number of infected leaves). My question are,

Should my response variable be number of infected leaves PER PLANT or on FOUR PLANTS (there were four plants per treatment)?

Should my response variable be count data or continuous? That is, should I use number of infected leaves per plant/per treatment (count data), or should I take an average of number of infected leaves per plant/per treatment (question 1), and thus use a continuous response variable? Total number of leaves per plant had not been counted, but an average of 3132 total leaves per plant are normally used in the literature for this plant species (Justin Brouwers boxwoods).

If you're interested in the details of the experiment, I left out my potted plants in the field for a week, took them back to the glasshouse and counted the number of infected leaves per plant after two weeks. I had two treatments - mulched (a practice where diseased plants materials left from previous years are covered with straw to prevent fungus spores splash dispersal to plants during rain), and non-mulched (infected plant remains from previous years are not covered, so we'd expect more spores being splashed to plants during rain. Disease is only spread by rain). The experiment was conducted over two years. In the first year, plants were taken out to the field for 30 weeks and in the second for 26 weeks, so total 56 weeks. If I use average or number of infected leaves PER TREATMENT (four plants), I'll have 56 data points. If I use number (or average) of infected leaves PER PLANT than I will have 56 x 4 = 224 data points. I have a total of 8 predictors ( mulched, non-mulched, wind speed, wind direction, total rain, rain duration, relative humidity and temperature during each week plants were in the field). Thanks very much for any assistance.
Comment: Do you also know the number of non-infected leaves on each plant? For example, having 4 infected leaves out of 4 total would seem to be a lot worse than having 4 infected leaves out of 400. Please add that information by editing the question, as comments are easy to overlook and can be deleted.
Comment: @EdM Thanks for your comment. I have edited question 2 with this information. Total number of leaves were not counted, but an average of 3132 total leaves per plant are normally used in the literature for this plant species.
Answer: As you have count data then it will be best to use a count model (Poisson, quasi-poisson, negative binomial) rather than treating the values as continuous.* As the highest number of infected leaves is only about 12% of the typical total number of leaves, you won't have to worry about hitting an upper limit of count numbers. One limitation is that you only know the number of infected leaves per plant, while what's probably of more interest is the probability of a leaf getting infected. That would involve a binomial model and require knowing numbers of total leaves per plant.
As you did not use the same plants repeatedly, think carefully whether a mixed model is really appropriate or helpful. With data over only 2 years, it doesn't make sense to treat the calendar year as a random effect. Whether a random effect for location makes sense similarly can depend on the number of locations. It's often thought best to have on the order of 6 groups (locations, here) to treat them as a random effect; see this page and this page for some discussion. You don't seem to have that many locations.
You propose to use the week as a random effect, but I suspect that (as typical for studies over time) you will have correlations in effects from week to week that a simple random intercept as you propose for week wouldn't adequately handle. It can be better to model week as a continuous variable but flexibly, with a regression spline or with smoothers in a generalized additive model.
For your main question about whether to use the numbers for each plant or the sum over the 4 plants for each treatment/week/location, it's generally best to analyze data as close as possible to the original unit of measurement. That argues for using values for each plant separately. An average over 4 plants wouldn't be appropriate for a count model. Treating the plants separately will better document whether there is extra variance among plants that needs to be handled with a quasi-Poisson or negative binomial model.
You should recognize that the main sample-size issue in count-based data is the number of counts rather than the number of individuals from which they were obtained. For example, if you did a binomial model with data on one leaf at a time and a probability less than 50% of infection per leaf, then the limiting factor would be the total number of infected leaves. And if the data are truly Poisson with the same distribution for each plant having the same treatment/week/location, the sum over 4 such plants would also be Poisson.

*If you nevertheless choose to treat the values as continuous, note that the variance of the count values will change with the number of counts in a way that simple linear regression won't acccount for. Modeling the square root of the number of counts is an alternative that sometimes works well, but provides results that are harder to explain to others.


Rails: what does schema.rb do?

Question: I used to think the db/schema.rb in a Rails project stored the database schema, so that ActiveRecord can know what table/column it has.
But earlier I surprisingly noticed that my project runs normally after I delete db/schema.rb!
So, since the Rails can work without it, what does schema.rb really do?
Comment: On boot Rails queries the database to get the real schema the DB has and this is what active record uses and how the schema.rb is generated. Some more info https://kirshatrov.com/posts/schema-cache/
Answer: The schema.rb serves mainly two purposes:

It documents the final current state of the database schema. Often, especially when you have more than a couple of migrations, it's hard to deduce the schema just from the migrations alone. With a present schema.rb, you can just have a look there. ActiveRecord itself will indeed not use it. It will introspect the database during runtime as this is much safer than to expect users to keep the schema.rb up-to-date. However to avoid confusion of your developers, you should always maintain a file that is up-to-date with your migrations.

It is used by the tests to populate the database schema. As such a rake db:schema:dump is often run as part of the rake test:prepare run. The purpose is that the schema of the test database exactly matches the current development database.

In addition to that, some people use the schema.rb to load the final schema into a database to avoid having to run a long list of migrations to setup a fresh database. This is sometimes necessary if you have an application where the previous migrations can not run cleanly with the rest of the application (e.g. because model definitions have changed between the time the migrations were added compared to the current state).
Generally however, I would recommend to keep the migrations up-to-date with the rest of the application so that you can always start with just the migrations rather than replying on schema.rb to avoid multiple and potentially diverging "sources of truth".
Comment: I think it should be expected that the users keep the `schema.rb` up o date, since the comment on the same file explain: _Note that this schema.rb definition is the authoritative source for your database schema_.
Comment: In some situations, you do need to update the database schema. For example, in our case we have multiple rails apps that share most of the models and those models are put in a separate repo (let's call it `shared-models`), which every app depend on. We put our migrations in `shared-models`, but run it in one of the apps, say app1. Then the `schema.rb` for app1 is updated automatically during the migration, but `schema.rb` files for other apps are not updated. You still need to copy the updated `schema.rb` file from app1 to other apps, so that they are all up to date
Comment: jgomo3 - The same comment in that file also says "This file is auto-generated...".  so there is no need for the users to keep this file up to date.  It happens automatically during migrations.
Answer: Rails Documentation / 6.1 What are Schema Files for?

Migrations, mighty as they may be, are not the authoritative source
  for your database schema. That role falls to either db/schema.rb or an
  SQL file which Active Record generates by examining the database. They
  are not designed to be edited, they just represent the current state
  of the database.
There is no need (and it is error prone) to deploy a new instance of
  an app by replaying the entire migration history. It is much simpler
  and faster to just load into the database a description of the current
  schema.
For example, this is how the test database is created: the current
  development database is dumped (either to db/schema.rb or
  db/structure.sql) and then loaded into the test database.
Schema files are also useful if you want a quick look at what
  attributes an Active Record object has. This information is not in the
  model's code and is frequently spread across several migrations, but
  the information is nicely summed up in the schema file. The
  annotate_models gem automatically adds and updates comments at the top
  of each model summarizing the schema if you desire that functionality.

Rails documents have you covered.

Rails: what does schema.rb do?


How can I improve as a site builder for dealing with errors I don't know how to handle?

Question: As a relatively new Site Builder, I understand some of what is going on under the hood. But when things go wrong .…
Without an intimate knowledge of module code and inner workings, the error messages often simply tell me something went wrong.
Furthermore, I don't know if a particular message occurred from the action I just executed, or if I have simply not been to a specific page in a while (or never before), in which case any number of actions could have broken it.
In any case, I have no idea what messages like this one mean:
<code>'Notice: Undefined index: var_name in _some_method_some_where() (line 35 .…'
</code>
This are the steps I typically perform (my workflow) to resolve an error:

Check the module's issue queue for known bugs –  Occasionally I find a known problem.
Google the error – Normally this doesn't help as the same error could happen for so many reasons, but occasionally it leads me to a fix.
Ask a developer if possible – They often have no idea about my problems …
Ignore the error and keep working.
If my site is really broken, I try to reset (ugh) or give up on the module altogether and do something else (sigh).

As a site builder, I really don't want to dive into the code every time.
How can I improve my workflow? Like what other steps, resources, approaches, etc would you recommend to a site builder when such kind of things go wrong?
Comment: One more thing to do: Learn to use Drush to access the error log and variables etc in case you get a WSOD.
Comment: A site builder shouldn't be dealing with errors related to code; that's a developer's job. The only sensible way to answer this is to say "learn the skills of a developer"
Comment: Interesting question, +1 ! I'd like to add another (relevant) answer to it, which is why I tried to enhance your question (feel free to correct where needed), and voted for it to be re-opened ... Fingers crossed!
Answer: I'm not really aware of a way to improve your workflow. In general I would recommend limiting your usage to modules that have hundreds or thousands of Downloads by site builders, but that is not a silver bullet. And, sometimes you need to use that -dev module that has only 5 downloads because it will save you tons of time in development work on your project.
Everyone typically builds up a listing modules they are familiar with, comfortable with and trust -- build that list for yourself.
Something you didnt mention and I think is a larger problem than what you've outlined is testing module updates to an existing site that is using tried/tested modules previously. I'm more scared of things breaking during a large update (even amongst stable modules) -- then of experimenting with modules earlier in my site building process.
Comment: In the end, there are no shortcuts for experience.
Answer: I think the key is in bullet number one:

Check module issue queue for known bug

You need to get to know the quirks of the module. Study the issue queue of the module the error is occurring in (as well as the module description and documentation, obviously). If your problem isn't there at all, file a bug report and help out the community.
Comment: Bullet "1." is indeed an important one, but I think there are others to consider as well. I'd like to add (bullet 0.) "learn how to pick your modules, how to recognize the good ones and the less-good ones"). After the request to re-open the question I'll be able to elaborate on that ("add comment" only allows a few hundreds of chars ...).


How to add a new field image?

Question: These are the field thats I already created:

And this is how my page currently looks like:

The first image is the background of this page.
I want to add field image on the blue line. But when I add new field of image it doesn't show the second image.
Any suggestions about how to solve this problem?
Comment: Please Check 1. In Manage display whether that image field has a setting hidden. If hidden it will not show up. 2. are you uploading image for node while creating that node? 3. Check the CSS of that image, whether it is hiding image due to CSS.
Comment: Does image show up in view preview?
Answer: Add the field to the content type; check your node/page template, and add some code to print the new image field. If there is no custom template for your content type, create one and customize the output to your wishes.
You might also check the display settings for the content type, and make sure your image is displayed.

How to add a new field image?


Can address change when passing a c++ vector by pointer

Question: If I have something like the code below, where I pass a vector pointer (e.g. it can be null), then in the called function I add items to the vector, is there danger that my vector pointer can become invalid? The same goes for passing by reference. Since vector is guaranteed to be contiguous in memory and will reallocate as needed is there danger that I could get a dangling pointer because the vector is relocated in memory? The code below is trivial but what if myVecFunc was adding a million values, or some large objects? I've seen library code that follows this pattern but it seems like you could run into trouble by doing this?
EDIT: Edited code to do *mVec->push_back(someNumber)
void myVecFunc(std::vector<double>* myVec)
{
     if (myVec != nullptr)
     {
        myVec->push_back(someNumber);
     }

}

int main(int argc, char* argv[])
{
   std::vector<double> myVec;
   myVecFunc(&myVec);
}

Comment: `myVec` itself cannot and will not be realloacted by a call to a member function. it has its own internal pointer for managing the dynamically allocated array (which can refer to different addresses after a `push_back`)
Comment: Your edit is wrong. Either do `(*myVec).push_back(...)` (note the extra parenthesis around `*myVec`) or `myVec->push_back(...)`(No asterisk here). The latter form is almost always preferred. Or in your case, just pass by reference.
Comment: Definitely use a reference, not a pointer. And yes, it is **safe** to do so. It is actually common for a function with a `std::vector<...>&` parameter to call `reserve()` first thing in its body so that memory is reallocated to what it is going to need (it makes the function faster by guaranteeing only 1 reallocation occurs, that it occurs before new elements are inserted + it guarantees you can use iterators without risk, since it will not reallocate).
Comment: Please try to create a [mre] to show us.
Comment: Just write `void myVecFunc(std::vector& myVec)  {   myVec.push_back(someNumber); }` And you will not even have to do nullptr validation.
Comment: It's common to have optional parameters that are pointers so that they can be `nullptr`.  Hence, OP's original question of the difference between the address of the object changing vs. the internal address of the object buffer changing on a realloc (for example) is a good one - has nothing to do with changing it to a reference.  @UnholySheep got it right.  Changing the signature to a reference is not the right answer in this situation.  It would be if the precondition of the parameter was that it be non-`nullptr`, but that's not the question.
Comment: @franji1 please do not alter the question to fix code when there are answers already. When you do, you should at least inform the answers so they can be fixed. In the current state my answer starts with nonsense. Nerermind, I noticed by chance, and will fix, but usually broken code is for the questions and fixes is for the answers
Comment: @463035818_is_not_an_ai Sorry - when I placed my comment - there wasn't an answer, but then I immediately edited the question (oops).  I did get to see your answer addressing the same issue of my fix - then saw you modified your answer (again, sorry).  My intent (based on my comment) was that people were commenting thinking the signature needed to be a reference because the client code did NOT pass `&myVec` but (I presume) a reference-looking parameter, hence the misleading comments about references.  Your answer nails it.
Answer: Frankly, you have two fundamental misunderstandings.
First, passing a pointer to a function: Function arguments are passed by value (unless you use references), pointers are no exception:
 void foo(int*);

 // usage
 int* x = nullptr;
 foo(x);
 assert( x == nullptr);

There is no way the assert could fail, because foo cannot modify x. In your example myVecFunc cannot modify the addressof myVec. The memory location of an object is tied to its identity. During lifetime it doesnt change. If you copy a vector to a different location, you get a copy.

Next std::vector. A vector internally stores a pointer to dynamically allocated memory used for the elements. The memory is properly managed by the vector. For example, you can copy a vector and it will copy the elements. You can pass a vector by pointer or by reference, no problem at all.
What can happen on a reallcoation that the pointer that the vector stores internally gets a different value. Hence this code should not be written like this:
std::vector<int> foo(2); // vector of size 2
int* ptr = foo.data();   // pointer to the internal array
foo.push_back(42);       // iterators and pointers are invalidated
std::cout << *ptr;       // DO NOT DERFERENCE THE INVALID POINTER !

In summary: There is nothing wrong in the code you show. However, you should only pass arguments by pointer when nullptr is a valid input. Otherwise use a reference.
Comment: _There is nothing wrong in the code you show._ Except, that is, `*myVec.push_back(someNumber);` should be `myVec->push_back(someNumber);`.
Comment: agreed myVec->push_back(...) is equivalent to (*myVec).push_back(...)


Application structure in Symfony 2

Question: I am quiet new to the symfony framework and took some lessons and purchased the 'Starting in Symfony2' tutorial from knpuniverse. I want to be sure that I use the correct setup for my application. My question is, How do you call your first central bundle? eg. FrontendBundle? I want to make the next structure in my application:

FrontendBundle

The front where people get a landing site where they can also login

from there, when they login, they get into the next bundle:

CustomerBundle

Backend app where customers get their invoices and pay them and edit their information we stored in the database

And at least:

AdminBundle

Another backend app where I can edit customers, make invoices for customers and edit the app information

Is this the correct way and is FOSUserBundle a good bundle for this kind of application?
Comment: Please provide links to external resources wherever you can.
Comment: I think that FOSUserBundle is good for this application. But I think that login page is part of FOSUserBundle.
Comment: @pal4life I cannot provide any links. I am a new user so I cannot post external links within my posts.
Answer: Bundles have sense only if they can be used in "multiple projects". I mean: if you write code, make it as a bundle and you can't reuse that bundle (for example because bundles, as you described above, are strictly and logically connected to your project) this three bundle separations is totally useless.
So, final answer (that is also a question) is:
Could you reuse FrontendBundle in other projects?
Could you reuse CustomBundle in other projects?
Could you reuse AdminBundle in other porjects?
If you notice that you can't use any or all of these bundles for other project, maybe this separations isn't good.
Why I say that?
Because if they can't be used in separated ways is likely that they should be used togheter so you should keep them togheter.
So I advice to keep them into a single bundle (YourNameYourBundleNameBundle (in that notation, for example)) and to separate the single "areas":

FrontEnd controllers/entities/views
Custom controllers/entities/views
Admin controllers/entities/views
Comment: @RicardoJ: wait a minute, FOSUserBundle should be "integrate" within your bundle but not inserted into. With integrated I mean that you should "link" the FOS using config and routings
Comment: Thank you for your answer. It is clear that I need to put the whole project in a single bundle, including fosuserbundle.
Answer: This problem has been discussed at length already. For application specific code either do a single AppBundle or don't use bundles at all.

Application structure in Symfony 2


Find the supremum of line integrals

Question: The problem is to find the supremum of the set of integrals of the form $$I=\int_C(y^3-y)dx-3x^3dy$$ where $C$ ranges over all positively oriented simple closed plane curves.
The idea I have is to apply Green's theorem to conclude that $I=\int\int_D (-9x^2-3y^2+1)dA$ where $D$ is the region bounded by $C$. I believe this integral has maximum value if $\int\int_D -(3x^2+y^2)dA$ does. But I don't know what to do next.
Answer: $\int\int_D (-9x^2-3y^2+1)dA$
The integral will be maximized if $-9x^2-3y^2+1 \ge 0$ for all $x,y\in D$
$9x^2 + 3y^2 \le  1$ is an ellipse
$x = \frac {r}3 \cos t\\y = \frac {r}{\sqrt 3} \sin t\\dy\ dx = \frac {r}{3\sqrt 3} \ dr\ dt$
$\int_0^{2\pi}\int_0^1 -\frac {r^3}{3\sqrt3}+\frac {r}{3\sqrt 3}\ dr\ dt$

Find the supremum of line integrals


Why my app crashes everytime i try to load my onboarding layout?

Question: I'm currently developing a small game with cards about Pokemon cards for class, and im facing a really weird issue.
I have a onboarding as a mini-tutorial for new users that only pops-up in the first run of the application but the issue is that in some devices it crashes and never shows up while in others it does.
I checked the console for this weird issue and the error i get is this one:
Onboard error in console
Not sure what to do, it works in one of my friends devices that is a Honor 8X but crashes in my Redmi note 9S also on a S10e and S21.
As extra, it does work in my Phone emulators inside android studio.
The only difference between the 3 is that my emulators and my friend's mobile are using API 29 while the others are on API 30, not sure if it had a lot to do with it but i guess it might help mentioning it.
Thanks and hopefully i can find a fix :D.
Answer: Managed to find the issue.
It was one of the libraries i was using for load my gif images, apparently in the version i was using it cause this weird issue with permissions that lead to that error i showed in my original message.
For fix it, i just used the lastest version of the library, in case anyone have the same error the librarie itself was:
<code>'pl.droidsonroids.gif:android-gif-drawable:1.2.+'
</code>
:)


Response reviewer on a repeated measures logistic regression

Question: I got a paper rejected at a conference with the following comment:

The used method for the analysis is correct, but I find it strange that
    the authors evaluate the results as a 4-condition experiment instead of
    the 2x2 experiment they set up. This makes their analysis of the
    interaction effect a bit clumsy, and they end up testing all possible
    combinations of conditions (which means they should have done a
    Bonferroni correction). A factorial analysis would have been much more
    straightforward.

As I do not have the possibility to respond, can anybody explain what the reviewer meant with:

the authors evaluate the results as a 4-condition experiment instead of
    the 2x2 experiment they set up
A factorial analysis would have been much more
    straightforward.

Can anybody explain what a factorial analysis is, and how a 4-condition experiment differ from a 2x2 experiment.
My experiment consist of 2x2 within-subjects design. For example A (yes/no) x B (yes/no), where AxB (no/no) is the control condition. I chose to perform a repeated measures logistic regression analyses as I have a:

Within-subjects design
A four level categorical IV (yes/yes, yes/no, no/yes, no/no)
A two level categorical DV (yes/no)

To test significance I contrasted the categories against a reference. I varied the reference to asses differences between categories. I don't see the "clumsiness" the reviewer implies, as this is the way I've learned it using a regression.
Answer: There are two possibilities here. The reviewer may be overly fixated upon this model due to strong preconceived notions of how such models should be adjusted. Or you did not sufficiently justify the model you presented. Reviewer preferences may be based upon either prior research to which you hadn't consulted thoroughly enough, or an overly critical mentality. In either case, those are beyond the scope of this answer.
Justifying an interaction effect depends highly upon the question at hand and there are circumstances when your model is correct. To explain the differences with models: the reviewer preferred the stratified model
$$\mbox{logit}(P(Y=1|X,W)) = \beta_0 + \beta_1 X + \beta_2 W$$
The interpretation of $\exp \left(\beta_1\right)$ is an odds ratio for the outcome comparing groups having $X=1$ to those having $X=0$ having the same value of $W$. A test of $\beta_1=0$ is analogous to the Mantel-Haenszel stratified odds ratio. Among $X$ and $W$, even if $W$ is experimentally controlled, we usually think of only one (e.g. $X$) variable as a main effect. Stratified models borrow information across values of $W$ and hence control for its influence upon the relationship.
What you fit was equivalent to the interaction model
$$\mbox{logit}(P(Y=1|X,W)) = \beta_0 + \beta_1 X + \beta_2 W + \gamma X W$$
where the interpretation of $\exp \left(\beta_1\right)$ is an odds ratio for the outcome comparing groups having $X=1$ to those having $X=0$ having $W=0$. If $W$ is an experimentally controlled condition, then that main effect has little practical interpretation. A test of $\gamma=0$ would be similar to a test of effect modification.
If you simultaneously test $\beta_1, \beta_2, \gamma = 0$ then what you are performing is a generalization of the Pearson $\chi^2$ test for independence in $X$ and $W$. Those two tests are the only justified tests I can conceive of from the interaction model. The test of effect modification is only really justified after examining the main effects from the stratified model.
Testing the y/n vs n/n, n/y vs n/n and y/y vs n/n contrasts is not a sensible way to do such an analysis. It's difficult to interpret their meanings and adjusting for multiple comparisons becomes hairy. (what if say, y/n vs n/n and n/y vs n/n was "significant" with positive association, but y/y vs n/n had negative association?) I would agree it's clumsy.
Answer: "Factorial analysis" means analyzing your data with respect to the factors in your model.
Your experimental design has two factors (A and B), each of which has two levels (yes/no).  This is usually modeled like this:
$$\textrm{logit}(p )=\beta_0 + \beta_1A+\beta_2B + \beta_3(A\cdot B)$$
This corresponds to arranging your data like this

and asking whether the row (Factor A, $\beta_1$), column (Factor B, $\beta_2$) or an interaction between them ($\beta_3$) produces differences in your outcome. This makes it easier to interpret your results because you can now argue that A and B are individually important (or not), and likewise for their interaction.
However, for your analysis, it sounds like you "exploded" your two two-level factors into a single factor with four levels and then asked whether different levels of that derived factor $D$ changed your outcome.
The model is something like:
$$ \textrm{logit}( p)=\beta_0 + \beta_1D$$
Graphically, it looks like this:

All you can say here is that one or more boxes are different from the rest. If you're going to compare them all, you ought to correct for multiple comparisons (but that's another thread).
This makes your result hard to interpret because I don't know whether A (or B) in isolation produces the effect, or if I need to measure both A and B to be sure. Suppose A="is male" and B indicates "is retired". It's much more useful to know if the effect is driven by gender or employment status, or both, rather than some nebulous combination of them.


Reduce button's size cut the image instead of reduce size

Question: I have a table with 2 columns: on the right one threre's some text and on the left one there's a button with image in it (some blue gradient) and a text. The image is in css file (it have to be this way).

When I change the width or height of the button (percentage) it doesn't reduce the image size but cutting it.
How can I make it reduce the size of the image?
Html:

            hello hello

            My name is

            Inigo Montoya

            <button class="button-background" type="button">
                update</button>

css:
    button.button-background
    {
        width: 100%;
        height: 100%;
        background: url('data:image/png;base64,iVBORw0g==');
        background-position: center;
        background-repeat: no-repeat;
        border: transparent;
        color: white;
    }

Comment: Use `background-size`. But are you sure the data url is OK? When I put that in a fiddle it doesn't show anything.
Comment: "background-size: contain" did the job. The url is a blue image
Answer: you need to make the image responsive so that it will fit inside the div/td width. For an image to be responsive add a class to image.
.image-responsive{
    max-width:100%;
    display:block;
}

Comment: Edited the answer. Misspelled while typing.
Answer: HTML:

    Hello Hello

            My name is

            Inigo Montoya

            <button class="button-background" type="button">
                update</button>

CSS:
table {
    border-collapse: collapse;
}
table, td, th {
    border: 1px solid black;
}
.button-background
    {
        width: 100%;
        height: 100%;
        background: url('http://wallpapers.free-   review.net/wallpapers/12/Abstract_Temporary_collapse.jpg');
        background-position: center;
        background-repeat: no-repeat;
        color:white;
    }


Delete entries from an associative array (JavaScript)

Question: I currently have a problem in deleting entries from an associative array in JS.
I tried this:
  myArray['key'] = value;
  myArray['key1'] = value1;

  ...

  delete myArray['key'];

But I get following results in my application:
  [ undefined, { key1: 'value1', key2: 'value2' }, undefined,
    { key1: 'value1', key2: 'value2' }, undefined, undefined ]

How can I delete the whole entry, key and value? I found the method splice() but I think it uses a different index. I wasn't able to delete the entries I want by passing the key to splice().
Comment: Javascript doesn't have associative arrays. It has objects, which are collections of names and values, and arrays, which are objects with a special length property and some handy methods.
Answer: It seems you are mixing arrays and objects. Associative arrays should be realized with objects:
myArray = {};
myArray['key'] = value;
myArray['key1'] = value1;

It is a bit confusing though because in your output, the objects don't have key anymore (so it worked), but the array containing those objects as undefined values. I cannot see how
 delete myArray['key']; is related to your output and which variable now contains which value (please clarify).
But it looks like you did something like:
var container = new Array(6);
container[1] = myArray;
container[3] = myArray;

This will initialize the array with 6 undefined values (sort of) and then set the second and forth value to something else.
If you want to use that "array" as associative array, you should declare it as object too:
var container = {};

Please post more code if you need a better answer.
Update: Yes, you should declare displayedWidgets as object:
var widgets = {
    displayedWidgets: {},

    clear: function() {
        this.displayedWidgets = {};
    },

    add: function(widget) {
        this.displayedWidgets[widget.id] = widget;
    },

    addArray: function(newWidgets) {
        // note that `each` is only available in newer browsers,
        // just loop over the array
        for(var i = newWidgets.length; i--; ) {
            this.add(newWidgets[i]);
        }
    },

    remove: function(widgetId) {
        if (widgetId in this.displayedWidgets) {
            delete this.displayedWidgets[widgetId];
        }
    }
};

Comment: The 'loop over the array' makes problems... How to get an entry of displayedWidgets by index, not by key? The key is the id of the widget what comes from the database.. so key != index.
Comment: +1: In JS, unlike PHP, arrays are not to be used as a hash map. The solution suggested is the best thing to do, displayedWidgets should be an object (which is a hash map), not an array which is to be used only when you need to index items by an interger, not a string.
Comment: @FFraenz: You cannot have both (with one data structure). If you also need some kind of order of the widgets, then you need another array, where you e.g. add the key. Or you base everything on indices only. Or I don't understand the problem... what do you need the index for?
Comment: I think I have to study a bit these things. Thank you for your fast help!


Pos receipt printer

Question: Is  it possible to connect a receipt printer to a telephone for printing similar to how a Credit card terminal works when connected to a telephone line.
Our clients donot have internet connections where we can connect the printer over Ethernet, so was thinking if it was possible to do the same via telephone line.
Comment: I do find the question on-topic, it's asking about a networking problem. That it's an unusual problem does not make it off-topic.
Comment: Be aware: your question appears to be off-topic, and will likely be closed. Are you *really* asking about connecting the printer to the telephone network, or is this about caring serial data over RJ-11 or RJ-14 cable?
Comment: I assume RJ-11 or RJ-14 are the cables used to connect telephone lines, so then yes this question would be related to carrying serial data over the RJ-11 or RJ-14 cable lines.
Answer: You provide too little information about your environment. Please at least mention:

What do your clients want to print?
What is your setup? Do you have a print server?
What is your existing network infrastructure?

That said, it seems you would like to remotely print to a printer, the way it is commonly done on a LAN, but over a telephone line instead of a LAN.
This is technically possible, but you'd need a printer that can talk to a telephone line. I'm not aware of any printer that does this. However, you could connect the printer to a router or a computer that has a modem and can dial out via telephone.
So either set up a (small) local server at the client site, or a special router. There used to be routers that made the connection Ethernet <-> analog modem, e.g. the MicroLink 56k Fun LAN from Devolo. No idea if there still is such hardware, but I'd guess there is.
Answer: It should be a fairly easy to use a pair of modems, the type that were used for dial-up Internet, provided that the receipt printer has a serial interface. Pre-configure the printer-side modem to auto-answer and have the terminal (DTE) speed and protocol compatible with the printer and save it as the default setting. Dial the receipt printer's telephone number from the other modem and once a connection is established any data sent to the modem will print on the receipt printer.
Answer: Wouldn't a FAX machine do the job?

Pos receipt printer


Magnitude of grad/nabla expressed in spherical coordinates

Question: Say we have the scalar field of $f(x,y,z)$ which we express in spherical coordinates $f(r,\theta,\phi)$. We are now asked to express the gradient of the field in spherical coordinates, with the following:
$$
\nabla{f}=\frac{\partial f}{\partial r}\hat{\mathbf{r}}
+\frac{1}{r}\frac{\partial f}{\partial \theta}\hat{\mathbf{\theta}}+
\frac{1}{r\sin{\theta}}\frac{\partial f}{\partial \varphi}\hat{\mathbf{\varphi}}
$$
We are then asked to find
$$
|\nabla{f}|
$$
I'm thinking that the magnitude component in spherical coordinates would be $r$, so $|\nabla{f}|=\frac{\partial f}{\partial r}$? So, if we have
$$
\nabla{f}=r^3\hat{\mathbf{r}}+\frac{1}{r}\sin{\theta}\hat{\mathbf{\theta}}
$$
then
$$
|\nabla{f}|=r^3
$$
Is this right, or am I missing something?
Answer: The vectors $\hat{r}$, $\hat{\theta}$, and $\hat{\varphi}$ form an orthonormal system. Exactly what these vectors are depends on the point we based them at, but they're always orthonormal unless that point was on the $z$-axis. The length of a vector $a\hat{r}+b\hat{\theta}+c\hat{\varphi}$ is therefore $\sqrt{a^2+b^2+c^2}$.
For an example of why those tangential components matter for the magnitude of the gradient, consider $f(x,y,z)=\frac{x^2-y^2}{x^2+y^2+z^2}$. In spherical coordinates(1), that's
$$f(r,\theta,\varphi) = \sin^2\theta\cos^2\varphi-\sin^2\theta\sin^2\varphi = \sin^2\theta\cos(2\varphi)$$
$$\nabla f = 0\cdot \hat{r}+\frac1r\sin(2\theta)\cos(2\varphi)\cdot\hat{\theta}+\frac{-2}{r}\sin\theta\sin(2\varphi)\cdot\hat{\varphi}$$
Sure, the radial component of that gradient is zero, but it's not a constant function. The gradient as a whole certainly isn't zero.
(1) There are two standard conventions for spherical coordinates; the physicist's convention $(r,\theta,\varphi)$ and the mathematician's convention $(\rho,\phi,\theta)$. They interchange the roles of the two angles, so you always have to watch out for the difference. In this post, I've followed the physicist's convention as used in the question.
Comment: so for your example the length would be $|\nabla f|=\sqrt{0^2+\left(\frac1r\sin(2\theta)\cos(2\varphi)\right)^2+\left(\frac{-2}{r}\sin\theta\sin(2\varphi)\right)^2}$?
Comment: Yes, that would be the length.


Modelagem Categorias e Subcategorias

Question: Estou modelando um banco de dados relacionado a e-commerce e estou com uma dúvida na modelagem das tabelas de categorias e subcategorias dos produtos.
A princípio eu criei duas tabelas uma de Categoria e outra de Subcategoria. No entanto, achei um artigo onde o autor diz não ser necessário criar duas tabelas. O que ele faz basicamente é na mesma tabela incluir o código da categoria no registro que será uma subcategoria.
Quais as vantagens de fazer um modelo com duas tabelas ou uma só, como mencionado no artigo?
Comment: Já trabalhei com os dois modelos mas não vi muitas diferenças entre duas ou um tabela.  A única coisa boa de usar somente uma foi a de montar treeview
Comment: Veja se algo te ajuda aqui http://pt.stackoverflow.com/search?tab=votes&q=categoria%20subcategoria
Answer: Necessário não é. A diferença está entre a normalização dos dados e a desnormalização dos dados.
A normalização visa evitar redundância de informações e dar mais consistência aos dados.
Já a desnormalização, visa melhor performance (uma vez que, em algumas situações, uma alta normalização pode causar altos custos de performance).
Optar entre um ou outro, ou mesmo utilizar um pouco de cada, depende de cada projeto (inclusive quantidade de registros, hardware disponível, quantidade de usuários, etc.).
Recomendação de um grande profissional da área de banco de dados:

"Normalizar até doer, desnormalizar até funcionar!"
Jason Couchman, autor do livro: "Oracle 8 Certified Professional DBA Certification Exam Guide"

Existem vários artigos na internet sobre o tema!

Modelagem Categorias e Subcategorias


Why are server CPUs so weak and expensive?

Question: So looking at CPUs with good single core performance. One example would be AMD EPYC 73F3 which is (according to passmark) on par with Ryzen 5950X, but 10 times more expensive and it's rated over x2 TDP.
In the intel realm there's really nothing on par when you look at single core performance as most of the offerings are marginally faster from Xeon E5-2660 v3 which is 8 years old. The upside for intel is that their server CPUs are not NUMA, so memory handling is better, and support seems more polished so not even sure how these synthetic benchmarks relate to real life situations where memory needs to be moved between cores in non-NUMA aware applications (is there really anything NUMA-aware out there besides oracle server?)
Xeon workstation CPUs seems to be on par with AMD's customer grade CPUs, but still not as powerfull as intel CPUs available for ordinary customers. The only upside for xeon workstation is that they support ECC, which seems to be the only reason why this space still exists as you could get much better customer CPU probably for half the price, but there's no ECC option and RAM is limited.
Also i noticed there are some issues with EPYC but Ryzen is working perfectly fine. So that may be a loaded question but what are people using nowdays as maybe im missing something but getting a server which is on par with some super-cheap ryzen setup in terms of power usage, reliability and performance seems impossible if you don't want to invest some enormous amount of money and the best you can do is to end up with single core performance of consumer grade 2YO Ryzen anyway.
Has innovation in server space stalled?
Comment: "10 times more expensive" *than* what? Also I'm not sure than recent Intel CPUs are non-NUMA (as claimed). I'm missing a concrete question.
Comment: This question will get mostly opinion based answers and probably will not survive.
Comment: Yes looking for opinion based answers. As for constantly running on high loads, usually cooling is the issue. ECC RAM is common on AMD consumer hardware, not that expensive. Have to pay premium on Intel for ECC, the thing is that on my laptop with 64G im constantly getting some small data corruption, while the sticks seems fine.

Actually consistent running at high loads should be easier to achieve as metal expansion and contraction is putting additional stress on components.
Answer: So let's go through your opinions line-by-line then;

So looking at CPUs with good single core performance. One example
would be AMD EPYC 73F3 which is (according to passmark) on par with
Ryzen 5950X, but 10 times more expensive and it's rated over x2 TDP.

This is a terrible comparison - try putting two CPUs in a 5950X-based 'server', or more than 128GB of memory,  or having more than 64MB of L3 cache, or more than 16+4 PCIe lanes.
It's not clear if you know what a server is I'm afraid, not in a production/professional environment anyway. Airliners, cruise-ships, oil-tankers, buses, trains etc. are designed to be reliable, resilient and deal with a wide variety of usage requirements over multiple years at a predictable cost - jet-fighters, speedboats, your car etc. are faster yes but designed for single, focussed use cases where reliability and costs are less of an issue.

In the intel realm there's really nothing on par when you look at
single core performance as most of the offerings are marginally faster
from Xeon E5-2660 v3 which is 8 years old. The upside for intel is
that their server CPUs are not NUMA, so memory handling is better, and
support seems more polished so not even sure how these synthetic
benchmarks relate to real life situations where memory needs to be
moved between cores in non-NUMA aware applications (is there really
anything NUMA-aware out there besides oracle server?)

Firstly nobody in a server environment cares about single-core performance, maybe a tiny handful do but >99% of people do not. It appears that you think that clock-speed is the only measure of single-core performance anyway, forgetting the impact of memory/QPI/UPI/IPC performance increases - not only would something as low-end as a 4210T (10c/20t, 2.3-base/3.4-turbo) absolute stomp a 2660v3 into the ground (and they list at only 555 USD by the way) but there are SKUs like the 8732C (28c/56t, 3.2-base/3.5-turbo) that would make the older chip seem silly - plus all their 40c/80t SKUs too.
And of course Intel does NUMA too, you probably mean on-socket-NUMA, which is a different thing, and the 92xx Xeons even did that - look at the 9282 (56c/112t) for instance, which has the same memory concerns as Zen CPUs.
Your assertion that "Oracle Server" is a rare case of being NUMA aware is wrong and pointless anyway as what matters is that the base OS or Hypervisor is NUMA aware, and anything even vaguely recent has had this for years. Any modern Linux/Windows will happily keep processes and their memory 'near' to each other within a NUMA domain unless very highly contended indeed, the same has been true for ESXi/KVM/Xen for even longer, most server applications just don't need to consider NUMA at all as it's all taken care of for them.

Xeon workstation CPUs seems to be on par with AMD's customer grade
CPUs, but still not as powerfull as intel CPUs available for ordinary
customers. The only upside for xeon workstation is that they support
ECC, which seems to be the only reason why this space still exists as
you could get much better customer CPU probably for half the price,
but there's no ECC option and RAM is limited.

Newer Threadripper and Ryzen CPUs and chipsets support ECC, so your point here is moot.

Also i noticed there are some issues with EPYC but Ryzen is working
perfectly fine. So that may be a loaded question but what are people
using nowdays as maybe im missing something but getting a server which
is on par with some super-cheap ryzen setup in terms of power usage,
reliability and performance seems impossible if you don't want to
invest some enormous amount of money and the best you can do is to end
up with single core performance of consumer grade 2YO Ryzen anyway.

Which problems, can you be specific?
Again this your lack of production experience. This site is very specifically for professional sysadmins/system-designers, we make that very clear when you join. And our number one priority when it comes to servers is to maintain the data we have and to maintain service for the dozens/hundreds/thousands of applications and users served by our infrastructure. Yes we care about power-usage, heat-management and overall server performance but these are distant secondary concerns to reliability, resilience, monitoring-capability, pre-failure-warning and capacity in terms of cores/threads/memory/PCIe-lanes - and frankly anything BUT production-level CPUs fail on multiple, if not all, of these criteria.
If you get bored google 'RRAS', see if that helps you understand.

Has innovation in server space stalled?

No not at all, but it's inherently never going to be at the same bleeding edge as consumer parts, simply because we need reliability - why would we risk running a server with a CPU with a few slightly faster cores but lose all of those features we need that I list above.
My analogy above is key - the vast amount of people fly with others on airliners as it's cheaper and more reliable than flying everywhere in a fighter-jet, the same for shipping containers - you could put one on a faster speedboat but the numbers don't add up, the same is true for lots of other ways of getting things done - handle more load, more reliably and more cheaply with larger well-engineered solutions rather than unique custom ones.
Metaphorically you've walked into the pilot's lounge at an airport and ripped into all the Boeings and Airbuses because they can't do a barrel-roll as easily as a Cessna. We're not idiots, just about everyone who comes here regularly has a decade or more (32 years in my case) of successfully doing this job on very large infrastructures, we're professionals who know how to research our work and learn from others in the same field (literally the point of this site).
Do you honestly think this post of yours is groundbreaking, genius-level work that hundreds of thousands of people, including every server and CPU manufacturer, has overlooked - or might it be that maybe you just need to learn more?
Comment: Actually disagree with some of your points. Even modern OS are horrible at managing NUMA and just manually setting affinity will land you 20-40% improvement in avg response times on EPYC even for applications with small memory footprint (< 50% of single node size) so it requires application support anyway and OS support is there mainly to keep it working, it seems.

Same as for single core performance being irrelevant. Probably 90% of the internet is php/node, multithreaded code is too complicated and to expensive to write and maintain for most users.
Comment: Very old 2260v3 will eat EPYC7451 regarding response times (around 40-60% faster for PHP), similar is true for mysql. Probably because of NUMA layout and inadequate support in software (im not sure if such fragmented layout can be optimally supported anyway, i think not because eg. OS disk cache cannot be optimized). Agreed that EPYC can process more concurrent requests, but you have slower to much slower response times and these response times add up on microservices architecture.
Comment: Not sure how 4210T could be more performant than 2260v3 considering the CPU is around 2x slower according to benchmarks, but that's actually a good comparison as i'm looking for some "replacement" for 2260v3 which would be around 40-50% more performant for close that price, which according to benchmarks seems impossible on recent intel hardware. Unless the benchmarks are incorrect.
Answer: Server CPU's are generally have instructions and features that are more suitable for the typical server workload and enterprise deployment:

optimised for concurrency (rather than single threaded application performance server workloads often scale by using more cores rather than running at the highest clock frequency on a single core)

they can be fitted with low-rise CPU coolers to fit in 1U server chassis

virtualisation support

more CPU cache

additional CPU instruction sets

no built in graphics

a server CPU works in concert with related chipsets on the motherboard and you're likely to have :

multi processor support
more memory banks and more supported memory
ECC memory
more PCI lanes and expansion slots
wired network at 10 GbE (or faster)
no desktop/laptop features:

no Wi-Fi
no Bluetooth
no HDMI/display-port/multiple video ports

out-of-band management
SAS rather than SATA ports
support for many NVME's

and others

Using server CPU's in desktops usually only makes sense when you're looking for those features and have a specific work loads that are better met with a workstation featuring server specs.  In general Server CPU's don't make "better" desktops


Vaadin and Java EE using Servlets and JSP Integration

Question: I have to develop 2 applications. On of those is an application which is already running on Tomcat using Servlets and JSP. The other is an application which is completely on Vaadin running on VMware vfabric localhost.
Now I want to integrate both as a single web application. How can I do this?
Answer: Check out the Chapter 11.2 in the Book of Vaadin:
There is a detailed description how to implement vaadin UIs inside html pages.
The simplest solution would be to use an iframe inside your JSP page , where you embedd a vaadin UI
Answer: You need to move the code of one of your applications into the other one. I would suggest you move Vaadin code into your JSP application as the later is usually more complex in terms of Servlets and Filters.
Once you have moved all the code, you need to make sure your VaadinServlet works alongside the existing Servlets and Filters in your JSP application. This means making sure that the JSP application's Servlets and Filters won't interfere with requests that should be handled by the VaadinServlet.
At that point you should be able to have both JSP and Vaadin running as a single Java web application. You have to pay attention to any shared resource that the applications might be using (for example the HTTP session) and fix/modify accordingly (this highly depends on your implementation details).
If you want to include Vaadin UIs into JSP pages, you can follow the steps of this example: https://github.com/alejandro-du/vaadin-jsp-integration-example. When including Vaadin Uis into JSP pages, test for Vaadin View implementations in your code (by adding/changing the URI fragment in the browser).
If your applications have any kind of Rol Based Access Control mechanisms, you will need to test and fix accordingly (something that also highly depends on your implementation details).


How does ObservableList know that its underlying data changed?

Question: Given the following code example:
<code>private final ObservableList<Person> data =
    FXCollections.observableArrayList(
        new Person("Jacob"),
        new Person("Isabella")
    );

public static class Person {

    private final SimpleStringProperty firstName;

    private Person(String fName, String lName, String email) {
        this.firstName = new SimpleStringProperty(fName);

    }

    public String getFirstName() {
        return firstName.get();
    }

    public void setFirstName(String fName) {
        firstName.set(fName);
    }
}
</code>
(A reduced example based on http://docs.oracle.com/javafx/2/ui_controls/table-view.htm#CJABHGAJ)
In that case, how does ObservableList know, that its underlying data changed? After all the SimpleStringProperty "firstName" in the Person class is private, so ObservableList shouldn't be able to attach any kind of listeners? Or is this done by some kind of reflection?
Comment: Can you provide an example showing that the ObservableList knows when the setter is called?
Comment: I can't, because there is none, I simply understood something wrong ;-)
Answer: It doesn't. It only knows about changes to the list itself. Check the API.


Drupal 8 - How to Reference Flags Twig Template without showing full content?

Question: I'm using Drupal 8 to construct a page, where flags are required for Adding Videos to Favorites. I am using the Flags Module, but it's a custom template, so I didn't use the {{content}} reference directly. Instead I'm using the machine names of each field in displaying and styling the node. I reference them using {{content.field_fieldname}}
The problem is that I'm unable to reference the flags that I have created using the Flags Module. They are appearing on other basic pages and articles (when I turn on those areas while editing the flags), but they fail to appear in the custom template that I have created for a node.
Could anyone please help me with this? Any sort of help is highly appreciated. Thank you.
Comment: Is it a part of links still? So `content.links`? If not you'll need to enable devel and dump out the variables to see what the name is.
Comment: @Kevin how do you mean it's part of links? Do I create a field under the Flag? I tried content.links and it's not showing up.
Comment: You'd need to identify then what the variable name is within the content array using a debugger.
Comment: Thank you very much @Kevin - I'll use a debugger. I've already switched on Twig debug but it's not showing the variable names. Can you suggest one?
Comment: Twig debug won't do that. You need to use devel or a debugger like xdebug and optionally Twig XDebug. devel comes with functions to use.
Answer: FOUND IT
Alright guys, so it's simple.
You reference the flag this way in your Twig Templates:
<code>{{ content.flag_machinename }}
</code>
Cheers.


Panels doesn't output views content pane title

Question: I have a panel named bar in which I added a view-content-pane named foo.For this view I created a template-override named views-view--foo--panel-pane.tpl.php in which I added, besides other things, a container for the $title like:

<?php print $title; ?>

The title of the view-content-pane is Foo.
To limit the moltiplication of divs I set to "No markup at all" the style of both the whole panel and the single pane.
Configured like that, the view shows with custom styles (which I setted in my custom theme-override) except for the title that doesn't display at all.
If I change the single pane style to "No style", the title is shown but using the panel default style (which breaks my layout).
It's there a way to output the view-content-pane title as configured in the template-override without this being rendered by the panel?
Comment: there is an option to disable panel page title.
Answer: The $title variable for the views_view theme hook is added only for the administrative preview. Here is the section of code in template_preprocess_views_view() that adds the title: http://cgit.drupalcode.org/views/tree/theme/theme.inc?h=7.x-3.11#n85
If you want to add that variable to your template override, you can do so with an additional preprocess.


How does lineage get passed down in RDDs in Apache Spark

Question: Do each RDD point to the same lineage graph
or
when a parent RDD gives its lineage to a new RDD, is the lineage graph copied by the child as well so both the parent and child have different graphs. In this case isn't it memory intensive?
Answer: Each RDD maintains a pointer to one or more parent along with the metadata about what type of relationship it has with the parent. For example, when we call val b = a.map() on an RDD, the RDD b just keeps a reference (and never copies) to its parent a, that's a lineage.
And when the driver submits the job, the RDD graph is serialized to the worker nodes so that each of the worker nodes apply the series of transformations (like, map filter and etc..) on different partitions. Also, this RDD lineage will be used to recompute the data if some failure occurs.
To display the lineage of an RDD, Spark provides a debug method toDebugString() method.
Consider the following example:
val input = sc.textFile("log.txt")
val splitedLines = input.map(line => line.split(" "))
                    .map(words => (words(0), 1))
                    .reduceByKey{(a,b) => a + b}

Executing toDebugString() on splitedLines RDD, will output the following,
(2) ShuffledRDD[6] at reduceByKey at <console>:25 []
    +-(2) MapPartitionsRDD[5] at map at <console>:24 []
    |  MapPartitionsRDD[4] at map at <console>:23 []
    |  log.txt MapPartitionsRDD[1] at textFile at <console>:21 []
    |  log.txt HadoopRDD[0] at textFile at <console>:21 []

For more information about how Spark works internally, please read my another post
Answer: When a transformation(map or filter etc) is called, it is not executed by Spark immediately, instead a lineage is created for each transformation.
A lineage will keep track of what all transformations has to be applied on that RDD,
including the location from where it has to read the data.
For example, consider the following example
val myRdd = sc.textFile("spam.txt")
val filteredRdd = myRdd.filter(line => line.contains("wonder"))
filteredRdd.count()

sc.textFile() and myRdd.filter() do not get executed immediately,
it will be executed only when an Action is called on the RDD - here filteredRdd.count().
An Action is used to either save result to some location or to display it.
RDD lineage information can also be printed by using the command filteredRdd.toDebugString(filteredRdd is the RDD here).
Also, DAG Visualization shows the complete graph in a very intuitive manner as follows:


While installing hadoop why do we turn iptables off?

Question: Why do we turn off iptables and Disable selinux.
Is there a workaround for this as it may cause security flaws?.
Answer: Many Hadoop clusters are built with "high walls". This basically means secure the outside of the cluster from random people getting in with iptables et al. But then once you are logged in you are trusted and anything goes. This usually isn't that hard if your Hadoop cluster data nodes are on a separate network, which is the norm for larger clusters. Security can impact performance, potentially cause things to break, and other bad things, so if you don't need it, don't use it.
This doesn't work for everyone, though. Either because of untrusted users or regulatory requirements. Authentication and authorization are challenging to solve in a distributed system like Hadoop and I'd end up writing a book on the subject to answer your question. I recommend taking a look at the new book Hadoop Security to help you with some of this http://shop.oreilly.com/product/0636920033332.do .
Answer: As perspective, we know Hadoop have it's own firewall system, so if in case don't want to be depend on underlying firewall.
Also we can say this underlying firewall takes part in communication every time, which is not necessary as you already have strong firewall
One more reason can be added that some communication error will come and we have to manage or resolve them, so rather than it's better to be disable.


Testing status for SagePay Form plugin

Question: I am providing maintenance for web site that is using "WooCommerce SagePay Form and SagePay Direct Gateway" plugin. To test some functionality I need temporary to turn on Testing status in "SagePay Form" section on Checkout tab of WooCommerce settings. Will I have any problems with returning to Live status? Do I need to contact support for activating account once again or everything is will be done automatically?
There is no clear answer on SagePay site. But there is a warning that after development stage is complete I need to turn on Live status and then it will be activated by the service. But what should I do after the account has already been activated?
Answer: Sage Pay live and test sites are unconnected. Therefore you can go back to using the test site at will - live won't be affected, so there is no need to contact support when you want to use live. You can even use them simultaneously, if you wish.

Testing status for SagePay Form plugin


REST calling is double executed at the time of multistep execution of Observable.subscribe

Question: Application is using Angular 2.4.3.
The problem that a REST calling is double executed by once in 2-3 months at present occurs.
Please tell me solution method.
The flow of processing is as follows.
(1) a button is clicked.
(2) REST1 is executed.
(3) when ResponseStatus of REST1 was 200, REST2 is executed.
above-mentioned (3) REST2 is double executed.
It's double executed by log of RESTService the same time.
The sample code is as follows.
I'm doing multistep execution of Observable.subscribe, but are there any problems in the code contents?
// (2) execution of REST1
let observable: Observable<Response> = this.http.get(requestOptions);
observable.subscribe((response: Response) => {
    let responseData: any = response.response.json();

    if (200 === response.status) {
        no1 = responseData.xxx.no1;
        no2 = responseData.xxx.no2;
        no3 = responseData.xxx.no2;

        // Abbreviation

        let requestOptions: RequestOptions = new RequestOptions({
            headers: headerParameters,
            search: urlParameters
        });
        let body = {
            "no1": no1,
            "no2": no2,
            "no3": no3,
        };
        let xxxDaoData: XxxDaoData = new XxxDaoData();
        xxxDaoData.data = body;

        // (3) execution of REST2 (REST is double executed)
        let observable2: Observable<Response> = this.http.post(xxxDaoData, requestOptions);
        observable2.subscribe((response: Response) => {
            // Abbreviation
        }
    }
}

If there are bug information on Angular and a case, please tell me.
Comment: How about checking responseData for null before executing Rest 2?
Comment: So **REST, REST1 and REST2** all are different
Comment: @RukshanDangalla I checked the log, I think `REST2` is executed double at the same time. Therefore I think it can't be avoided in null check in responseData.
Answer: Live Example
It must be to imperative approached you are using to chaining your request, please try the reactive way:
import { Observable } from 'rxjs';
import { concatMap } from 'rxjs/operators';

let request = observable.pipe(
  concatMap(val => {
    ... somecode
    return observable2;
  })
);

request.subscribe(console.log);

Comment: Thank you. I will try this method.


Como centralizar uma div com a largura auto?

Question: Tenho uma div dentro do footer, mas ela é expansível na largura, como faço para centralizar? Já usei margin: 0 auto; mas não foi.

Comment: posta um exemplo aí com o css do que tu fez
Comment: footer.rodape > aside.footer-down > .partners { width: auto; margin: auto; } essa é a div que quero centralizar
Comment: footer.rodape > aside.footer-down {
 margin: auto;
 width: 950px;
 height: 50px;
 display: table;
 position: absolute;
 bottom: 0px;
} essa é aonde ta o rodapé
Comment: Se não funcionou com `margin: 0 auto;` é por algum outro problema na sua página. Se não puser o CSS na pergunta, fica complicado de alguém responder.
Comment: Neste caso você pode remover a pergunta, ou postar a solução como resposta, se achar que pode ser útil para outras pessoas.
Answer: Provalmente o problema de não estar centralizando a div é a questão de que sua class 'rodape' não tem uma width definida e o mesmo vale para a div 'centralizar'...

.rodape{
  width:100%;
  background:red
}
.centralizar{
  width:80%;
  background:gray;
  margin:0 auto;
  padding:20px
}

qualquer coisa aqui

Answer: Se quer uma div responsiva que se auto ajuste e ela continue centralizada utilize o seguinte css:
.centralizar{width:20%; margin: 0 auto;}

Caso queira aumentar a div é só aumentar a porcetagem do width.
Lembre-se a posição e relativa a estrutura do html feita.


Como instalar o Opencv

Question: eu gostaria de saber como faz para instalar a ultima versão do Opencv 3.2 no linux ubuntu 14.04. Eu consegui instalar e colocar para compilar no codeblocks usando C++ seguindo um tutorial. Mas meu objetivo é realmente instalar a biblioteca opencv para que eu use ela com a linguagem python e possa rodar de boas o codigo. Eu nao entendi muito bem mas eu iria usar o impot do python para usar o opencv? alguem que conheça essa biblioteca poderia me dar umas dicas e me ajudar nisso? obrigado.
Obs: meu objetivo é reconhecimento de cor,e objetos.
Obs 2: eu gostaria de executar ele no atom ou no codeblocks.De preferencia no codeblocks.
Comment: Já [tentou](https://pypi.python.org/pypi/opencv-python): `pip install opencv-python`
Comment: nao funcinou,nao parece existir uma bilioteca no pip do opencv
Comment: Eu utilizei [este tutorial em inglês](https://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/) para o Ubuntu 16.04
Answer: Procure pelo pacote opencv em python com o pip, no exemplo abaixo estou em um ubuntu 16, em uma env python3:
~$ pip search opencv | grep "^opencv"
opencv-python-armv7l (3.2.0)     - opencv-python on armv7l.
opencv-contrib-python (188.8.131.52)  - Wrapper package for OpenCV python bindings.
opencv-cython (0.4)              - An alternative OpenCV wrapper
opencv-utils (0.0.2)             - OpenCV Utilities
opencv-python (184.108.40.206)          - Wrapper package for OpenCV python bindings.
opencv_cffi (0.2.2)              - A random subset of OpenCV's functionality, wrapped via CFFI
opencv_engine (1.0.1)            - OpenCV imaging engine for thumbor.
opencv_helpers (1.1)             - Helper functions for opencv
opencvutils (0.9.2)              - Simple OpenCV 3.x image processing functions

Nesse caso vamos instalar o quarto item:
pip install opencv-python

Ou instale o anaconda e acabe com todos os problemas de pacotes. :-)
Exemplo de uso
Capturando um video:
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Este exemplo foi retirado da otima documentação do pacote, há uma área de tutoriais muito boa com vários exercícios, divirta-se.
Answer: Instala o Anaconda.
Instala o OpenCV 3 rodando este comando no prompt do anaconda:
conda install -c menpo opencv3
Testei no Windows 10 e Ubuntu 14.
fonte: https://anaconda.org/menpo/opencv3

Como instalar o Opencv


predicate logic questions

Question: I'm having serious trouble understanding how to prove whether the below statements are true or false. Normally (when I'm working with simple stuff like p(x) → q(x)) I would create a truth table and see if there is a way to make the left side true and the right side false. In this case I have no clue how to begin. Questions: How do I solve this? Is it possible to do it simply using truth tables and if so, how does it work when I have something like p(x,y)? Can one p(x,y) = 1 and another p(x,y) = 0 in the same statement? Thanks in advance for any help.
∀x∀y(¬p(x,y) ∨ ¬q(x,y)), ∀x∀y(¬p(x,y) ↔ ¬s(x,y)), ∀x∀y(¬q(x,y) ↔ ¬t(x,y)) ⊨ ∀x∀y(¬s(x,y) ∨ ¬t(x,y))
∃x∃y(¬p(x,y) ∧ ¬q(x,y)), ∀x∀y(¬p(x,y) ∨ s(x,y)), ∀x∀y(¬q(x,y) ∨ t(x,y)) ⊨ ∃x∃y(s(x,y) ∧ t(x,y))
Answer: In general, truth table method does not work in predicate logic, due to the fact that we have to consider also interpretations with infinite domain.
In order to show that :

$\Gamma \vDash \varphi$

holds, where $\Gamma$ is a set of formulae, we need a proof (in a suitable proof system).

In the case of :

$∀x∀y(¬p(x,y) ∨ ¬q(x,y)), ∀x∀y(¬p(x,y) ↔ ¬s(x,y)), ∀x∀y(¬q(x,y) ↔ ¬t(x,y)) \vDash ∀x∀y(¬s(x,y) ∨ ¬t(x,y))$

due to the very simple formulae involved, we can try with an "informal" argument.
Forget about the quantifiers (all universal) and consider two "generic" objcets $a$ and $b$ in a domain $D$ whatever (i.e.$a,b \in D$).
Thus, from the premises of the formula above we have :

$(¬p(a,b) ∨ ¬q(a,b)), (¬p(a,b) ↔ ¬s(a,b)), (¬q(a,b) ↔ ¬t(a,b))$;

now we can use propositional logic.
If $¬p ↔ ¬s$ and $¬q ↔ ¬t$, from $¬p ∨ ¬q$ we can conclude with : $¬s ∨ ¬t$.
"Going back" to f-o logic, we have : $(¬s(a,b) ∨ ¬t(a,b))$.
But $a,b$ where objects whatever in the domain $D$; thus we can "generalize" the last formula, concluding with :

$\forall x \forall y (¬s(x,y) \lor ¬t(x,y))$.

predicate logic questions


What is the average or above-average score range for the AMC 1o and AIME?

Question: I'm not sure if this is the right place to ask, but what is the average/above-average score range for the AMC 10 and AIME? For example, what points would you say are below-average, average, above-average, and top-of-the-line?
As a starter, I'd say 120 for the AMC 10 is above-average because it's the AIME cutoff.
Comment: Seems to me that you can find statistics here: http://amc-reg.maa.org/reports/generalreports.aspx
Comment: In particular for AMC 10 120 looks quite above average (eyeballing 1-2 standard deviations above)
Comment: oh wait, it tells me mean and standard deviation. It's actually the nearest thing to 2 standard deviations above
Answer: Looking to the link Peter Woolfitt placed, we can find the following:

Over the past 6 AMC competitions, the average score is between 60 and 75. With 120 you are almost always in the top 2.5%, and in half of the cases its enough to get you in that top 1%. I'd say that 100 is already above average, i.e. at least in the top 20%.
AIME, I'd say that 5.0 is average, 3.0 is below average, 8.0 is above average, and 13.0 is the top, i.e. probably in the top 1%.


Using regex to split string by commas with a prefix

Question: It's a really basic question here but I'm for some reason struggling to build the regex.
I have a bunch of strings starting with X  (space at the end) and then a list of strings (could have multiple words) that separated by a comma and have a dot at the end.
Examples:
X abc, abd.
X abc, abd, abcd.
X abc abd, abc.
X asdas, asdasd, adsasda, asdasda.
X asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas.

I'm trying to use the re module to get a list of all the strings between commas, so I get:
['abc', 'abd']
['abc', 'abd', 'abcd']
['abc abd', 'abc']
['asdas', 'asdasd', 'adsasda', 'asdasda']
['asdas asdasda', 'asdasdas asdasda', 'asdasdasas', 'asdasddas']

I tried:
match = re.search('X\s+((.*)\,)+(.*)\.', content.text)

But it looks like it does not work:

Which regex I could use here?
Please note that the strings could have numbers and specials chars (like :;() and others).
Comment: You cannot do it with plain `re`-compatible regex. You either use a bit of code, or use PyPi  regex library. See [RegEx with multiple groups?](https://stackoverflow.com/questions/4963691/regex-with-multiple-groups) for a generic approach. With PyPi regex, `(?:\G(?!\A)\W+|X\s+)(\w+)` [can be used](https://regex101.com/r/wu5rii/1), or `(?<=X\s.*)\w+` ([demo](https://regex101.com/r/wu5rii/2))
Answer: This is a way to achieve what you want using only regex:
import re

lst = ['X abc, abd.',
       'X abc, abd, abcd.',
       'X abc abd, abc.',
       'X asdas, asdasd, adsasda, asdasda.',
       'X asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas.']

[re.split(", ", re.search("X\s(.*)\.", i).group(1)) for i in lst]

This method uses part regex:
import re

lst = ['X abc, abd.',
       'X abc, abd, abcd.',
       'X abc abd, abc.',
       'X asdas, asdasd, adsasda, asdasda.',
       'X asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas.']

[[j.strip() for j in re.split(",", i.strip("X."))] for i in lst]

Answer: Seems like you could achieve that easily without a regex:
string = 'X asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas.'

result = string.lstrip('X ').rstrip('.').split(', ')

should do what you want. Result:
['asdas asdasda', 'asdasdas asdasda', 'asdasdasas', 'asdasddas']

You can also shorten this to
result = string.strip('X .').split(', ')

but this will remove the given characters from both ends of the string.
If you have your whole text in one multi-line string, you can still do it in one line with list comprehension:
text = '''X abc, abd.
X abc, abd, abcd.
X abc abd, abc.
X asdas, asdasd, adsasda, asdasda.
X asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas.'''

result = [t.strip('X .').split(', ') for t in text.splitlines()]

Result:
[['abc', 'abd'],
 ['abc', 'abd', 'abcd'],
 ['abc abd', 'abc'],
 ['asdas', 'asdasd', 'adsasda', 'asdasda'],
 ['asdas asdasda', 'asdasdas asdasda', 'asdasdasas', 'asdasddas']
]

Please note: This only works if the characters in X and .  are different from the characters at the start respectively end of the string you want to keep. This is because strip doesn't mean "remove this substring from the ends of the string", but instead "remove any characters from the given set of characters from the ends of the string".
If your pattern in front e.g. looked like this
line = 'asdasX asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas.'

the above approach would not work.
Instead you could also trim the sting based on the length of your pattern, optionally after verifying that it in fact starts and ends with the patterns you are looking for:
if line.startswith('asdasX') and line.endswith('.'):
    result = line[7:-1].split(', ')

Result:
['asdas asdasda', 'asdasdas asdasda', 'asdasdasas', 'asdasddas']

or again, as list comprehension:
text = '''asdasX abc, abd.
asdasX abc, abd, abcd.
asdasX abc abd, abc.
asdasX asdas, asdasd, adsasda, asdasda.
asdasX asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas.'''

result = [t[7:-1].split(', ') for t in text.splitlines() if t.startswith('asdasX') and t.endswith('.')]

Result:
[['abc', 'abd'],
 ['abc', 'abd', 'abcd'],
 ['abc abd', 'abc'],
 ['asdas', 'asdasd', 'adsasda', 'asdasda'],
 ['asdas asdasda', 'asdasdas asdasda', 'asdasdasas', 'asdasddas']
]

On Python 3.9 and newer you can use the removeprefix and removesuffix methods to remove an entire substring from either side of the string:
result = [t.removeprefix('asdasX').removesuffix('.').split(', ') for t in text.splitlines()]

See this SO post.
Answer: Assuming that we can phrase the problem as wanting to find any one or more sequence of space-separated words, we can try using re.findall:
inp = ["X abc, abd.", "X abc, abd, abcd.", "X abc abd, abc.", "X asdas, asdasd, adsasda, asdasda.", "X asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas."]
for i in inp:
    matches = re.findall(r'(?<=.)\w+(?: \w+)*', i)
    print(matches)

This prints:
['abc', 'abd']
['abc', 'abd', 'abcd']
['abc abd', 'abc']
['asdas', 'asdasd', 'adsasda', 'asdasda']
['asdas asdasda', 'asdasdas asdasda', 'asdasdasas', 'asdasddas']

Answer: The easiest way to do this will be not with regex, but with a simple python script:
strings = ["X abc, abd.", "X abc, abd, abcd.", "X abc abd, abc.", "X asdas, asdasd, adsasda, asdasda.", "X asdas asdasda, asdasdas asdasda, asdasdasas, asdasddas."]

def split_words(list_of_strings):
    words_per_string = []

    for idx, s in enumerate(list_of_strings):
        words_per_string.append([])
        # remove X and first whitespace
        s = s[2:]
        splitted = s.split(",")
        for words in splitted:
            words_per_string[idx].append(words.strip())

    return words_per_string

split_words(strings)


Biostatistics and Pure

Question: I hope this is not "opinion" question
but I am curious as to whether or not the study of statistics and probability theory in the realm of cancer genomics is considered "less philosophical" than the pure math studies.
I am only asking because something inside me is very skeptical of pure math, i.e.  algebra and geometry.  I just am lacking a faith to study these abstract notions.
but I am interested in modeling cancer genes, and using probability to study biology.
however, I have some ingrained notion that "applied" is not as respected as "pure" math.  Can someone help me with this?
Even my algebra teacher has scoffed at applied studies.  So I am having this dilemma.
For instance,  straying away from functional analysis, and moving more into probability theory seems to me like a "weaker" move.   I am sure this is a philosophical question, but I am looking for the guidance of those working in statistics, and biostatistics.   Are these field theoretically rewarding and dense?
Ultimately,
 my question is that ,  do you think that biostatistics is only a particular scope on a specific part of biotechnology revolution? Do you think biostats is a general field, or particular and why?   "
The reason I am concerned about this, is because I am not interested in studying just a narrow field interested in just a small set of problems, and wish to be as general as possible.  Can someone advise on this?
Thank you very much.
Comment: This question seems pretty solidly in the realm of *opinion*.
Comment: I have no idea what that means.
Comment: Setting out to tackle (& *identify*) general, broadly applicable problems without ever having solved a specific problem in a narrow field might be viewed as a little ambitious. ["A Conversation with Sir David Cox", *Statist. Sci*, **9**, 3](http://projecteuclid.org/euclid.ss/1177010394) is interesting - his "fantastic experience" at the start of his career with the Wool Industries Research Association.
Comment: how can we know if a field is not general enough?
Comment: I think this question could be rephrased to be more appropriate for this site. Maybe something simple like "what distinguishes biostats from 'vanilla' stats?"
Comment: The conversation with David Cox is exactly what I wanted to read.  THANK YOU. I am interested not just in the interior of a field (i.e. "I study stats")  I am interested in the exterior of the field (i.e.  Wool textiles intersects physics, biology, engineering, and economic government funding etc etc )
Comment: He mentions in the paper that the statistics jobs in the UK for academy were all going to the Pure mathematicians.  is this true today?
Comment: In the paper of "Conversation with Sir David Cox" he mentions exactly the limits with applied fields being narrow in scope , and the broad sense of theoretical development.  Can studying biostatistics fall into the category of being "narrow" in scope?  and does biostats have the capacity to be broad enough to expand statistical theory in general?  this is my ultimate question.
Comment: (1) Hes' talking about Maths posts - Statistics posts barely existed back then. (2) It's more nuanced than a choice between narrowly applicable applied work vs broadly applicable theoretical work. Cox says his theoretical work on conditional inference "was very strongly motivated by practical experience  and yet on the other hand, I couldn't say it arose from one particular special type of problem. It arose in a sense from all the applied work I'd done to that point."
Answer: I see theory and application as intimately tied together.
Without theory we don't really know anything, and without application we don't know about anything.
Application without theory devolves into stamp-collecting, and theory without any application* is some kind of abstract language-game.
* Without application, what is it actually for? Keeping mathematicians out of pubs?
Fortunately, even when people do try to do purely abstract mathematics, the kind that is treated as 'interesting' is also the kind people keep coming up with applications for.
Theory gives a framework and methodology for understanding how to solve real problems (without which you are unlikely to get far), and application gives real problems to solve.
While I see myself as primarily an applied-applied statistician who has a smattering of theory, I can't imagine doing much of either without the other. Tools like simulation can get you some way where theory isn't up to the task (or our abilities aren't), but even simulation relies on theory. Almost everything I do relies on theoretical concepts, to frame and guide what I am doing, even when I seem to be doing the most "applied" things. My first step in trying to think about a new problem involves a pen and some paper (or sometimes, effective equivalents like LaTeX), typically to do algebra related to the statistical problem.
Comment: Can your work in the applied area, lead to the develop of new theory?  or is studying applied problems, trapping you into this particular problem set?
Comment: Or to be more concrete,  do the journals published in the statistical journals come from Math PhD's  or from Statistics PhDs?
Comment: Well, my PhD is in statistics (at least that's how I'd characterize it); but plenty of people publishing statistics papers have neither a mathematics PhD nor a stats one - I can point to many people from other areas doing important work in stats. (Indeed, people manage to publish good work just fine with no PhD at all; Fisher didn't seem to require one, for example, yet he did major work in more than one area. There's really nothing special about a PhD. It's basically a sign that you can do publishable work. Anyone with a couple of half-decent papers has demonstrated that already.)
Comment: wow this Fisher gentleman , quite awesome.  Yes, I think the limitations that I am worried about is not dependent on the field but on ability. It is quite possible to study statistics and publish in biology.  and vice versa.
Comment: In you applied work, you use theory, but can you develop theory?
Comment: or do only Pure math guys develop theory?

Biostatistics and Pure


include objective-c header in c++ file

Question: Is there a way to include an objective-c header from a cpp? Because when I try to #include "cocos2d.h" from a cpp .h file, a lot of errors complaining about @'s and -'s are showing up.
Can c++ files include obj-c headers like that?
Comment: Including a file is just like copying and pasting code from one file to another. I'm not sure why you think this would work since they are different languages. I think the question you should be asking is "how can I interface C++ code with objective C code".
Comment: When using .mm file, Obj-c is just fine including cpp, so I thought the inverse was possible.
Comment: Yes, but the inverse is including ObjC in a .mm file that mainly uses C++.
Answer: It is possible, but you need to use Objective-C++ (e.g. by making the file extension .mm) to mix the languages, plain C++ sources don't work.
To make that clear:

.m files only allow Objective-C sources
.cpp files only allow C++ sources
.mm allow mixed Objective-C++ sources - i.e. both Objective-C and C++ with some limitations

If you need to keep the two worlds seperated instead you need to write wrapper classes that hides the Objective-C details from C++ and vice versa.
Comment: So interfacing with an objective-c library from c++ is impossible? Hopefully not.
Comment: @shar: Technically you can call into ObjC from plain C++ using the runtime functions - but you'll not want to do that. Just use either the mixed approach or wrap the ObjC classes.
Comment: @Georg Fritzsche: but if I do, seems like I can't use cpp syntax in the .h or .mm file.
Comment: @shar: In the `.mm` this should be no problem, you might want to ask about that instead with more details. In the header this is fine as long you don't include it in plain `.m` files.
Comment: @Georg Fritzsche: I'm currently using a framework which uses .m files.  Might that be the problem, and if yes, is there a way to work around it?
Comment: @sha: If you are just *using* the framework, there is no problem. You only need `.mm` files where you *mix* the languages, e.g. if you want to call into ObjC methods from C++ code. As i said, show us what is failing.
Comment: @George, when i am trying to follow this, getting the error in NSObjcRuntime.h class? Any idea to resolve this??
Comment: @HussainShabbir It would be best to ask a new question with more details on your issue.
Comment: @george, please look on this http://stackoverflow.com/questions/21213734/import-objective-c-class-in-c-header-file
Answer: C++ has no idea what Objective-C is. So including an Objective-C .h in a .cpp is a no-go.
The other way around, though is fine, if you use the .mm file extension (Objective-C++) instead of .m (Objective-C).
Comment: It would be gross, but if you really really wanted to include a header that includes Objective-C in a .cpp, wrap the Objective-C stuff in `#ifdef __OBJC__` … `#endif` to prevent it from being parsed.
Answer: It is possible when you are compiling with mixed objc/c++. Cocoa applications can be written in languages mix in both directions: you can either use an obj-c class inside the C++ or a C++ class inside a obj-c object.
I assume in your case you are compiling pure C++ app where the obj-c code is not allowed.
Comment: No, i'm developing for iphone os and the cpp header file is referenced from a .mm file.

include objective-c header in c++ file