Can you define categories in terms of functors first?

Question: I've heard the properties of an object are fully determined by the morphisms to and from it.
So if functors map between categories then it ought to be possible to define what a category is in terms of functors?
Instead of "a functor maps between categories" "a category is what a functor maps to and from".
Comment: You should not take such statements too seriously. There is an element of truth there but it needs to be understood in context and _in addition_ to the traditional point of view, not instead of.
Comment: How is "functor" to be defined without using the notions of objects and maps between them? [If one uses those in the definition, it won't serve as defining "category" that way via functors.]
Answer: It can be done and it's not at all useless to think about how this can be done. The fact that it can be done is due to the same principle that a category can be defined by specifying its morphisms together with a partial binary operation satisfying some properties. Then, the objects can be defined in terms of the morphisms as those morphisms with some special property. Now, suppose that you want to define the category of sets in an object free manner. Well, there is a well-known axiomatisation due to Lawvere of the category of sets. So, take these axioms and state them in the object free manner (this can certainly be done, since it's just a syntactical difference between the language with objects and without objects). So, we can describe the category of sets and functions without saying what sets are.
Now, you can repeat the trick for the category of categories. But why stop here. Functors are the things the natural transformations translate between, so let's define the whole 2-category of categories purely in terms of its $2$-cells. And why stop here, let's define the $3$-category of $2$-categories purely in terms of its $3$-cells. Well, this never stops. There is a slick way to define strict $n$-categories; simply the category of all categories enriched in strict $(n-1)$-categories. I suspect that this slick mechanism gives a similarly slick way to mechanically climb up the ladder of defining strict $n$-categories purely in terms of its highest level cells.
Now, let's improve. Strict $n$-categories are too strict. We really want weak $n$-categories. And we really really want weak $\infty $-categories. So, if we can take the syntactic approach to defining strict categories and methodically weaken it sufficiently, we might get a workable definition of weak categories. There are many approach to weak categories and some are syntactic (e.g., Batanin's definition via a suitable monad on globular sets).
Comment: You mean the single sorted definition?https://ncatlab.org/nlab/show/single-sorted+definition+of+a+category I was thinking this might apply and yes also I was thinking of issues of recursion. Your explanation is a bit erudite it would help if you added references to some of the constructions you refer to.
Answer: I don't know whether it can be done, but I have also had this question recently.
To show that it could be done, we would need to state axioms in terms of "categories, functors, (other primitive notions)" and show that those were bi-interpretable with the typical axioms in terms of "categories, objects, morphisms".
Obviously categories can be interpreted as categories in both directions, and we know how to interpret functors from primitive notions of objects and morphisms. So what we need is some way to interpret objects and morphisms from primitive notions of functors.
For the sake notation, define (in the typical axiomatization)
$$ \mathbf{1} = \{ \ast \} \,, $$
the category with one object (the identity morphism is meant to be implicit above), and
$$ \mathbf{2} = \{\ast \to \ast \} \,,$$
(sometimes called the "interval category", cf. here or here) the category with two objects and one non-identity morphism.
Then we know in the standard axiomatization that objects of any category $\mathcal{C}$ can be identified with functors $\mathbf{1} \to \mathcal{C}$ and likewise morphisms of any category $\mathcal{C}$ can be identified with functors $\mathbf{2} \to \mathcal{C}$.
So if it is possible, I would guess that it likely requires not just having "category" and "functor" as primitive notions, but also "$\mathbf{1}$" and $"\mathbf{2}"$ as primitive notions. Then in this case objects would be interpreted/defined as functors $\mathbf{1} \to \mathcal{C}$, and likewise morphisms would be interpreted/defined as functors $\mathbf{2} \to \mathcal{C}$.
Using $\mathbf{1}$ as a primitive notion shouldn't be difficult, because that would just require an axiom saying something to the effect that it is the terminal object in the "category of all categories" $Cat$ (cf. here or here for rigorous definitions). E.g. something to the effect that,

There exists a category $\mathbf{1}$ such that for every category $\mathcal{C}$, there exists a unique functor $\mathcal{C} \to \mathbf{1}$.

I would guess that $\mathbf{2}$ also has a universal property that could be axiomatized solely in terms of functors, but I'm not sure. Because $Cat$ is apparently a (2-)topos (apparently the "archetypical example"), I would guess that $\mathbf{2}$ is "probably" (possibly) a subobject classifier for $Cat$ (a "Boolean subobject classifier"?). Anyway, if it has a universal property that can be stated solely in terms of categories and functors, and thus serve as an axiom, we are probably in good shape.
That being said, we would then either need to give axioms for the behavior of functors without referencing $\mathbf{1}$ or $\mathbf{2}$, or cheat and basically encode the standard axioms for objects and morphisms using/in terms of functors from $\mathbf{1}$ and $\mathbf{2}$. So whether such a project is possible (in a meaningful way) would seem to depend on how necessary it is to cheat when axiomatizing functoriality.
At this point it seems like what we might be looking for might be an axiomatization for $Cat$. This is definitely not my area of expertise, but it seems like such problems have been studied, and progress is possibly incomplete. In any case, see the following links for more reading that might give a better answer:

(nLab) ET2CC: an elementary theory of the 2-category of categories
(nLab) formal category theory
(MathOverflow) category of categories as a foundation for mathematics

None of these seem to directly give axiomatizations in terms of categories and functors, per se, but the idea at least seems related. Again, hopefully someone gives a more clarifying/edifying answer one day.


Getting wrong FBUID on iOS and old rest api

Question: I have a big problem.
The uid which comes from facebook (2147483647) is wrong.
On this site I can see, that the right uid of my profile is 100002137171664.
So .. what i am doing wrong ?
All needed permission are setted.

----------------------------------------------------------------------
-(void) session:(FBSession *)session didLogin:(FBUID)uid {
    NSLog(@"FBUID: %lld",uid); // 2147483647
}
----------------------------------------------------------------------
Answer: I think the problem is that you are formatting the fbUID incorrectly, try usin %d or %llu instead.
Comment: i tried it with %llu

Now i get an uid of 9223372032559808512

but its still wrong.
Try with %d = 2147483647 :(
Comment: Which Facebook SDK are you using? I think you should be using the new one, the one that provides SSO. Even if you want to disable SSO and login the old-fashioned way.


How to split data by date and predict using sklift from sklearn?

Question: I am using the sklift objects from sklearn to develop an uplift model (Solo Model). I am trying to split the data for train and validation whereas for each partition, there are X, y, and treatment columns. Treatment in this case would be a user getting notification (boolean) and y would be user converting (boolean).
stratify_cols = pd.concat([notification_flag, df.converted_flag], axis=1)
df=df.drop(['notification_flag','converted_flag'],axis=1)

X_train, X_val, trmnt_train, trmnt_val, y_train, y_val = train_test_split(
    df,
    stratify_cols.notification_flag,
    stratify_cols.converted_flag,
    stratify=stratify_cols,
    test_size=0.3,
    random_state=42
)

How to use all my data up to 2022-01-01 in my data frame (df) for the training and everything after that date for validation. How do I do this?

How do I predict for a new unseen dataset and return all three columns, the uplift, the actual baseline probability (if treated), and counterfactual probability (if untreated), i.e. 3% uplift / 30% conversion prob if treated / 27% conversion prob if not treated?
Comment: I don't get the second question. For the first one, please see the answer below.
Answer: Convert your date column to Pandas DatetimeIndex and perform a slice.
To convert you can use:
df["date"] = pd.to_datetime(df["date"])

Example:
import numpy as np
import pandas as pd

# generating a random df
df = pd.DataFrame(np.random.random((500,3)))

#generating random dates
df['date'] = pd.date_range('2021-1-1', periods=500, freq='D')
df = df.set_index(['date'])
train_df = df.loc[:'2022-01-01']

print(train_df.tail())

                   0         1         2
date
2021-12-28  0.027423  0.740380  0.606964
2021-12-29  0.609302  0.602346  0.812362
2021-12-30  0.171841  0.250788  0.182188
2021-12-31  0.322778  0.287429  0.585201
2022-01-01  0.014228  0.798382  0.769986

Comment: Thanks! Do you also happen to know how I could predict on unseen data with sklift to get the probabilities of interest?
Comment: No, I'm sorry, I don't know that. I'd suggest you to ask a detailed seperate question with appropriate tags to get an answer for it. And if my answer works for your first question, an upvote would be helpful for the community.


Estimating the confidence interval for the volatility of a GARCH model

Question: This question is a followup of my previous question
Forecasting with ARIMA and GARCH: does my plan look alright?
I have a times series $r_t$ and I am trying to estimate its volatility with a GARCH model as in the referred question.
You can for example consider the following time series:
<code> [1] -0.008230499 -0.025105921 -0.025752496  0.025752496
 [5] -0.008510690  0.041847110 -0.033336420  0.041499731
 [9] -0.008163311  0.024292693 -0.032523192 -0.008298803
[13]  0.080042708  0.000000000  0.088292607  0.041385216
[17] -0.013605652  0.046831300  0.006514681 -0.019672766
[21]  0.013158085 -0.006557401  0.019544596  0.092373320
[25]  0.116474991  0.020726131  0.169418152  0.167054085
[29] -0.128832872  0.056695344 -0.032002731 -0.016393810
[33] -0.151399646  0.104879631  0.159701110 -0.029964789
[37] -0.003809528 -0.034955015 -0.011928571 -0.016129382
[41]  0.012121361 -0.004024150 -0.004040410 -0.008130126
[45] -0.033198069 -0.065382759  0.017857617  0.034786116
[49] -0.017241806 -0.026433257  0.013303966  0.000000000
[53] -0.045052664  0.013730193 -0.009132484 -0.013857035
[57] -0.023530497 -0.019231362 -0.070380797 -0.005221944
[61]  0.015584731 -0.010362787 -0.048009219 -0.005479466
>
</code>
the elements of which are not autocorrelated.
The volatility is then estimated using a GARCH(1,1) model and predicted from it as follows:
<code>G.A = garchFit(formula = A~garch(1, 1), data = diff_log_close_price, trace = F)
G.A.est = predict(G.A, 30, plot=T, nx=nrow(closing_price))
volatility.A = c(volatility(G.A, type = "sigma"), G.A.est$standardDeviation)
</code>
Questions:

How can I estimate the confidence interval for the volatility from a theoretical point of view?
Is there an R function that does it?

I need the intervals for both predicted and historical volatility.
Comment: Great question! Did not have enough time to think deeper about it, but looking forward to some answers. Under a correctly specified model, the uncertainty in the forecasts of the conditional variance will be directly due to estimation variance (imprecisely estimated parameters) but not the estimated variance of the point process (which applies directly when calculating confidence and prediction intervals for fitted point values and point forecasts, respectively).
Answer: Due to the fact that I am not an avid R user, I will only contribute to question 1).
The GARCH process is defined by the mean equation
\begin{equation}
r_t = \mu + \sigma_t z_t
\end{equation}
and the GARCH equation
\begin{equation}
\sigma_{t+1}^2 = \omega  + \alpha \varepsilon_t^2 + \beta\sigma_t^2
\end{equation}
combined with an assumption about $z_t$, e.g. $z_t\sim N(0,1)$.
I have never seen people showcase confidence intervals for the fitted volatility process - in the GARCH process, the volatility at time t+1 is not stohastic, but know at time t.
It will however make sense, to showcase confidence intervals for $\varepsilon_{t+1\vert t} \sim N(0,\sigma_{t+1}^2)$ or $\varepsilon_{t+1\vert t}^2$.
To construct confidence intervals for GARCH forecasts multiple periods ahead ($\sigma_{t+k\vert t}^2$), where no closed form distribution is available, the standard procedure is to simulate a large number of paths and take the desired quantile based on either the assumed distribution of $z_t$ applied in the estimation or the bootstrapped distribution.
Comment: Though $\sigma_{t+1}^2$ is indeed deterministic given the information available at time $t$, a GARCH model may be used for obtaining fitted conditional variance. Then it is quite natural to ask for some confidence intervals; after all, we do not assume the estimates are perfect (primarily due to estimation uncertainty if we forget about model uncertainty for now). Bootstrapping would be an easy solution if only this was not a time series setting; it should be possible nevertheless. I wonder what other solutions one could come up with.
Answer:
The conifdence interval is simply given by:
$estimate\pm 1.96*s.e.$,

where 1.96 is the 95%-quantile of a normal distribution and s.e. is the standard error of the estimate.

There is a specific object of the function predict in R that allows you to plot the forecast and the relative confidence interval, try:
<code>  predict(G.A, n.ahead=30, mse='cond', plot=T)
</code>
Comment: I am afraid this does not apply to predicted volatilities (it applies to point forecasts, but that is besides the point).


Initialization between types "const int** const" and "int**" is not allowed, why?

Question: Using V1.8 z/OS XL C compiler, with warnings jacked-up using INFO(ALL), I get the following warning on line 4 of the code below:
WARNING CCN3196 Initialization between types "const int** const" and "int**"
                is not allowed.

1  int foo = 0;
2  int *ptr = &foo;

3  const int * const fixed_readonly_ptr = ptr;

4  const int ** const fixed_ptr_to_readonly_ptr = &ptr;

I can't wrap my head around why I'm getting this warning.  If I can assign an int pointer to a const pointer to const int (line 3), then why can't I assign the address of an int pointer to a const pointer to pointer to const int? What am I missing?
Note the code above is a slimmed down example just showing the issue I'm encountering in a small amount of code.  The real context is that I have a const pointer to pointer to struct (struct s** const) and am passing it as an argument to a function who's parameter is defined as a const pointer to pointer to const struct (const struct s** const). This is because the function will not modify the data in the struct (hence the first const) and it does not modify the pointer parameter which always holds the address passed in (hence the second const).  The value of the pointer pointed to may be changed by the way (which is why there is NOT a third const in between the **).
Comment: Pavel and Charles have made it perfectly clear why the compiler is warning me.  I upvoted both of you, but gave the credit to Charles for breaking it down from C point of view (although both answers are very similar and show why the warning is issued).
Answer: It's a type safety violation. Consider this code (I shuffled const around a bit to make it clear whether it applies to pointer or pointee, but semantically it means exact same thing):
int* p = 0;
int const** pp = &p; // presumably ok

int const c = 123;
*pp = &c; // okay, &c is int const*, and *p is int const* lvalue

*p = 666; // okay, *p is int lvalue

// wait, so we just changed the value of (const) c above, with no const_cast!

Answer: The C rule is that you can convert a pointer to something to a pointer to const something, but that something has to be exactly the same type including const and volatile qualifications further down the chain.
The rationale for this rule is that if the second of these two lines were allowed:
int *ptr;

const int ** const fixed_ptr_to_readonly_ptr = &ptr;

then this can be used to break type safety without a cast.
const int i = 4;

// OK, both sides have type const int *
*fixed_ptr_to_readonly_ptr = &i;

// the value of fixed_ptr_to_readonly_ptr is still &ptr
// the value of ptr is now &i;

*ptr = 5;

// oops, attempt to change the value of i which is const

Answer: This is a type-safety violation. You probably want to use a const int * const * instead.
See http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17
Comment: `const int * const *` only helps in C++, not C


Two raters' inter-reader reliability versus two-classifier classification accuracy

Question: 30 patients have a CT and a pseudo-CT scan image, I want to get them scored for the presence of a disease to know if the pseudo-CT has the same diagnostic performance as CT.
I give these two sets (30 CT and 30 pseudo-CT) to two radiologists to score them for the presence of disease using an ordinal score of 0-3.
What would be the best measure for this? Should I see that as an inter-reader reliability and go for Cohen's kappa? Or should I see that as classifier accuracy evaluation and go for its metrics?
Answer: Inter-rater, inter-coder and classifier accuracy are the same thing. But since they stem from different fields, the handbooks recommend different metrics. All metrics may be applied to all of them, however.
The metric that would be most useful in your case is Krippendorff's alpha for ordinal variables (since a 1-3 disagreement would be worse than a 2-3 disagreement). Most other coefficients for interrater agreement (Cohen's Kappa, Scott's Pi, Holsti...) don't distinguish between the types and gravity of errors.
Quite inapplicable would be the metrics used for dichotomous classification accuracy. Since you have four categories, you would have to recode the ratings and lose information.
Since you have few cases and only 2 coders, you could also just look at a cross-tabulation of ratings to identify eventual systematic biases (e.g. when radiologist 1 sometimes gives lower scores than radiologist 2 but never higher ones). This might also be interesting.
Comment: One display for such data is exemplified in Section 6 of https://journals.sagepub.com/doi/pdf/10.1177/1536867X1201200314

Two raters’ inter-reader reliability versus two-classifier classification accuracy


Botão que ao clicar envia para localização?

Question: Como configurar um botão para que quando clicado abra o maps e envie o usuario para um endereço?
Comment: Como assim: teletransporte?
Comment: Gps, ao clicar no botão envia pro maps
Comment: Deve te ajudar: http://www.coders-hub.com/2015/02/advance-android-google-map-2-tutorial-with-example.html#.WTgxjuvyuUk
https://stackoverflow.com/questions/4446811/how-to-get-the-latitude-and-longitude-on-map-in-android
https://stackoverflow.com/questions/24302112/how-to-get-the-latitude-and-longitude-of-location-where-user-taps-on-the-map-in
Answer: Primeiro, cria a atividade do mapa, aqui tem um Exemplo.
Depois, cria um método pra abrir a atividade e associa ao onClick do botão, algo como
public void getLocalizacao(View view) {
    Intent i = new Intent(getApplication(), Mapa.class);
    startActivity(i);
}

Voltando à atividade do mapa, pode setar a localização:
public void onMapReady(GoogleMap googleMap) {
    LatLng congresso = new LatLng(-15.7997586, -47.8647535);

E pra ficar legal, adiciona uma animação pra onde você setou a localização
CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(congresso)
                .zoom(16).bearing(0)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Answer: Tente da seguinte forma:
private void abrirRota(){

    /**
     * Nossa intenção será um google.navigation
     * Temos os seguintes parametros:
     * q= [Destino, endereço ou Latitude e longitude]; OBRIGATÓRIO!
     * mode= [define o método de transporte] {d= condução, w = caminhada, b = bicicleta}; OPCIONAL
     * avoid=[define os recursos que a rota deve tentar evitar] {t = pedágios, h = estradas, f=  balsas} OPCIONAL
     */

    final String url = String.format(Locale.getDefault(),  "google.navigation:q=Heitor+Stockler+de+França,+470+-+Centro+Cívico,+Curitiba+-+PR");
    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    startActivity(intent);
}


Does RCBD tend to increase the F value compared to the one way ANOVA?

Question: I thought that the RCBD model accounts for the variation from different factors, and so when we use ANOVA, the treatment effect gets "muddled up". Hence our F value in the RCBD model is higher than the F value in ANOVA, and we are more likely to reject the H0 in the RCBD model.
But I stumbled upon an example where the F value in RCBD is lower than the F value in ANOVA. How can my f-value increase when I combined SSE and SSB?
Answer: If the blocks are quite different, then using that information will reduce the estimate of error variance.
On the other hand, if the blocks barely differ, then it might even slightly increase the estimate of error variance (as it does in this example)


Can't logging in created users in Symfony2 with FOSUserBundle

Question: I have an application which only admin can create users and I use FOSUserBundle.
I can create user but I've got some problems when I want to login the created user.
They can't login.
I use the default login from FOSUserBundle and it works with users created from command line.
What I missed to do?
This is my createAction from my UserController:
public function createAction(Request $request)
{
    $user = new User();

    $form = $this->createForm(new UserType(), $user);

    if ($request->getMethod() == 'POST') {
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
        }

        $this->get('session')->getFlashBag()->add('success', 'The user has been added!');
        return $this->redirect($this->generateUrl('crm_users'));
    }

    return $this->render('LanCrmBundle:User:create.html.twig', array(
        'form' => $form->createView(),
    ));
}

This is my buildForm:
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('username')
        ->add('email')
        ->add('enabled')
        ->add('password')
        ->add('roles', 'choice',  array('choices' => array('ROLE_USER' => 'User', 'ROLE_ADMIN' => 'Admin'),'multiple'  => true));
}

Answer: You are not encrypting the password while creating the user.
Change the code inside form valid success to,
if ($form->isValid()) {
    $em = $this->getDoctrine()->getManager();
    $userManager = $this->container->get('fos_user.user_manager');
    $user->setPlainPassword($user->getPassword());
    $userManager->updatePassword($user);
    $em->persist($user);
    $em->flush();
}

Answer: Maybe your default enabled value is false.
Try to set it directly :
        if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $user->setEnabled(true);

        $em->persist($user);
        $em->flush();
    }

Or put it in your default value in entity class.


Errror ERROR 1064 (42000) on MySQL import

Question: Been trying to import a WordPress database using the command line on a FreeBSD server:
uname -a
FreeBSD host.com 8.3-i386-20120831 FreeBSD 8.3-i386-20120831 #0: Fri Aug 31 10:36:09 UTC 2012     firstname.lastname@example.com:/usr/obj/i386/usr/src/sys/SERVER8-I386  i386

as I had to many time-outs using PHPMyAdmin as it is a large file I guess . Importing using the CLI command
mysql -u user_wp -p -h subdomain.mysql.host.com database --default_character_set utf8 < betazone.sql

I got
ERROR 1064 (42000) at line 38316: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w' at line 1

There I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

Any ideas how I can get around this error. Earlier dump using WP DB Backup got imported, but it mangled Russian and some special characters and an import with --default utf8 did not work so I tried a PHPMyAdmin dump and then I had this odd error.
Any ideas how to fix this?
Answer: Looks like this is not a dump, or something prepend it.
Let us take a look to head betazone.sql
Comment: Yeah, there seems to be HTML in it. Here is as you asked:
head betazone.sql
-- phpMyAdmin SQL Dump
-- version
-- http://www.phpmyadmin.net
--
-- Host: sub.mysql.domain.com
-- Generation Time: Jan 14, 2013 at 12:56 PM
-- Server version: 5.0.95
-- PHP Version: 5.3.3
Making and trying a new dump now just in case
Comment: New import was of correct size. Other missed data and therefore did not work. All seems to be OK now and encoding is OK as well.


Understanding the elements of harmony in "honky-tonk" or ragtime style piano

Question: I enjoy improvising piano in what I call (perhaps incorrectly) a "honky-tonk" or "ragtime" style, usually involving a steady stride or two-step in the left hand, and playing over that with lots of syncopation in the right hand.  Harmony usually consists of majors and sevenths.
I am always impressed when I hear the introduction of other chords, fleetingly introduced (perhaps in a chromatic manner); they seem to be slipped in while transitioning from I to IV chords for example.  I am assuming they are augmented or diminished chords, but I have never understood the theory of which ones to use and where.
Is there a systematic way of thinking about this, or is it - just - what sounds great?
EDIT:  Here is the only quick example I could think of, off the top of my head.  (Can you tell I have young kids -- please excuse the example).  See middle of the piano solo at exactly 2:15 there is a chromatic bit.  What is going on there, harmonically?  And in general what harmonic principles is the piano player using throughout (e.g. at 1:41, and throughout piano solo 1:57 to 2:18).
Comment: This Wikipedia page, http://www.en.wikipedia.org/wiki/Classic_rag has the 'rules' for classic ragtime. Is that what you're looking for?
Comment: @Luke this is very interesting, thanks. But I'd like to know more about harmony and how to treat this in an improvisational context.  Not necessarily ragtime, but in general for any piano style of the pre-Jazz era.
Comment: One thing I think is cool regarding honky tonk or ragtime is that I think of a setting where the piano is played at some non-fancy bar or diner as background music where the piano is slightly off-tune. This is something that makes it a bit charming, and adds to the "honky tonk feeling".
Answer: If there are rules, they are pretty much the same as for popular music of the early 20th century.  Some rags have simple progressions; some use more complex progressions.  As with jazz improvising, "substitution" chords can be used, like ii-V7-I in place of IV-V7-I.  Ninth chords and beyond are rare.  Joplin's "Euphonic Sounds" and "Antoinette" are extreme in their progressions, and "Wall Street Rag" is unusual in using "crazy chords".  Joplin was pushing the envelope, or more likely writing what he considered classical piano intermezzos.
One interesting pattern that Perfessor Bill Edwards pointed out to me:  The first strain of a rag usually starts on a I chord; the second strain often starts with V-I, and the last strain often starts IV-I.
Answer: Scott Joplin, in his School of Ragtime, insists that ragtime should always be played in a strict, even time; straight eights. Ragtime does not swing, nor does it rock, instead it ripples.
So if you're swinging the eighth-notes, then "honky-tonk" is probably as good a term as any. If the left hand were busier, it might be Boogie-woogie.
To investigate the harmonic aspects, the chords or changes, of this genre (whatever we choose to call it), you should get a "Real Book".
[ Are we allowed to talk about these openly, yet? Nobody gonna sue nobody? ]
While the rhythms vary for all these related styles the harmony in all of them is based on Blues. The chords on the page for any song marked "blues" is going to ba a variation on the "standard" blues pattern
(
<code>12-bar:
 I - - - | IV - - - | I - - - | - - - - |
IV - - - |  - - - - | I - - - | - - - - |
 V - - - | IV - - - | I - - - | V - - - ||
</code>
) and any recording you may find of the song is likely to vary further still.
There are certain "events" in the progression that stand out. The movement to the IV chord feels (to me at least) like a "pulling away". It's only the Is and Vs where you can "sit a spell". But the I chord in bars 7 and 8 is not "comfortable". It's likely trying to listen to a lecture when you really need to pee. And the V chord in bar 12 "knows it's going home". The chordal variations change the character of these events, the mood of the situation.
Comment: Appreciate your clarification of the genre definition.  I will now not call this stuff ragtime, as I am certainly swinging it, and definitely not rippling (cool LaTeX by the way)
Answer: When talking about note, I think it is called "leading note" or "leading tone".
Look at this article in Wikipedia on leading tone.
EDIT:
When talking about chords (which seems to be the correct one for your question), I think you were referring to the Tritone Substitution Chords.
Tritone Substitution, is basically replacing the V in ii - V - I progression for example, with the note tritone away from the original. from V - VI is one tone. V - VII is two tone, from VII to IIb (two flat) is tritone distance.
Let's grab an example:
If you play a song in C, the basic ii - V - I progression is Dm - G7 - C, or its variants, Dm7 - G7 - CM7, or Dm9 - G11 - CM9, etc.
If you are doing tritone substitution, you will play: Dm - Db - C, or most of the time Jazz players will translate this to Db7 (D flat seventh), Dm7 - Db7 - CM7.
You can easily recognize this tritone substitution in classic Bossanova like "Garota de Ipanema" (Girls from Ipanema).
In the Bananaphone song above, my ear thinks the progression is II - V7 - II - V7 - I, with tritone substitution. So the V7 was replaced by IIb7. The progression goes II - IIb7 - II - IIb7 - I.
In C you'd play D7 - Db7 - D7 - Db7 - C.
Answer: If you're hearing a diminished chord, it's probably a ii or vii chord. The vii chord is pretty rare, but the ii can function as a secondary dominant, resolving to a IV or V which then of course goes to I.
I don't know too much about ragtime, so take this with a grain of salt.
Answer: Look at your dominant chords (motion by fifths, for example D7 > Gmaj, E7 > A) regardless of what key you're in. For example, say you're in the key of C, and you want to "arrive" at a Gmaj chord, you may insert a D7 in front of it. Or you want to "arrive" at a Em chord, you may insert a B7 in front of it, even though these D7 and B7 chord are not actually in the key of C, but they do function as dominant chords, and they do give that chromatic approach tone.
Dimished chords actually have a similiar function. A diminished chord is a substitute for a dom7b9 (dominant 7th with a flat 9) and they are often used where the two upper or two lower notes of the chord resolve up or down a half step to the next chord.
Answer: I heard this piano go to the IV chord, and then raise the root note up a half step. This is rather common in this kind of music, and It has a very interesting sound. The chromatic part, as far as I can tell, Is A type of V chord turnaround. You can play it by playing V, V, VI VIIb VII.


How can I point to a site in a not common directory path?

Question: Normally when adding a new Drupal site I just put the sites root folder in /var/www/ and then edit the hosts file for that address and then edit the httpd.conf file to point to that site.
The situation here is the Drupal site I am working on came from a git repo where other people work on it as well. The site came like this - /sitename/web/sites/default so when I put that in my /var/www directory it isn't the same as a usual setup which is - /sitename/sites/default, multipleSite1, multipleSite2, ...
So the /web directory is throwing things off I think. It messes with the simple way I point to a site with http.d conf and the way Drupal looks inside that directory for the settings.php file.
Simple example of httpd.conf that normally works fine
<VirtualHost *:80>
     DocumentRoot /var/www/testsite
     ServerName testsite
</VirtualHost>

Any ideas? I'm sure it's a real simple solution.
-apache2 on ubuntu10.04
Comment: This question doesn't seem specific to Drupal.
Comment: It has to do with where Drupal looks for the settings.php file. If the path to that file changes then Drupal relies on Apache to tell it where to look. How can I tell Drupal where to look for it?
Comment: If you install Drupal on /Volumes/HDA/Library/Webserver/Documents/dr71, then it will look for the settings.php file in /Volumes/HDA/Library/Webserver/Documents/dr71/sites/default/settings.php.
Comment: I install all my sites to /var/www/
Comment: Make sure the user `www-data` have read acces to this folder.
Answer: If I have an unusual directory structure I tend to use symlinks to get the folders into the correct place on the system.
If your site is running a standard drupal install you could install that to /var/www as normal
and create a link to your directory
ls -s /path/to/my/default/dir /var/www/default

Comment: combine this with the correct permissions @tostinni mentioned above and it's good to go. Thanks


Converter cronômetro para o formato hh mm ss

Question: Meu cronômetro está correndo sem o formato 00:00:00
Criei uma div no index.html

  00:00:00

No js
static iniciarTimer() {
        let time = 0
        const timer = document.getElementById(ID_DISPLAY)
        // atualizar o texto a cada segundo
        const atualizarTexto = () =>

        (timer.innerHTML =  time++)

        atualizarTexto()

        const idDoDisplay = setInterval(atualizarTexto, 1000)
        return idDoDisplay
    }

E inicio ele em outro arquivo: main usando this.tela.iniciarTimer()
Ele roda mas sem o padrão (00:00:00). O que devo acrescentar, retirar ou melhorar?
Comment: Precisa fazer alguns `if`s para verificar. [Aqui](https://pt.stackoverflow.com/q/279563/100416) tem um exemplo
Comment: Eu dei uma olhada, e fiz esse código porém ao sair da Tela ele pausa a contagem.
Comment: Isso já seria outra pergunta. [Nessa](https://pt.stackoverflow.com/q/62990/100416) tem exemplos em PHP, se você quiser em JavaScript mesmo, com cache, recomendo primeiro tentar fazer e, se não conseguir, criar uma nova pergunta apresentando suas dificuldades.
Answer: Crie um objeto do tipo Date e com o método Date.prototype.setHours() ajuste sua hora, minutos, segundo e milissegundos em 0. A porção respectiva a data nesse caso é irrelevante.
Dentro da sua função atualizarTexto() incremente em um segundo(1000 milissegundos) esse objeto do tipo Date com Date.prototype.setTime() e com o método Date.prototype.toLocaleTimeString() obtenha uma string com uma representação sensível ao idioma de uma porção de tempo dessa instancia de Date.

function iniciarTimer() {
  const timer = document.getElementById("display");
  let time = new Date();                            //Inicializa objeto Date para ser usado como cronômetro.
  time.setHours(0, 0, 0, 0);                        //Reseta o cronômetro.
  const atualizarTexto = function() {
    time.setTime(time.getTime() + 1000);            //Incrementa o cronômetro em  1s.
    timer.innerHTML = time.toLocaleTimeString('pt-BR', {
      hour: "2-digit",                              //Exibirá horas.
      minute: "2-digit",                            //Exibirá minutos.
      second: "2-digit"                             //Exibirá segundos.
    });
  };
  return setInterval(atualizarTexto, 1000);
}

iniciarTimer();                                     //Inicializa o time para ser exibido aqui no exemplo.

  00:00:00

Comment: Show! Este código está mais clean e fácil de entender. Utilizei e rodou tudo certo.
Answer: Revendo os códigos cheguei a uma solução, deixando desta forma:
static cronometro () {
        let timer = document.getElementById(ID_DISPLAY)
        let timerArray = timer.textContent.split(':')
        let timerParado = true
        let [hh, mm, ss] = timerArray

        setInterval(() => {
            if(timerParado) {
                timerParado = false
            }
                ss = parseInt(ss) + 1
                timer.textContent = `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`
            if (parseInt(ss) > 59 ) {
                ss = '00'
                mm = parseInt(mm) + 1
                timer.textContent = `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`
            }
            else if (parseInt(mm) > 59 ) {
                mm = '00'
                hh = parseInt(hh) + 1
                timer.textContent = `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`
            }
        }, 1000);

    }

Answer: Outra forma de fazer seguindo a sua linha de codigo seria, organizar o seu time em hora, minuto e segundo, e entao formatar...

 function iniciarTimer() {
      let hora = 0
      let minuto = 0
      let seg = 0
      const timer = document.getElementById('display')
      // atualizar o texto a cada segundo
      const atualizarTexto = ()=>{
       timer.innerHTML = formata_numero(hora) + " : " + formata_numero(minuto) + " : " + formata_numero(seg);
          seg++; //incrementa segundos
          if (seg == 60) {
            minuto ++; //incrementa minutos a cada 60 segundos
            seg = 0;
            if (minuto == 60) {
              minuto = 0;
              hora++;//incrementa horas a cada 60 minutos
            }
          }
      }

      atualizarTexto()

      const idDoDisplay = setInterval(atualizarTexto, 1000); //set 10 para teste, porem 1000 deve ser setado para incrementar de 1 em 1 segundo
      return idDoDisplay
}
iniciarTimer();

//concatena o ZERO caso numero seja menor que 10
function formata_numero( num ){
  return (num < 10)?"0" + num:num;
}

  00:00:00


Atmosphere with Spring Security

Question: I asked this question, but no answers. I found a lot of discussion about it. But no real solutions.
That's what I see.
After the first puch from server to client I receive data on client but Spring session is lost (I use GWT so all GWT RPC calls - 401 error). If I'm just doing push notifications from client to server without response from the server, the session is not lost.
More details here
If someone faced with the integration of Atmosphere and Spring Security (not necessarily with GWT). Please write. Or if someone has a good experience GWT + Spring Security + any other comet\websocket framework please share your experience.
Thanks in advance
Answer: I haven't tested this, but you can try enabling HTTP session support. If you can get to the underlying HTTP session, you should have access to SPRING_SECURITY_CONTEXT.

Atmosphere with Spring Security


calculating Z-values for path over surface described by x-values, y-values, and z-matrix in R

Question: The x axis and y axis is described by Longitude and latitude range values (1d-vectors),
The z axis is described by a 2d matrix.
How I can estimate the z value for a give lon/lat position in the surface?
    terra= interp(x, y, z, xo = lons[i], yo = lats[i]))

is not working as expected (akima) due to the case, that z has another dimension:

Error in interp(x, y, z, xo = lons[i], yo = lats[i]) :
Lengths of x, y, and z do not match

The size of the matrix z is x * y.
Comment: If you are using `interp` from the package `akima` (or the package `interp`), the x, y and z values all need to be the same length, so you need something like `interp(rep(x, each = length(y)), rep(y, length(x)), as.vector(z))`
Comment: Is there any alternative to the akima interp for this application?
Comment: Yes -see my answer below
Answer: The bottom line here is that akima::interp is probably the wrong tool for what you are trying to do, and you should instead use:
pracma::interp2(x, y, z, xp = lat[i], yp = lon[i])

Explanation
If I am understanding you correctly, you have a matrix z that represents a 3D surface. The latitude of each row is stored in the vector y and the longitude of each column in the vector x. You wish to find out the implied value of z for any arbitrary x, y co-ordinates that are not on the original grid using 2D interpolation.
This isn't really what the function interp is for (see below for an explanation of what interp does). It would be better here to use a function that specifically interpolates a 2D matrix such as pracma::interp2.
For example, suppose I have the following x, y, z objects, similar to your own set up:
x <- seq(0, 45, length = 10)
y <- seq(-45, 45, length = 10)
z <- outer(x, y, function(x, y) x^2 + y^2)

x
#>  [1]  0  5 10 15 20 25 30 35 40 45
y
#>  [1] -45 -35 -25 -15  -5   5  15  25  35  45
z
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#>  [1,] 2025 1225  625  225   25   25  225  625 1225  2025
#>  [2,] 2050 1250  650  250   50   50  250  650 1250  2050
#>  [3,] 2125 1325  725  325  125  125  325  725 1325  2125
#>  [4,] 2250 1450  850  450  250  250  450  850 1450  2250
#>  [5,] 2425 1625 1025  625  425  425  625 1025 1625  2425
#>  [6,] 2650 1850 1250  850  650  650  850 1250 1850  2650
#>  [7,] 2925 2125 1525 1125  925  925 1125 1525 2125  2925
#>  [8,] 3250 2450 1850 1450 1250 1250 1450 1850 2450  3250
#>  [9,] 3625 2825 2225 1825 1625 1625 1825 2225 2825  3625
#> [10,] 4050 3250 2650 2250 2050 2050 2250 2650 3250  4050

We can see this draws a concave surface:
persp(x, y, z, theta = 225, phi = 30, col = 'gold')

Now suppose I have some lat, lon co-ordinates that are within this domain but not directly on the original grid:
lat <- c(12.3, 4.6, 5.1)
lon <- c(-5.3, 0, 4.1)

I can work out the z value at these three points like this:
pracma::interp2(x, y, z, xp = lat, yp = lon)
#> [1]  835.75 1801.50 1817.75

Which seems to be the type of output you are looking for.

Why not akima::interp here?
By contrast, akima::interp tries to create a regular matrix of x, y, z values representing a 3D surface, given only a few x, y, z co-ordinates on that surface. It therefore creates a regular grid when you don't already have one, rather than interpolating arbitrary points between an existing regular grid.
We can show this by turning our x, y and z objects into a set of points and feeding them to interp. if we expand the x and y vectors and turn z from a matrix to a vector, we create 3 vectors of length 100 that represent the x co-ordinates, y co-ordinates and z co-ordinates of points on our surface. Feeding these to akima::interp will result in a smooth 40 x 40 grid being created from the original data:
persp(interp::interp(rep(x, length(y)), rep(y, each = length(x)), z),
      theta = 225, phi = 30, col = 'gold')

Since you already have a regular grid, this does not seem to be what you need.


Contact form in node

Question: I have a product catalogue website with no commerce feature and i want to embed a contact form in every product(node). User will be able to fill that form and the owner of the website will receive an email which will also includes the title and the link of the specific node. Is there any module available that can do this?
Thank you
Comment: Are you using d6 or d7?
Answer: Node feedback module offers a check box on the node form asking the author to allow the visitors of the node to send feedback/request for the node using the personal/site wide contact form. It is also possible to view URL from which node, for that you have set token. See the below image, possible to set available fields token.

For Drupal 6:
Author Contact shows a contact form that contacts the author of the current node.
You can set the tokens for title to show in email as well as in fields. I am using this in my website see the Interested in this Property
Comment: Node feedback might was good solution but there is a bug for D7 wich can be found here https://drupal.org/node/2031139 and i am not sure if i can use custom fields with it
Answer: The module Contact Form On Node exactly says what it does, so please give it a go.
Answer: Webforms + Nodeblock would work. Enable both modules & allow the Webform content type to be shown as a block, then configure the block to display only on your selected nodes.
Comment: With weforms + nodeblock is it possilbe for administrator to receive the Node Title and URL when user submits the form?
Comment: Sure- just add the Rule. It works like a normal webform, but displays as a block instead of page.
Comment: I have set up the rule and added the related tokens but what happens is to get the title of the Webform and not the title of the Current page(product) where the webform is displayed as a block.
Answer: You can use any of the way to insert contact form in node.

You can use webform module to insert any type of form in node. Webform provide you the flexibility to add as many forms with any number of fields in form with the availability of form created as block.
Now this module can be assigned to any node using its visibility settings
You can use Form block module which created block availability of contact form . so it can be assigned any node.
Or can call the contact form programmatically using the below code in  any custom block using php.

Hope it will help!
<code>  <?php

          module_load_include('inc', 'contact', 'contact.pages');
          echo drupal_render(drupal_get_form('contact_site_form'));     ?>
</code>

Contact form in node


Statistics: Combination problem

Question: Good day everyone.
I'm doing a combination problem and its solution keeps eluding me.
Problem:
Of a hand of 13 in a deck of 52 how many combinations are there of none of the cards being greater than 10, assuming that ace is greater than 10.
Attempted solution:
There are sixteen cards greater than 10: ace, jack, queen and king (all houses). So of thirteen cards in a house four are too great.
\begin{equation}
\left( \begin{array}{c} 13 \\ 4 \end{array} \right)
\end{equation}
Possible combinations of a hand consisting of only higher than 10 cards is:
\begin{equation}
\left( \begin{array}{c} 16 \\ 13 \end{array} \right)
\end{equation}
Multiply them together and subtract that from
\begin{equation}
\left( \begin{array}{c} 52 \\ 13 \end{array} \right)
\end{equation}
to get the wrong answer. There is something missing or wrong or both and I would appreciate help.
Thanks for your time.
Comment: Note that you can produce binomial coefficients more easily using e.g. `\binom nk` to produce $\binom nk$. Also, general matrices in parentheses are more easily produced using e.g. `\pmatrix{1&0\\0&1}` rather than `\left(\begin{array}{c}1&0\\0&1\end{array}\right)` to produce $\pmatrix{1&0\\0&1}$.
Answer: You don't really need to get into the substraction here. You can count directly the "good" hands. You've already shown there are $16$ "bad" cards. That leaves $52-16=36$ good cards. You need to pick $13$ of them. You thus get
$$
\binom {36}{13}
$$
"good" hands

Statistics: Combination problem


What are the advantages of hidden Markov model over neural network?

Question: I would like to know how about the differences between hidden markov model and neural network.
Comment: Welcome to this site yimon. This is a very general question, probably too general to give a sensible answer. Can you narrow it down? For example, if you have a specific research project in mind and are trying to decide between these two, then it may help a lot if you describe that research project.
Answer: Short answer: an HMM is a generative, probabilistical model and a neural network on the contrary, is a deterministic, discriminative model.
Longer one: Basically, a HMM is a generative, probabilistical model where you try to model the process generating the training sequences, or more precisely, the distribution over the sequences of observations. For the sake of clarity, let me refer to the case of text tagging. The goal is to learn to generate text: you give in one or more words, and the system should be able to generate a text on his own. In order to do that, one attempts to learn the grammatical structure of sentences (a verb comes after a noun) and how likely are given words to follow one another, given their lexical category.
The corresponding graphical model for an HMM is the following:

In the graph, $y(t)$ is the observation at time (or position) $t$. In our case, the word $y$ at position $t$. The hidden state, $x$, corresponds to its lexical category. It assumes that the observations (for example words) are generated by some hidden state. In addition, it assumes that those hidden states follow the markov property: the current state depends only on the previous state. I.e. whether the next word if a verb or an adjective only depends on the current lexical category.
The way this model generates text is the following: given the current word and category, it first samples the probability distribution $P(x(t)|x(t-1))$. Given the resulting $x$, it samples the probability $P(y(t)|x(t))$.
A neural network (specifically a multilayer perceptron) on the contrary, is a deterministic, discriminative model. A neural network leans a mapping from the input space into the output space. Once the network has been trained, i.e. the values of all weights and thresholds have been determined, the response of the network to every input is deterministic, i.e. for each input it always gives the same answer.
You can learn to generate text with a neural network, but there is no explicit modelling of a grammatical structure (it may learn some on its own, but that is hidden from you). You would train your network, and then feed the network with the first words. But after that what comes next is fixed, it is always the same. With HMM even when you feed in the same words, the output text will likely vary more or less.
Notice that for other models of stochastic neural networks is completely different.


Android - NullPointerException on ListView adapter when using SimpleDateFormat

Question: I'm having trouble when displaying a custom ListView on a tab (fragment). If I just set the adapter (which is a separate class that extends BaseAdapter) and the fields downloaded from the server, it works just fine. If I set the application to use my custom DateFormat class and format the date taken from the server in dd/MM/aaaa, I get a NullPointerException related to "childMeasure" (full logcat of the error below).
IndicatorsListAdapter.java (the adapter for the ListView)
package android.palharini.myhealth.fragments.tabs.adapters;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.palharini.myhealth.R;
import android.palharini.myhealth.date_time.DateFormat;
import android.palharini.myhealth.db.entities.Indicator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class IndicatorsListAdapter extends BaseAdapter {

    static class ViewHolder {
        public TextView tvMeasure;
        public TextView tvUnit;
        public TextView tvDate;
        public TextView tvTime;
        public int position;
    }

    private  ViewHolder holder;

    private Context context;

    private Indicator indicator;
    private List<Indicator> lsIndicators;

    private DateFormat df;

    public IndicatorsListAdapter(Context context, List<Indicator> lsIndicators) {
        this.context = context;
        this.lsIndicators = lsIndicators;
    }

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

    @Override
    public Object getItem(int id) {
        return lsIndicators.get(id);
    }

    @Override
    public long getItemId(int id) {
        return lsIndicators.get(id).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            convertView = inflater.inflate(R.layout.list_indicators, parent, false);

            holder = new ViewHolder();

            holder.tvMeasure = (TextView) convertView.findViewById(R.id.lvTvMeasure);
            holder.tvUnit = (TextView) convertView.findViewById(R.id.lvTvUnit);
            holder.tvDate = (TextView) convertView.findViewById(R.id.lvTvDate);
            holder.tvTime = (TextView) convertView.findViewById(R.id.lvTvTime);

            convertView.setTag(holder);

        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        indicator = lsIndicators.get(position);

        if (indicator != null) {
            holder.tvMeasure.setText(indicator.getMedida1().toString());
            holder.tvUnit.setText(indicator.getUnidade());

            String stDate = df.getDataAndroid(indicator.getData());

            holder.tvDate.setText(stDate);
            holder.tvTime.setText(indicator.getHora());

        }

        return convertView;
    }

}

WeekTab.java (a tab which has to display the ListView, along with an AndroidPlot graph)
package android.palharini.myhealth.fragments.tabs;

import java.util.Arrays;
import java.util.List;

import com.androidplot.ui.SizeLayoutType;
import com.androidplot.ui.SizeMetrics;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import com.androidplot.xy.XYStepMode;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.palharini.myhealth.R;
import android.palharini.myhealth.activities.edit.IndicatorEdit;
import android.palharini.myhealth.activities.register.IndicatorRegister;
import android.palharini.myhealth.date_time.DateFormat;
import android.palharini.myhealth.db.dao.IndicatorDAO;
import android.palharini.myhealth.db.entities.Indicator;
import android.palharini.myhealth.fragments.tabs.adapters.IndicatorsListAdapter;
import android.palharini.myhealth.session.SessionManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

public class WeekTab extends Fragment {

    private static Integer  difData = 7;
    private static String periodo = "DAY";

    private SessionManager sessao;
    private DateFormat ts;

    private IndicatorDAO indDAO;

    private ListView lvIndicadores;
    private Button btCadastrarInd;
    private Integer intTipoIndicador;
    private int x, y=0;

    private String stDataBusca;
    private Double dbMedia, vtMedias1[], vtMedias2[];
    private Integer intIdUsuario, vtDatas[];
    private List<Indicator> lsIndicators;
    private IndicatorsListAdapter adIndicators;

    private XYPlot grafico;
    private XYSeries grafSerie1, grafSerie2;
    private LineAndPointFormatter grafFormat;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_tab, container, false);

        sessao = new SessionManager(getActivity());
        ts = new DateFormat();
        indDAO = new IndicatorDAO();

        lvIndicadores = (ListView) view.findViewById(R.id.listViewInd);
        btCadastrarInd = (Button) view.findViewById(R.id.btCadastrarInd);

        grafico = (XYPlot) view.findViewById(R.id.xyPlot);

        grafico.getBackgroundPaint().setColor(Color.WHITE);
        grafico.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE);
        grafico.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);
        grafico.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
        grafico.setPlotMargins(0, 0, 0, 0);
        grafico.setPlotPadding(25, 10, 20, 0);
        grafico.setGridPadding(30, 30, 30, 10);
        grafico.getGraphWidget().setSize(new SizeMetrics(0, SizeLayoutType.FILL, 0, SizeLayoutType.FILL));
        grafico.getLayoutManager().remove(grafico.getLegendWidget());
        grafico.getLayoutManager().remove(grafico.getDomainLabelWidget());
        grafico.getLayoutManager().remove(grafico.getRangeLabelWidget());
        grafico.getLayoutManager().remove(grafico.getTitleWidget());
        grafico.getLayoutManager().getPaddingPaint().setColor(Color.TRANSPARENT);
        grafico.setTicksPerRangeLabel(5);
        grafico.setTicksPerDomainLabel(1);
        grafico.getGraphWidget().setMarginBottom(15);

        Intent intent = getActivity().getIntent();
        intTipoIndicador = intent.getIntExtra("tipoSelecionado", 0);

        intIdUsuario = sessao.getIdUsuario();
        stDataBusca = ts.getDataAtualBusca();

        vtMedias1 = new Double[difData+1];
        vtMedias2 = new Double[difData+1];

        vtDatas = new Integer[difData+1];

        for (x = difData; x>=0; x--) {
            dbMedia = indDAO.buscarMedia1Periodo(
                    intTipoIndicador, intIdUsuario, periodo, stDataBusca, x);
            if (dbMedia > 0) {
                vtMedias1[x] = dbMedia;
                vtDatas[x] = x;
                y = x;
            }
            else {
                vtMedias1[x] = vtMedias1[y];
                vtDatas[x] = x;

            }
        }

        grafSerie1 = new SimpleXYSeries (Arrays.asList(vtDatas), Arrays.asList(vtMedias1), "Médias");

        grafFormat = new LineAndPointFormatter(
                Color.RED,
                Color.RED,
                Color.TRANSPARENT,
                null);
        grafFormat.setPointLabelFormatter(new PointLabelFormatter());
        grafFormat.configure(getActivity(), R.xml.formato_serie_medias);

        grafico.addSeries(grafSerie1, grafFormat);

        if (intTipoIndicador == 3) {
            for (int x = difData; x>=0; x--) {
                dbMedia = indDAO.buscarMedia2Periodo(
                        intTipoIndicador, intIdUsuario, periodo, stDataBusca, x);
                if (dbMedia > 0) {
                    vtMedias2[x] = dbMedia;
                    vtDatas[x] = x;
                    y = x;
                }
                else {
                    vtMedias2[x] = vtMedias2[y];
                    vtDatas[x] = x;

                }
            }
            grafSerie2 = new SimpleXYSeries (Arrays.asList(vtDatas), Arrays.asList(vtMedias2), "Médias");
            grafico.addSeries(grafSerie2, grafFormat);
        }

        lsIndicators = indDAO.buscarIndicadoresPeriodoTipo(
                intIdUsuario, intTipoIndicador, periodo, stDataBusca, difData);

        adIndicators = new IndicatorsListAdapter(getActivity(), lsIndicators);

        lvIndicadores.setAdapter(adIndicators);

        lvIndicadores.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
                // TODO Auto-generated method stub
                Indicator indicSelecionado = new Indicator();
                indicSelecionado = (Indicator) lvIndicadores.getItemAtPosition(position);
                Intent irTelaEdicaoIndicador = new Intent(getActivity(), IndicatorEdit.class);
                irTelaEdicaoIndicador.putExtra("idIndicador", indicSelecionado.getId());
                startActivity(irTelaEdicaoIndicador);
            }
        });

        btCadastrarInd.setOnClickListener(new Button.OnClickListener () {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent irTelaCadIndicador = new Intent(getActivity(), IndicatorRegister.class);
                irTelaCadIndicador.putExtra("tipoSelecionado", intTipoIndicador);
                startActivity(irTelaCadIndicador);
            }
        });
        return view;
    }

}

Logcat
11-28 13:14:17.177: E/AndroidRuntime(1152): FATAL EXCEPTION: main
11-28 13:14:17.177: E/AndroidRuntime(1152): Process: android.palharini.myhealth, PID: 1152
11-28 13:14:17.177: E/AndroidRuntime(1152): java.lang.NullPointerException
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.palharini.myhealth.fragments.tabs.adapters.IndicatorsListAdapter.getView(IndicatorsListAdapter.java:81)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.AbsListView.obtainView(AbsListView.java:2255)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.ListView.onMeasure(ListView.java:1175)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1456)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.Choreographer.doFrame(Choreographer.java:544)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.os.Handler.handleCallback(Handler.java:733)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.os.Looper.loop(Looper.java:136)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at android.app.ActivityThread.main(ActivityThread.java:5001)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at java.lang.reflect.Method.invokeNative(Native Method)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at java.lang.reflect.Method.invoke(Method.java:515)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
11-28 13:14:17.177: E/AndroidRuntime(1152):     at dalvik.system.NativeStart.main(Native Method)

Can someone help me on this? (if additional code samples are needed, I'll be glad to provide)
Thanks in advance!
Comment: I think you did not initialize df
Comment: @Wicked161089 Oh dear, what a lack of attention from myself! Thanks for pointing that out!
Comment: Which line of your `IndicatorsListAdapter` is line 81?
Comment: Could you point at that line? `IndicatorsListAdapter.java:81`
Comment: String stDate = df.getDataAndroid(indicator.getData());
Comment: Also, it's worth mentioning that no errors were found on my DateFormat class. The same exact method is working normally in another screen.
Answer: change
private DateFormat df;

to
private DateFormat df = new SimpleDateFormat("MM-dd kk:mm:ss");

Comment: As I already have a full working class with my formats for dates I just initialized as `new DateFormat()`. That did the trick! Thanks all, you're awesome! :)
Answer: I see private DateFormat df; at the top of your IndicatorsListAdapter-class, but I don't see you intialize it anywhere before you get in the getView line 81:
String stDate = df.getDataAndroid(indicator.getData());

Perhaps change it to:
if(df != null)
    String stDate = df.getDataAndroid(indicator.getData());

or simply set your df somewhere before this, like directly at the variable:
private final DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
// replace dd-MM-yyyy with your desired Date format


How often should electric guitars be serviced?

Question: I have an electric guitar that I play from time to time. Should I be giving it 'maintenance services' or only if something goes wrong?
Comment: possible duplicate of [How do you care for your guitar?](http://music.stackexchange.com/questions/1372/how-do-you-care-for-your-guitar)
Answer: You should periodically inspect it and check the fingerboard and finish, because those are easily affected by humidity and temperature.
You should clean it periodically because sweat and skin oils can harden into gunk that is hard to remove later.
You should periodically check intonation because little bumps against the bridge can knock it out. Periodically check your pickup heights too, for the same reason.
Because you're not playing it a lot I don't think you need to check the nuts on the volume controls, switches and output jack regularly, but they can loosen from playing or temperature swings. They can also hide gunk so I used to pull mine off and clean under them, but that's just me.


Valve and solid state guitar amp power comparisons?

Question: is there a chart or general rule of thumb of how the different power levels for a valve amp compare to an equivalent volume solid state amp?
for example,

5 watt valve amp similar volume to 20 watt solid state
20 watt valve similar volume to 100 watt SS...
some other arbitrary example
Comment: It's not really meaningful to do such a comparison, as it depends heavily on how you use the dynamic range. A 5 watt solid state amp is actually _louder_ than a valve amp of the same power, you just usually don't play it that loud because, while solid-state power amps sound simply unpleasant when you drive them to the limit, this is exactly the point where valve amps produce the best of their sweet distortion. But a modern solid-state amp with sophisticated limiting can actually reach the full power without going into audible distortion at all.
Comment: put a great speaker in a GOOD solid state amp.a speaker that's rated around 110 db and see what happens. unless your cliché u wont regret it. itll change you!!!!
Answer: The simple answer is "no". All measures of the relationship between wattage and perceived loudness depend on a myriad of factors, tangible and intangible, and the results are ultimately subjective. You just have to line up different amps and speakers and cabinets and plug in your favorite guitar and your favorite effects and listen to what they sound like.
Answer: The simple answer is that a watt is watt whatever produces it - and that a watt is a measure of power, not volume (acoustic pressure level - decibels, that is). The volume is a factor of power AND speaker efficiency (ie: how many decibels a speaker produces for one watt).
As long as we're talking about pure clean tones and not pushing your amp to it's limits, a SS amp and a tube amp set up to produce the same output power (watts) AND going thru the same loudspeaker will produce the same volume (db).
The a-bit-less simple answer is that a SS amp cannot produce much more power than what it's rated for - it will almost immediatly hard-clip your signal - while a tube amp will smoothly go into a more gentle soft-clipping, slightly warming up and compressing your signal but with still quite a lot of "less clean" available power. Given the very dynamic nature of a guitar signal, this means that when pushed to it's nominal power, a tube amp will still have some "not quite clean but pleasantly sounding" headroom where the SS amp will hit a brick wall.
If you factor in the fact that most SS guitar amps are budget practice amps with cheap cabs, cheap and inefficient speakers and more often than not very optimistic nominal power rating you understand where the myth of the "tube watts vs SS watts" comes from.
EQ (from the guitar, the preamp AND the speaker) also plays a huge role when it comes to perceived loudness, specially in a mix where you have to compete with other instruments. Guitar tone is essentially about mids, mids and then mids, so if you end up with a very scooped "V shaped" EQ you'll have to compete with the bass and kick in the lows and with the cymbals in the highs, and chances are you'll need much more power to be heard.
So to make a long story short: no, there's no "chart or rule of thumb", since it's not that much about how many watts but about how these watts are used.
Answer: I think perception of loudness is much more relevant than technical specs. We use our ears to hear the amp not meters. I have had several amps over the years. 5 all valve amps. 3 Laneys, a Fender Hotrod deluxe and a Vox AC15. I have also had countless solid state and tube emulation amps. And what it boils down to is this: My 15 watt Vox will easily match an un-mic'd drummer. If I need louder I can mix the amplifier through the PA use the front of house to provide the volume. What is crucial to me and the only thing that should matter to you is what the amp SOUNDS like. The quality of tone has to be the primary consideration and on that score for me, I have never found a Solid State amp that sounds a fraction of good (or perceptively as LOUD) as a valve amp.
Answer: No. A watt is a watt. The apparent difference has to do with how the speaker interacts with a valve or a SS power stage. Read this   http://lenardaudio.com/education/14_valve_amps_7.html   It's science, not where you set your knobs.
Answer: Good answers on this age old topic...
A tube amp with a specified 50w output from 100Hz to 10000Hz with 1% distortion will be similar in clean undistorted volume as a 50w mosfet amp with the same frequency specs and distortion level.
But the tube amp will start to clip gracefully with harmonic distortion and at 10% distortion you will still perceive it as fairly clean with a little bit of hair around hte note whereas the solid state amp will sound fairly terrible with 10% of harsh unmusical distortion.
But also build and such is important.. A vintage 100w marshall SLP has large transformers and capacitors and can put out considerable more power than the 100W speicified.. I think I have seen numbers in the 160-170w with a big degree of harmonic distortion in the output stage...
But 4x the output from tube to solid state is exagerated. If the solid state amp is overbuilt and can deliever a lot of current under a wide range of impedances it will be fairly strong.. My transitor VOX VT50 was specified at 50W RMS and is was a loud amp.. Compared to a Laney cub 12r with two EL84 for 15 watts of output and dinky transformers the VOX through the same speaker was louder and much more punchy..
Answer: I remember reading that the magic ratio was three times, so a five watt tube amp would compare to a fifteen watt solid state. But like everyone else is pointing out, this is a perceived comparison, not real. There are many other factors involved. From experience I can tell you that I perceive this difference and appreciate it, but when you are playing with a drummer and you need say thirty watts to hear yourself, the ten watt tube amp isn't going to cut it.


Translate "A is not necessary for B" in math expression

Question: I tried to to solve this but what I found is
A is not necessary for B

I could be wrong

= not(A is necessary for B)
= not(not(B) or A)
= not(A) and B

but it doesn't make sense.
Let's take an example:
A = understand things
B = argue about things
A is not necessary to B = not(A) and B

so

Understand things is not necessary to argue about things = Not understand things and argue about things

should be the same thing.
I really appreciate any kind of help.
Comment: "A is not necessary for B" means that B could be true even when A is false. So $B \nRightarrow A$
Comment: $A$ does not imply $B$?
Comment: @stuartstevenson That states that $A$ is not *sufficient* for $B$. The correct answer is: $B$ does not imply $A$. Also have a look at [this question](https://math.stackexchange.com/questions/2942178/is-every-sufficient-condition-also-a-necessary-condition/2942186#2942186).
Comment: The problem with this approach is that instead of negating $B \to A$, you probably intend a meaning that is better expressed by negating $\forall x.(B \to A)$
Answer: "$A$ necessary for $B$" is actually "$B$ implies $A$"
So "$A$ not necessary for $B$" is actually "$B$ does not imply $A$"
In mathematical notation:$$\neg[B\implies A]\text{ or equivalently }\neg A\wedge B$$
This states that $B$ can be true while at the same time $A$ is not true (so no necessity for $A$ to be true in order to achieve that $A$ is true).
Comment: It's probably worth noting that, strictly speaking, the statement should be written in predicate logic, rather than propositional logic. In which case it would be $\neg[\forall x\in B, x\in A]$, or some other variation on this.
Comment: "B implies A" is equivalent with "not(B) or A". This is mentioned in the question (" not(A is necessary for B) = not(not(B) or A)"). I do not see how you answer the question.
Answer: When you interpret "is necessary" as "is implied by" then indeed we have "$A$ is not neccessary for $B$" exactly where "not $A$ yet $B$".
Check the truth table: $$\begin{array}{l:l|cc}A & B & A\gets B\\\hline \top & \top & \top  \\ \top & \bot & \top \\ \bot & \top & \bot &\star \\\bot& \bot & \top \end{array}$$

The issue is you are interpreting "is not necessary" as "is maybe not implied by"; which requires modal logic quantifiers.
$$\neg\Box(B\to A)\equiv \Diamond(B\land\lnot A)$$


Como referencio um context no EntityFramework?

Question: Estou desenvolvendo uma API em c# e uso o framework Entity e preciso criar uma migration.
Minha API precisa conectar com dois bancos de dados o banco interno e um banco externo, com isso , foi necessário a criação de dois contexts. O problema ocorre quando eu uso o comando
dotnet ef migration add migration_002

É retornado o seguinte erro:

More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

Preciso selecionar um de vários contexts mas não consigo selecionar nenhum deles.
Answer: Coloque o -Context (--context se tiver usando o CLI dotnet) depois disso o caminho do context, algo tipo:
dotnet ef migrations <COMANDO> --context solução/models/NomeContext

Comment: obrigado @Rogerio Santos ajudou muito!!!
Answer: Consegui criar a migration , ficou assim
dotnet ef migrations add migration_001 --context NomeDoContext


How to get ordered this sql query

Question: comments table
comments table
stars table
stars table
i write this query: (for ordering sites by most stars_sum)
$comments->join('stars', 'comments.star_id', '=', 'stars.id');
$comments->selectRaw('comments.site_id as site_id, comments.id as comment_id, stars.key1 + stars.key2 + stars.key3 + stars.key4 + stars.key5 as stars_sum');
$comments->groupByRaw('site_id, comment_id DESC');

select comments.site_id as site_id, comments.id as comment_id, stars.key1 + stars.key2 + stars.key3 + stars.key4 + stars.key5 as stars_sum from `comments` inner join `stars` on `comments`.`star_id` = `stars`.`id` where `comments`.`deleted_at` is null group by site_id, comment_id DESC

query result
stars table
but i want result like this:

site_id
stars_sum

1
...

2
...

3
...
Comment: @brombeer because this stars for 5 different thing
Comment: You are grouping by `site_id` and `comment_id` if you want the sum all starts for each site for all comments you'd probably need something like `SUM(stars.key1)+SUM(starts.key2)...` and not have the `comment_id` in the select at all
Answer: This is what you are looking for
Comment::selectRaw('comments.site_id as site_id, SUM(stars.key1) + SUM(stars.key2) + SUM(stars.key3) + SUM(stars.key4) + SUM(stars.key5) as stars_sum');
    ->join('stars', 'comments.star_id', '=', 'stars.id')
    ->groupBy('site_id')
    ->orderByDesc('stars_sum');

Comment: please add an explanation how this code solve the question

How to get ordered this sql query


adding " in abbrev for emacs

Question: How can I add a " in abbrev mode.
("stdce" "std::cout << " "<< std::endl;")
The " is not added but the line finishes after that
and i tried /" \" but that wont work
Comment: how do i close the question ?
Answer: never mind,
it worked.
I used \" and it worked fine. May be I didn't upload it when I tried before.

adding " in abbrev for emacs


Iniciar uma função no click e parar a mesma ao clicar novamente?

Question: Inicialmente o background do circulo deve ser branco.Quando clicar no circulo executar em loop a função mudaCor e quando clicar novamente deixar o background do circulo branco parando a função mudaCor. Como fazer isso?
//o círculo se movimenta com as teclas a, w, s, d, mas não consigo executar os eventos acima.
segue o código completo:

//----VARIÁVEIS----//
var dx;
var dy;
var px;
var py;
var vel;
var anima;
var ang;
var jog;
var skin;
var rotacao;
var tecla;
var tmp;
var tmpCor;
//-----------------//

function inicia(){
   dx = 0;
   dy = 0;
   px = 0;
   py = 0;
   vel = 5;
   ang = 0;
   rotacao = false;
   estadoCor = false;

   jog = document.getElementById("jog");
   skin = document.getElementById("skin");

   skin.addEventListener("click",giraPara);
   skin.addEventListener("click",mudaCor);
   document.addEventListener("keydown",teclaDw);
   document.addEventListener("keyup",teclaUp);

   tmp = setInterval(enterFrame,5);

   tmpCor = setInterval(mudaCor,1000);

}

//---FUNÇÕES DE ROTAÇÃO DO JOG---//

function gira(){
    if(ang>360){
         ang = 0;
    }
    ang+=8;
    jog.style.transform="rotate("+ang+"deg)";
    anima = requestAnimationFrame(gira);
}

function giraPara(){
   if(!rotacao){
      rotacao = true;
      anima = requestAnimationFrame(gira);
   }else if(rotacao){
      rotacao = false;
      cancelAnimationFrame(anima);
   }

}

//-------------------------------//

//---FUNÇÕES DE MOVIMENTO DO JOG---//

//Teclas --> a=65, w=87, d=68, s=83

function teclaDw(){
   tecla = event.keyCode;

   if(tecla==65){
      dx = -1;
   }else if(tecla==87){
      dy = -1;
   }else if(tecla==68){
      dx = 1;
   }else if(tecla==83){
      dy = 1;
   }
}

function teclaUp(){
   tecla = event.keyCode;

   if(tecla==65){
      dx = 0;
   }else if(tecla==87){
      dy = 0;
   }else if(tecla==68){
      dx = 0;
   }else if(tecla==83){
      dy = 0;
   }
}

function enterFrame(){
   px+= (dx*vel);
   py+= (dy*vel);

   jog.style.left = px + "px";
   jog.style.top = py + "px";
}

//----------------------------------//

//---FUNÇÃO DE CORES---//

function mudaCor(){
   var r = Math.floor(Math.random()*255);
   var g = Math.floor(Math.random()*255);
   var b = Math.floor(Math.random()*255);

   skin.style.backgroundColor= "rgb("+r+","+g+","+b+")";
}

window.addEventListener("load",inicia);
#jog{
     width: 100px;
     height: 100px;
     border: 1px solid #000;
     position: absolute;
     top: 0px;
     left: 0px;
     background-color: #f00;
     display: flex;
}

#skin{
     width: 100px;
     height: 100px;
     border: 2px solid #000;
     background-color: #fff;
     border-radius: 50%;
     margin-left: -1px;
     margin-top: -2px;
     align-self: auto;
     cursor: pointer;
}

Answer: Tem que cancelar o setInterval tmpCor ao clicar (veja comentário no código). Você usa clearInterval() para isso:
clearInterval(tmpCor);

Agora o tmpCor = setInterval(mudaCor,1000); deve ser iniciado dentro da função giraPara() quando a variável rotacao for false e cancelado quando for true:
function giraPara(){
    if(!rotacao){
       // inicia o temporizador
       tmpCor = setInterval(mudaCor,1000);
        rotacao = true;
        anima = requestAnimationFrame(gira);
    }else if(rotacao){
       // cancela o temporizador
      clearInterval(tmpCor);
        rotacao = false;
        cancelAnimationFrame(anima);
    }

}

E para voltar para o fundo branco (rgb(255, 255, 255)), verifique se a variável rotacao é true ou false fazendo um ternário nesta linha dentro da função mudaCor():
skin.style.backgroundColor= rotacao ?
    "rgb("+r+","+g+","+b+")" : "rgb(255, 255, 255)";
                 ↑                        ↑
           cor aleatória                branco

Isso porque ao cancelar o setInterval, o temporizador não é cancelado de imediato, ainda irá chamar a função uma última vez dentro do tempo que ele possui.
Então ficaria assim:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title> Title </title>

Vale observar que o else if na função giraPara() é redundante, pois se rotacao não for false, só pode ser true. Basta apenas um else:
function giraPara(){
    if(!rotacao){
       // inicia o temporizador
       tmpCor = setInterval(mudaCor,1000);
        rotacao = true;
        anima = requestAnimationFrame(gira);
    }else{
       // cancela o temporizador
      clearInterval(tmpCor);
        rotacao = false;
        cancelAnimationFrame(anima);
    }

}


Formula for the area of the interior of a closed contour in the complex plane

Question: Let $\gamma \colon [a,b] \to \mathbb{C}$ be closed contour in the complex plane. What is the formula for the area of the interior $I(\gamma)$ of $\gamma$? My assumption is that it involves some kind of contour integral. If possible, please kindly show me a derivation and direct me to a resource where I can research this further. Many thanks.
Comment: Interior of a closed contour is  a very difficult concept. To make your intuitive idea of points inside the contour precise you have get into some deep topology. So there is no hope of finding  a formula for the areas enclosed by the contour in general. You will need what are called Jordan curves even to define points 'inside'  the contour.
Comment: @Zak1120: If you are also  mechanically inclined: https://en.wikipedia.org/wiki/Planimeter
Comment: @KaviRamaMurthy: sir, can one use a mechanical planimeter to find enclosed areas for curved topographies in 3D?
Answer: Note that applying Green formula for $\bar z dz$ we get that the area inside $\gamma$ (assuming the curve is simple and piecewise smooth say) is $\frac{1}{2i}\int_{\gamma}{\bar z }dz$
Answer: This does not differ from the case of a parametric curve $x=f(t),y=g(t)$, such that the area can be computed as
$$A=\oint x\,dy=-\oint y\,dx=\frac12\oint(x\,dy-y\,dx).$$
Noticing that $x\,dx+y\,dy$ is a total differential, which integrates to $0$, this explains the formula
$$\frac12\oint \bar z\,dz=iA.$$


Silverlight Navigation - how to override Back button behavior

Question: I'm trying to override the default behavior of the browser's back button in Silverlight (v4).
Each of my XAML pages has an ability to show options. I want these options to be hidden when the user presses the back button, or to move to the previous page if the options are not visible. The Silverlight Frame seems to set back and forward points whenever the user navigates to a page with a new QueryString. Is there any other way of implementing my scenario other than having to implement a querystring component for my ShowOptions property?
Answer: PhoneApplicationPage class has BackKeyPress event
<code>BackKeyPress += MainPage_BackKeyPress;

private void MainPage_BackKeyPress(object sender, CancelEventArgs e)
    {
        e.Cancel = true;
        // do whatever you want
    }
</code>


Rails: ActiveAdmin doesn't work with Friendly_id

Question: I have ActiveAdmin set up to manage the users on the site, and Friendly_id for readable urls. When I go to /admin/users, it throws this error:
Undefined method `per' for #<User::FriendlyIdActiveRecordRelation:0x007fdb61a38d30>

How friendly_id is set up in the user model:
class User < ActiveRecord::Base
  #...
  extend FriendlyId
  friendly_id :name, use: :slugged
end

The only resource I could find for the conflict between these 2 gems is this question ActiveRecord::ReadOnlyRecord when using ActiveAdmin and Friendly_id which seems like a different issue and the solution doesn't work in my case. Any suggestions on how to resolve this?
Answer: I was able to fix it this way:

Unless you use the :finders addon, you should modify your admin controllers for models that use FriendlyId with something similar to the following:

controller do
  def find_resource
    scoped_collection.friendly.find(params[:id])
  end
end

Answer: I figured out that it's actually not the problem with friendly_id but with will_paginate as mentioned here https://github.com/gregbell/active_admin/issues/670. Switching to kaminari for pagination solves the issue for me.
Answer: I also encountered this issue, and found that friendly_id overrides the to_param method, so just re-override it. it works for me.
ActiveAdmin.register User do
  before_filter do
    User.class_eval do
      def to_param
        id.to_s
      end
    end
  end
end


Weighted gamma Weibull distribution

Question: I want a formula of Gini's concentration ratio and the Lorenz concentration ratio  involving three parameters about gamma Weibull distribution.
I have formula about gamma distribution that contains only one parameter. but I want it for three parameters. For the gamma distribution,the Gini concentration ratio is
$ G= (Γ(α+1/2))/(√π Γ(α+1)) $.
Answer: The Gini coefficient of any distribution $F$ with mean $\alpha$ is
$$\frac{1}{\alpha}\int_{-\infty}^\infty F(x)\left(1-F(x)\right) dx.$$
The three-parameter Gamma family is the location-scale extension of the Gamma distribution.  That is, the location parameter $\mu$ and the scale parameter $\sigma\gt 0$ induce a new distribution
$$F_{\mu,\sigma}(z) = F\left(\frac{z-\mu}{\sigma}\right)$$
whose standard deviation has been multiplied by $\sigma$ and whose mean is $\sigma\alpha+\mu$.
Substitute $x = \frac{z-\mu}{\sigma}$ in the integral.  Noting that $dz = \sigma\, d\left(\frac{z-\mu}{\sigma}\right) = \sigma dx,$   it is immediate that the Gini coefficient of $F_{\mu,\sigma}$ is
$$\frac{1}{\sigma\alpha+\mu}\int_{-\infty}^\infty F_{\mu,\sigma}(z)\left(1-F_{\mu,\sigma}(z)\right) dz = \frac{\sigma \alpha}{\sigma\alpha+\mu}\left(\frac{1}{\alpha}\int_{-\infty}^\infty F(x)\left(1-F(x)\right) dx\right).$$
The parenthesized expression on the right hand side is the Gini coefficient of $F$.  This general result shows how the Gini coefficient responds to changes of location and scale.
For the Gamma distribution with shape parameter $\alpha$ the mean is $\alpha$ and its Gini coefficient is $1/(\alpha B(\alpha, 1/2))$ (equivalent to the expression in the question).  Therefore the Gini coefficient for the three-parameter version equals $$\frac{\sigma\alpha}{\sigma\alpha+\mu} \frac{1}{\alpha B(\alpha, 1/2)}$$
provided $\mu \ne -\alpha$.
Comment: I suppose Zahida need to find the Gini concentration ratio  of three parameter Gamma Weibull distribution instead of three parameter Gamma distribution.
Comment: @Azeem Thank you; I see why you would conjecture that this is what was requested. I addressed the Gamma distribution because (1) it, and not the Gamma-Weibull, has the "only one parameter" mentioned and (2) the question provides the correct Gini coefficient for that distribution, so I assumed *that* was the one that needed to be generalized to three parameters. Let's wait for Zahida to clarify which one is intended.

Weighted gamma Weibull distribution


How use Java ServiveLocator with One-Jar

Question: I'm packaging an application of mine in a single jar using the One-Jar tool:
http://one-jar.sourceforge.net/
It works nike, but I have a problem with a service implemented in a dependency module, which is implemented in a separate jar.
The module uses the standard Java ServiceLoader mechanism to provide its service i.e. the jar has a file META-INF/services/package.name.ServiceProviderClass which specifies the service concrete class to be instantiated.
BUT when this jar is embedded in the application "fat-jar", created by One-Jar, the the service it is NOT discovered by the service loader mechanism.
Any idea how to make it work?
Cheers,
Paolo
Answer: At the end I solved this problem by using Capsule packaging in place of One-jar
http://github.com/puniverse/capsule
Enjoy


Using Paid Fonts As Web Font

Question: My client want to use a paid font (Futura) on website. We will purchase Futura but i have a question. When i purchase the font, is it possible to convert it to webfont to use on my website? Or it's forbidden because of licenses ? Or are there another ways to use Futura on our website.
(I found a link for Futura Webfont, but i'm not sure is it what we are looking for.)
Comment: Stack Overflow is not a site for legal recommendations. We are all programmers- so most of us can't give you real legal advice. Perhaps you should contact the creators of Futura- they would probably give you the best advice.
Comment: This question appears to be off-topic because it is about legal advice.
Answer: After a few conversations , i decided to use TypeKit. When i purchase a TypeKit account, i'll be able to use Futura as a webfont without any license problem. So if you experience same problem with me, and looking for answer you can purchase a TypeKit , or you can purchase Web use license for your font from myfonts.com

Using Paid Fonts As Web Font


Errors compiling SDL2 code

Question: I'm trying to follow a SDL2 tutorial at Lazy Foo: http://lazyfoo.net/tutorials/SDL/01_hello_SDL/index2.php
I have done the tutorial and my window appears when the program is executed, even though I get a lot of compile errors when compiling the tutorial code. When I use the g++ compiler the errors are:
<code>g++ sdl -w -lSDL2

sdl:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/../../../../lib/crt1.o:(.rodata.cst4+0x0): first defined here
sdl: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/crtbegin.o:(.data+0x0): first defined here
sdl: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/../../../../lib/crti.o:(.fini+0x0): first defined here
sdl: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/../../../../lib/crt1.o:(.text+0x0): first defined here
sdl: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/../../../../lib/crti.o:(.init+0x0): first defined here
sdl: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/../../../../lib/crt1.o:(.data+0x0): first defined here
/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/crtend.o:(.tm_clone_table+0x0): multiple definition of `\__TMC_END__'
sdl:(.data+0x10): first defined here
/usr/bin/ld: error in sdl(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status
make: *** [Makefile:11: all] Error 1
</code>
I don't know what these compile errors mean or how to solve them. I tried using the gcc compiler but the same errors appear. Can someone help me learn how to properly compile SDL2 code? What is my mistake? My Makefile is as follows:
<code># CC specifies which compiler we're using
CC = g++

# C_FLAGS specifies addicional compiler flags
CFLAGS = -w -lSDL2

#TARGETS specifies source files to be compiled
TARGETS = sdl

all: $(TARGETS)
    $(CC) $(TARGETS) $(CFLAGS)

clean:
    rm -f $(TARGETS)
</code>
Comment: `#TARGETS specifies source files to be compiled` it actually doesn't, but specify the targets.
Comment: Do you have your own headers? Did you forget a header guard?
Comment: What is an `sdl` file that you're trying to link with libsdl? Where did it came from? Is a source code saved in that file? If so - it just asks for problems, and `-w` reassures compiler that you're actually want that problems.
Answer: I do not quite know what the error means, but it seems like you are linking wrong files while compiling.
Since you asked I can tell you how I compile C programs in Ubuntu 14.04 LTS.
(I only use text editor and terminal)
Here is the command:
<code>$gcc main.c -o outputfile -lSDL2_image -lSDL2_mixer \`sld2-config --cflags --libs`

-lSDL2_image: library for image handling
-lSDL2_mixer: library for audio handling
</code>

Errors compiling SDL2 code