How to model left-censored and right-truncated data on Stata?

Question: I have data that is left-censored and right-truncated.
I'd like to run a tobit or truncreg. Although, using tobiton Stata takes account both sides are censored or only one side is censored. Using truncreg takes account both sides are truncated or only one side is truncated.
Is there a way to deal with a data which is censored and truncated on Stata?
Comment: I think it would be beneficial if you edit your question to remove the "in Stata" part (though you could specify a preference for that) in favor of more software-agnostic solution. It would also be helpful if you gave examples of the sort of data that you have to deal with.
Answer: Edited substantially to reflect helpful suggestions.
Take a look at David Roodman's command cmp, which is described in the Stata Journal article here (though many features have been added since that came out).
I believe this would estimate a model in which the latent dependent variable is first truncated and then passes through a censoring process:
. webuse laborsup, clear

. sum fem_inc, detail // minimum female income is 10

                        Female income
-------------------------------------------------------------
      Percentiles      Smallest
 1%           10             10
 5%           10             10
10%           10             10       Obs                 500
25%           10             10       Sum of Wgt.         500

50%           10                      Mean           18.12979
                        Largest       Std. Dev.      12.70491
75%     23.20812       65.20599
90%     37.00847       66.28354       Variance       161.4148
95%     46.02529       72.50031       Skewness       1.788829
99%     59.69054        84.6134       Kurtosis        6.06882

.
. /* Left Censoring Only */
. tobit fem_inc kids male_educ, ll

Refining starting values:

Grid node 0:   log likelihood = -1324.0111

Fitting full model:

Iteration 0:   log likelihood = -1324.0111
Iteration 1:   log likelihood = -1214.6402
Iteration 2:   log likelihood = -1191.8252
Iteration 3:   log likelihood = -1188.6169
Iteration 4:   log likelihood = -1188.5826
Iteration 5:   log likelihood = -1188.5826

Tobit regression                                Number of obs     =        500
                                                   Uncensored     =        228
Limits: lower = 10                                 Left-censored  =        272
        upper = +inf                               Right-censored =          0

                                                LR chi2(2)        =      59.33
                                                Prob > chi2       =     0.0000
Log likelihood = -1188.5826                     Pseudo R2         =     0.0244

--------------------------------------------------------------------------------
       fem_inc |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
---------------+----------------------------------------------------------------
          kids |  -4.135792   .8287279    -4.99   0.000    -5.764026   -2.507558
     male_educ |  -2.553038   .4308611    -5.93   0.000    -3.399568   -1.706509
         _cons |   46.17639   5.368424     8.60   0.000     35.62884    56.72395
---------------+----------------------------------------------------------------
 var(e.fem_inc)|   469.4704   48.96169                      382.4891    576.2321
--------------------------------------------------------------------------------

. cmp (fem_inc = kids male_educ), indicators("cond(fem_inc>10, $cmp_cont, $cmp_left)") qui

Fitting individual models as starting point for full model fit.
Note: For programming reasons, these initial estimates may deviate from your specification.
      For exact fits of each equation alone, run cmp separately on each.

Fitting constants-only model for LR test of overall model fit.

Fitting full model.

Mixed-process regression                        Number of obs     =        500
                                                LR chi2(2)        =      59.33
Log likelihood = -1188.5826                     Prob > chi2       =     0.0000

------------------------------------------------------------------------------
     fem_inc |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
fem_inc      |
        kids |  -4.135794   .8287292    -4.99   0.000    -5.760073   -2.511514
   male_educ |   -2.55304   .4308618    -5.93   0.000    -3.397513   -1.708566
       _cons |    46.1764   5.368432     8.60   0.000     35.65447    56.69834
-------------+----------------------------------------------------------------
    /lnsig_1 |   3.075804   .0521458    58.98   0.000       2.9736    3.178008
-------------+----------------------------------------------------------------
       sig_1 |    21.6673   1.129859                      19.56222     23.9989
------------------------------------------------------------------------------

.
. /* Right Truncation Only */
. truncreg fem_inc kids male_educ, ul(55)
(note: 9 obs. truncated)

Fitting full model:

Iteration 0:   log likelihood = -1857.7549
Iteration 1:   log likelihood = -1857.7537
Iteration 2:   log likelihood = -1857.7537

Truncated regression
Limit:   lower =       -inf                     Number of obs =   =        491
         upper =         55                     Wald chi2(2)      =      43.90
Log likelihood = -1857.7537                     Prob > chi2       =     0.0000

------------------------------------------------------------------------------
     fem_inc |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
        kids |  -1.682383   .3556318    -4.73   0.000    -2.379408   -.9853573
   male_educ |  -.8728686   .1834869    -4.76   0.000    -1.232496   -.5132409
       _cons |   31.12295    2.38037    13.07   0.000     26.45751    35.78839
-------------+----------------------------------------------------------------
      /sigma |   10.66551   .3444767    30.96   0.000      9.99035    11.34067
------------------------------------------------------------------------------

. cmp (fem_inc = kids male_educ, truncpoints(. 55)), indicators($cmp_cont) qui

Fitting individual models as starting point for full model fit.
Note: For programming reasons, these initial estimates may deviate from your specification.
      For exact fits of each equation alone, run cmp separately on each.

Fitting constants-only model for LR test of overall model fit.

Fitting full model.

Mixed-process regression                        Number of obs     =        491
                                                LR chi2(2)        =      42.14
Log likelihood = -1857.7537                     Prob > chi2       =     0.0000

------------------------------------------------------------------------------
     fem_inc |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
fem_inc      |
        kids |  -1.682383   .3556318    -4.73   0.000    -2.379408   -.9853573
   male_educ |  -.8728686   .1834869    -4.76   0.000    -1.232496   -.5132409
       _cons |   31.12295   2.380369    13.07   0.000     26.45751    35.78839
-------------+----------------------------------------------------------------
    /lnsig_1 |   2.367015   .0322982    73.29   0.000     2.303712    2.430319
-------------+----------------------------------------------------------------
       sig_1 |   10.66551   .3444767                      10.01128     11.3625
------------------------------------------------------------------------------

.
. /* Both Censoring and Truncation */
. cmp (fem_inc = kids male_educ, truncpoints(. 55)), indicators("cond(fem_inc>10, $cmp_cont, $cmp_left)") qui

Fitting individual models as starting point for full model fit.
Note: For programming reasons, these initial estimates may deviate from your specification.
      For exact fits of each equation alone, run cmp separately on each.

Fitting constants-only model for LR test of overall model fit.

Fitting full model.

Mixed-process regression                        Number of obs     =        491
                                                LR chi2(2)        =      51.18
Log likelihood = -1118.6343                     Prob > chi2       =     0.0000

------------------------------------------------------------------------------
     fem_inc |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
fem_inc      |
        kids |  -4.367595   .9732673    -4.49   0.000    -6.275164   -2.460026
   male_educ |  -2.605114   .5150163    -5.06   0.000    -3.614527   -1.595701
       _cons |   47.26099   6.615904     7.14   0.000     34.29406    60.22793
-------------+----------------------------------------------------------------
    /lnsig_1 |    3.10493   .0756042    41.07   0.000     2.956748    3.253111
-------------+----------------------------------------------------------------
       sig_1 |   22.30766   1.686552                      19.23532    25.87071
------------------------------------------------------------------------------

. cmp (fem_inc = kids male_educ, truncpoints(. 55)), indicators("cond(fem_inc>10, cond(fem_inc > 55, $cmp_trunc, $cm
> p_cont), $cmp_left)") qui // deprecated way

Fitting individual models as starting point for full model fit.
Note: For programming reasons, these initial estimates may deviate from your specification.
      For exact fits of each equation alone, run cmp separately on each.

Fitting constants-only model for LR test of overall model fit.

Fitting full model.

Mixed-process regression                        Number of obs     =        491
                                                LR chi2(2)        =      51.18
Log likelihood = -1118.6343                     Prob > chi2       =     0.0000

------------------------------------------------------------------------------
     fem_inc |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
fem_inc      |
        kids |  -4.367595   .9732673    -4.49   0.000    -6.275164   -2.460026
   male_educ |  -2.605114   .5150163    -5.06   0.000    -3.614527   -1.595701
       _cons |   47.26099   6.615904     7.14   0.000     34.29406    60.22793
-------------+----------------------------------------------------------------
    /lnsig_1 |    3.10493   .0756042    41.07   0.000     2.956748    3.253111
-------------+----------------------------------------------------------------
       sig_1 |   22.30766   1.686552                      19.23532    25.87071
------------------------------------------------------------------------------

Code:
webuse laborsup, clear
sum fem_inc, detail // minimum female income is 10

/* Left Censoring Only */
tobit fem_inc kids male_educ, ll
cmp (fem_inc = kids male_educ), indicators("cond(fem_inc>10, $cmp_cont, $cmp_left)") qui

/* Right Truncation Only */
truncreg fem_inc kids male_educ, ul(55)
cmp (fem_inc = kids male_educ, truncpoints(. 55)), indicators($cmp_cont) qui

/* Both Censoring and Truncation */
cmp (fem_inc = kids male_educ, truncpoints(. 55)), indicators("cond(fem_inc>10, $cmp_cont, $cmp_left)") qui
cmp (fem_inc = kids male_educ, truncpoints(. 55)), indicators("cond(fem_inc>10, cond(fem_inc > 55, $cmp_trunc, $cmp_cont), $cmp_left)") qui // deprecated way

Comment: Your proposal involves censored data on both sides. What if the right-side of the data distribution is truncated instead and censored on the left-side of the distribution?


Set the header for web page so that IE doesn't cache the page but AKAMAI still does?

Question: I'm setting the headers for a web page to CacheControlMaxAge 900 secs. This works well with Akamai and all the browsers ignore this setting except IE which caches the page for 9 minutes.
What I want is to have only Akamai cache the page for 9 minutes and no caching done by the browser (IE this is the one we have troubles with).
Web server: IIS 7
Comment: How does Akamai work? Does it fetch your pages the normal way? Does it have a specific user agent string?
Comment: Akamai will look at the last modified date and if it's within the max age it will go back to the origin server and collect new content. Otherwise it will just render the stale content.
Answer: Akamai lets you separately set the Browser Cache Control Headers (how long before browser revisits an Akamai edge server for a file) and edge server Time To Live Rules (how long before the edge server revisits the origin for a file).
If what you want is for the browser to never cache and for the edge servers to refresh from your origin every 9 minutes, here's what you do:

Under Browser Cache Control Headers, choose "Add cache busting headers to cacheable content and remove the default Akamai caching headers". That'll put no-cache and no-store in your page headers.
Under Time To Live Rules, set the server TTL to 9 minutes.


Problem on angles

Question: In triangle ABC, AB = AC and angle BAC = 20. A point D lies on the side AB and AD = BC. Find angle BCD?
My construction involved drawing a line parallel to BC intersecting AC at E. However, I am still unable to link this to the known angles!
Hint please!
Comment: HINT: Construct an isosceles triangle $ADE$ with $\angle AED=20^\circ$
Comment: A further hint please! How do we solve this without using trigonometry...
Answer:
Let $\angle BCD=\theta$
If you apply sine rule in the $\Delta ADC$ you'll get :
$$\frac{AD}{\sin(80^\circ-\theta)}=\frac{DC}{\sin20^\circ}$$
And doing the same in the $\Delta BDC$ you'll get:
$$\frac{BC}{\sin(100^\circ-\theta)}=\frac{DC}{\sin80^\circ}$$
Dividing these two relations you get:
$$\frac{\sin(100^\circ-\theta)}{\sin(80^\circ-\theta)}=\frac{\sin80^\circ}{\sin20^\circ}$$
EDIT:I had time so I decided to add how I got the value of $\theta=70^\circ$
$$\sin20^\circ\sin(100^\circ-\theta)=\sin80^\circ\sin(80^\circ-\theta)$$
$$\sin20^\circ\sin(80^\circ+\theta)=\sin80^\circ\sin(80^\circ-\theta)$$
$$\sin20^\circ\sin80^\circ\cos\theta+\sin20^\circ\cos80^\circ\sin\theta=\sin^280^\circ\cos\theta-\sin80^\circ\cos80^\circ\sin\theta$$
Rearranging,
$$\tan\theta=\tan80^\circ{\sin80^\circ-\sin20^\circ \over \sin80^\circ+\sin20^\circ}$$
$$\tan\theta=\tan80^\circ{\cos50^\circ \sin30^\circ \over \sin50^\circ \cos30^\circ }$$
$$\tan\theta=\tan80^\circ\tan40^\circ\tan30^\circ$$
$$\tan\theta={\tan80^\circ\tan40^\circ\tan30^\circ\tan20^\circ\over \tan20^\circ}$$
Now just apply this identity with $x=20^\circ$:
$$\tan x\tan(60^\circ-x)\tan(60^\circ+x)=tan3x$$
$$\tan\theta={1\over \tan20^\circ}=\tan70^\circ$$
Comment: Was thinking of a non-trigonometric solution using the hint above!

Problem on angles


Como fazer funcionar o href que esta dentro da minha div com focus?

Question: Tenho uma lista que quando clicar em algum item ela recebe um focus e aparece uma div com informações. Uma dessas informações tem um link  mas quando clico nele, minha div fecha e não abre a página.
Segue o código...
HTML completo:

Como me cadastrar?

Para se cadastrar, Clique aqui
                Nós enviaremos um e-mail com as suas informações e se elas estiverem corretas, é só confirmar a aproveitar!

Como consigo fazer com que o href funcione quando clicar?
Comment: O que seria "link-clicavel"  dentro do href? não deveria ser o caminho de onde deseja chegar?
Comment: Exato! Coloquei um link avulso para mostrar que não funciona.
Comment: Pode colocar o código completo, dentro do local específico para os códigos ? <> não no {}
Comment: Post editado. o HTML fica assim msm.
Comment: Vê lá @Ikaro Pinheiro vê se te resolve...
Comment: funfou... Avisa ae se naum num consigo dormir...
Comment: hehe, deu certo sim, vlw mano.
Answer: Vê se é isso patrão:

li{
display:inline:block;
}
.faq-content-answer {
    display: none;
    position: absolute;

}

.faq-content-answer a {

    display: block;
}

.faq-content-answer a:hover {background-color: #f1f1f1}

li:hover .faq-content-answer {
    display: block;
}

Como me cadastrar?

Para se cadastrar, Clique aqui
                Nós enviaremos um e-mail com as suas informações e se elas estiverem corretas, é só confirmar a aproveitar!

Se gosta se adapta, GL ;)!
Answer: Seria algo como isso? Utilizando a biblioteca jQuery.

$('#div-clicavel').on('click', function() {
  window.location.href = "https://www.google.com/";
});

Clique Aqui

Comment: Não entendi o que quis dizer com "causar esse erro" esse código acima não contem erros.
Comment: A resposta é viável, mas a intenção é não causar esse erro, e a tag agir normalmente sobre a natureza dela.


What is the $\lim\limits_{x \rightarrow 0} \frac{f(x)}{g(x)}$

Question: Assume that $f(x)$ and $g(x)$ are both differentiable functions such that
$f(0) = g(0) = 0$ and $g'(0)$ does not equal $0$.
What is the $$\lim_{x\to0}\frac{f(x)}{g(x)}$$
in terms of $f(x)$, $g(x)$, $f'(x)$ and $g'(x)$.
Sidenote: Unable to use L'Hopital's rule
Answer: Well, this problem is setup for L'Hopital, so I guess what you need to do is run through its proof:
$$\lim_{x\to 0}\frac{f(x)}{g(x)}=\lim_{x\to 0}\frac{f(x)-f(0)}{g(x)-g(0)}=\lim_{x\to 0}\frac{\frac{f(x)-f(0)}{x}}{\frac{g(x)-g(0)}{x}}=\frac{\lim_{x\to 0}\frac{f(x)-f(0)}{x}}{\lim_{x\to 0}\frac{g(x)-g(0)}{x}}=\frac{f'(0)}{g'(0)}$$
Make sure you can justify why each equality holds!
Answer: Use one of the forms of the definition of derivative:
$$
f(x)=f'(0)\,x+e_1(x),\quad g(x)=g'(0)\,x+e_2(x)
$$
where
$$
\lim_{x\to0}\frac{e_1(x)}{x}=\lim_{x\to0}\frac{e_2(x)}{x}=?
$$
Answer: Hint:
$$
\frac{f(x)}{g(x)}=\frac{\frac{f(x)-f(0)}{x-0}}{\frac{g(x)-g(0)}{x-0}}
$$
for $x\neq0$ sufficiently close to $0$.
Answer: Note that
$$
\frac{f(x)}{g(x)}=\frac{\frac{f(x)-f(0)}{x}}{\frac{g(x)-g(0)}{x}},
$$
and
$$
\frac{f(x)-f(0)}{x}\to f'(0), \quad \frac{g(x)-g(0)}{x}\to g'(0).
$$
Hence
$$
\frac{f(x)}{g(x)}=\frac{\frac{f(x)-f(0)}{x}}{\frac{g(x)-g(0)}{x}}\to \frac{f'(0}{g'(0)}.
$$
Answer: The answer $\frac{f'(0)}{g'(0)}$ follows from the definition of the derivative. Rewrite $\frac{f(h)}{g(h)}$ as $\frac{\frac{f(h)-f(0)}{h}}{\frac{g(h)-g(0)}{h}}$.
That has been amply described in answers already. We look only at a a small technical issue. Everything is fine if $g(h)\ne 0$. But we need to make sure that there is an interval $(-\epsilon, \epsilon)$ such that if $h$ is in this interval and $h\ne 0$, then $g(h)\ne 0$.
Suppose to the contrary that there is a sequence $h_1, h_2, \dots$ of non-zero numbers with limit $0$ such that $g(h_i)=0$ for all $i$. Then for these $h_i$ we have $\frac{g(h_i)-g(0)}{h_i}=0$, contradicting the fact that $g'(0)\ne 0$.


ValueError - The annotation 'status' conflicts with a field on the model django

Question: I'm trying to perform a bit of complicated query in my rest api view so I can order my contacts in the right order, now as e4c5 suggested in my previous question I could do this Case annotation and build my custom annotation with CASE/WHEN and then use that in annotation in the order by, but now I'm getting ValueError at /api/sales/lead_contact/
The annotation 'status' conflicts with a field on the model so this is the custom annotation I'm trying to build so I can properly order contacts, one note is that I'm preforming this in rest view:
   class LeadContactViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        filter_date = self.request.query_params.get('filter_date', None)

        case_sql = LeadContact.objects.annotate(
            status=Case(
                When(status=LeadContactConstants.STATUS_CLIENT, then=Value('1')),
                When(status=LeadContactConstants.STATUS_QUALIFIED, then=Value('2')),
                When(status=LeadContactConstants.STATUS_CONTACTED, then=Value('3')),
                When(status=LeadContactConstants.STATUS_PRISTINE, then=Value('4')),
                default=Value('1'),
                output_field=CharField(),

            )
        ).values_list('status')

        if filter_date is not None:
            queryset = queryset.filter(next_action_date=filter_date).extra(select={'status': case_sql},
                                                                           order_by=['status'])

        return queryset

Model fields:
class LeadContact(models.Model):
    status = models.CharField(max_length=10,
  choices=LeadContactConstants.STATUSES, default=LeadContactConstants.STATUS_PRISTINE)

and the choices for this field:
class LeadContactConstants(object):
    STATUS_PRISTINE = "PRISTINE"
    STATUS_CONTACTED = "CONTACTED"
    STATUS_QUALIFIED = "QUALIFIED"
    STATUS_CLIENT = "CLIENT"

    STATUSES = ((STATUS_PRISTINE, "Virgin"),
                (STATUS_CONTACTED, "Contacted"),
                (STATUS_QUALIFIED, "Qualified"),
                (STATUS_CLIENT, "Client"))

Serializer class:
class LeadContactSerializer(serializers.ModelSerializer):
    account_handler = AccountHandlerSerializer()
    next_action_date = serializers.DateTimeField(format=settings.CUSTOM_DATE_FORMAT_NO_TIME)
    absolute_url = serializers.URLField(source='get_absolute_url')

    class Meta:
        model = LeadContact
        fields = (
            'pk', 'organization_name', 'sub_organization_name', 'serial_number', 'account_handler', 'status_text',
            'first_name', 'last_name', 'next_action_date', 'absolute_url', 'status_display_class'
        )
        depth = 1

Full Stack Trace:
Traceback:
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
  87.             return self.dispatch(request, *args, **kwargs)
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  466.             response = self.handle_exception(exc)
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  463.             response = handler(request, *args, **kwargs)
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/mixins.py" in list
  40.         queryset = self.filter_queryset(self.get_queryset())
File "/home/vagrant/vincluos/VincluCMSProject/vinclucms_sales/restapi/views/lead_contact_viewset.py" in get_queryset
  29.                 output_field=CharField(),
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/query.py" in annotate
  793.                                  "the model." % alias)

Exception Type: ValueError at /api/sales/lead_contact/
Exception Value: The annotation 'status' conflicts with a field on the model.

Comment: What's the reason you are doing this? It would be simpler to store your statuses as integers in the first place, you could still use the choices to render them as readable text.
Comment: add the full stack trace and the model please
Comment: But I would say that the error is self-explanatory - you can't give an annotation the same name as an existing field. So, call it something else.
Comment: Good point @DanielRoseman
Answer:
As you can read the error message "'status' conflicts with a field on the model",
here the error is telling you that LeadContact model already has a field status (you can see it on your model definition of LeadContact)
that's why you're not able to annotate.
Basically annotate tries to add a field to your queryset result in your case it is status as you have a model LeadContact with status field because of which you're not able to annotate.
The Solution is you have to the field name other then status and choices.
hope this helps.


TypeError: unsupported operand type(s) for |: 'tuple' and 'bool'

Question: I got strange error when I tried to use "|" operator in if with tuple.
#example
Myset = ((1, 3), (4, 6), (3, 1), (2, 2), (3, 5), (2, 4), (3, 3))
courd = (4,6)
if(courd[0] - 1 ,courd[1] - 1 in d ):
    isSafe = True # work as expected

but if I will try something like this:
if((courd[0] - 1 ,courd[1] - 1 in d) | 2==2 ): # or something else that involved "|"
    isSafe = True

I'm getting
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    if((courd[0] - 1 ,courd[1] - 1 in d )| (2 == 2)):
TypeError: unsupported operand type(s) for |: 'tuple' and 'bool'

Comment: Well, you have a `tuple` - `(courd[0] - 1 ,courd[1] - 1 in d)` and you're trying to bitwise or it with a `bool` `2==2` (which is `True`) - which isn't supported (what would it mean anyway) - what more is there to be said?
Comment: What do you intend for that to do?
Comment: I think I confused between bitwise or and logical or...
Answer: You need to use parens, as needed, like this
if((courd[0] - 1, courd[1] - 1) in d):
    pass

Now, it will create a tuple (courd[0] - 1, courd[1] - 1) and it will check if it is in d. In the next case,
if((courd[0] - 1, courd[1] - 1 in d) | 2 == 2):
    pass

(courd[0] - 1, courd[1] - 1 in d) will be evaluated first and that will create a tuple. And then 2 == 2 will be evaluated (since | has lower precedence than ==) to True, which is basically a boolean. So, you are effectively doing
tuple | boolean

That is why you are getting that error.
Note: | is called bitwise OR in Python. If you meant logical OR, you need to write it like this
if(((courd[0] - 1, courd[1] - 1) in d) or (2 == 2)):
    pass

Now, (courd[0] - 1, courd[1] - 1) will be evaluated first to create a tuple and then the tuple will be checked if it exists in d (this will return either True or False, a boolean) and then (2 == 2) will be evaluated which returns True. Now logical or would happily work with two booleans.
Comment: @OrHalimi [Bitwise Operators](https://wiki.python.org/moin/BitwiseOperators), [Logical Operators](https://docs.python.org/2/library/stdtypes.html#boolean-operations-and-or-not)
Comment: What the different between logical OR and bitwise OR? I know in c# there is a "|" operator that doesn't evaluated the expression and "||" operator that does (or the opposite, I don't remember in this hour). Is logical OR evaluated the expression?


How compute overall reliability based on two related (dependent) inter-rater reliability coefficients

Question: The Situation
In many disability programs, a physician, psychologist, or other health professional conducts an exam with the claimant. Although it's not easy, a research study could determine an inter-rater reliability estimate1 for these medical2 examinations.
After the medical exam, lay3 adjudicators review all relevant records, including questionnaires and statements from the claimant, along with the medical examiner's report, and apply regulatory standards to reach an administrative/legal decision regarding the disability claim. Researchers could conduct a study to estimate the inter-rater reliability for these adjudicative decisions.
As you can see, the medical examiner's report influences the adjudicative decision, at least to some extent. (In most systems, the examiner's report significantly influences adjudicative decisions.) Thus, the two inter-rater reliability estimates are not independent.
My Question
What is/are the best way(s) to calculate the overall reliability of such a disability determination process?
Brief Background
I'm asking this question because some organizations conduct research on the inter-rater reliability of the adjudicative decisions and describe the results as "the accuracy of our disability determination decisions". The unspoken assumption is that the inter-rater reliability of the medical examinations is 1.00.
Notes

I wasn't sure if "coefficient" would be a better term than "estimate".
Most disability programs refer to all exams as "medical" even though some are actually psychological, audiological, etc.
lay, adj. - Not of or belonging to a particular profession; nonprofessional.

Prior research
I searched SE-Math but found just one related thread: combined reliability
I reviewed the following texts/tutorials (not that I couldn't have missed something relevant).
Gwet, Kilem L. Handbook of Inter-Rater Reliability. 4th ed. Gaithersburg, MD: Advanced Analytics, 2014.
Khan Academy, Statistics and probability.
Stat Trek, Statistics and Probability.
Trochim, William M., James P. Donnelly, and Kanika Arora. Research Methods: The Essential Knowledge Base. 2nd ed. Boston: Cengage Learning, 2016.
Answer: I'm not a statistician, but here are some starting thoughts. I've made this into an answer rather than a comment due to its length.
Before you calculate anything, you need to model the situation. There is rarely a single, god-given model. Modeling requires making choices, and these choices are informed by the experience of subject experts.
Modeling I: Patients
You want to understand the inter-reliability of medical and adjucative examinations. It seems likely that this reliability is a function of the underlying medical condition,  as well as a host of other socio-economic factors. If you don't include this information in your model, you will get average estimates of inter-reliability that don't take into account the variance seen in different patient groups. It's up to you to decide what level of granularity to adopt.
Modeling II: Evaluations
Just as there are different ways of modeling the patient pool, there are different ways of modeling the evaluations. One possibility is binary: approve or deny claim. Binary outcomes make the most sense for the legal decisions. However, I'm imagining that the medical examiner's report contains more information, perhaps a value between $0$ and $5$ indicating the severity of the condition or their conviction for requesting approval.
Modeling III: Connections
What is the relationship between healthcare professionals and legal adjucators? Does an adjucator treat every healthcare professional's opinion equally? How many healthcare professionals does a given claimant see? Are they random?
A Simple Model
A model that is too complicated is impossible to use in practice, due to the lack of infinite data. Let me suggest the following simple model. Let $P$ be the set of patients. $P$ could contain all patients, or could be narrowed down to a group of patients with similar characteristics. Assuming every patient sees $d$ doctors, and each doctor gives a "yes-no" answer, we have a function $f: P \to \{0, 1, \cdots, d\}$ that records the total number of "approve" responses. Assume every patient has $n$ adjucators, we then have a function $g: \{0, 1, \cdots, d\} \to \{0, 1, \cdots, n\}$ that takes the total number of medical "approve" responses and outputs the total number of adjucator "approve" responses.
If you look at the variance of the function $g \circ f$, you get the total variance of the process over the set $P$. If you look at the variance of $f$, you get the total variance of the medical evaluations. Lastly, to get the variance of the legal adjucators for a fixed medical assessment, you need to take the variances of $g$ conditioned on particular outputs of $f$ (you can then average these quantities).
To my mind, variance is a good statistic to measure reliability. If the collections of patients in $P$ are all similar, an assumption of reliability would predict a fairly consistent medical and legal evaluation. The larger the variance of the various functions described in the prior paragraph, the more disagreement between medical and legal experts. Assuming patient homogeneity, this implies a lack of reliability.
Comment: Awesome! Thank you very much. - Mark


How to split json object extracted from mongodb using java

Question: I have stored some JSON objects in MongoDB collections and using Mongo jar and Java I did full text search, and I am extracting one of my DB fields using below code:
String tags2=dbo.getString("Tags");

Result:
[["pdf","java","c++"]["perl","pdf","c"]["java","c++"]]

My requirement is to split all the words and remove duplicates. I require the following output:
pdf
java
c++
c
perl

Can you please suggest a way to get this?
Comment: That isn't valid JSON. Are there definitely no commas between the sub-arrays?
Comment: I don't know what your schema looks like, but `distinct` may be a reasonable option. http://docs.mongodb.org/manual/reference/command/distinct/
Answer: As your JSON is invalid, you could parse your output using a regex pattern to extract the values. These can then be added to a Set in order to remove duplicates, e.g.:
final Pattern p = Pattern.compile("\"(.*?)\"");
final Matcher m = p.matcher(tags2);

final Set<String> unique = new HashSet<String>();
while (m.find()) {
    unique.add(m.group());
}

assert unique == ["perl", "java", "c", "c++", "pdf"];

You may need to use a different Set implementation if some kind of ordering is important to you.
Alternatively, if your JSON is valid you can simply do:
final String[][] result = new Gson().fromJson(tags2, String[][].class);

And then add the contents of result to a Set.
Answer: Various libraries such as GSON will help you to do that.
Example for ints:
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

Your example is solved by:
String tags2 = "[[\"pdf\",\"java\",\"c++\"],[\"perl\",\"pdf\",\"c\"],[\"java\",\"c++\"]]";
// added commas between the arrays to make sure the JSON is valid
// your code: String tags2=dbo.getString("Tags");
Set<String> elems = new HashSet<String>();
JsonElement rootJSonElement  = new JsonParser().parse(tags2);
for (JsonElement jsonElement : rootJSonElement.getAsJsonArray()) {
    for (JsonElement innerJsonElement : jsonElement.getAsJsonArray()) {
        elems.add(innerJsonElement.getAsString());
    }
}
System.out.println(elems);

Answer: Use like this in GSON
JsonArray finalResult = null;
JsonParser  parser = new JsonParser();
String tags2=dbo.getString("Tags");
JsonElement elem   = parser.parse(tags2);
finalResult = elem.getAsJsonArray();
for(int i=o;i<finalResult .size();i++)
{
//Get individual array and get the fields as String and store it anywhere
}

Comment: HI, thanks for the reply,but do i need to import any gson jars, because i am getting error at "elem"
Comment: The above code will not compile because `elem` has not been initialized yet. And yes you will need the GSON jar on your classpath
Comment: its working but i need to write this code in another for loop      for( Iterator  it = results2.iterator();it.hasNext();), so when i kept this code, for every iteration i am getting result, how can i get the tags for all results in a single string or json variable


OO way of adding base field definitions

Question: Is there any object oriented Drupal way to add a base field definition to an existing entity?
Of course I am familiar with hook_entity_base_field_info(), but I am trying to keep my .module file size to a minimum and I was wondering if there is a way to achieve that with a different approach.
I thought of decorating or extending the entity, but after some research, I stumbled upon these issues that suggest those two options aren't yet possible or elegant, as far as I understand.

Allow entities to be subclassed using "bundle classes"
Create a generic way to decorate Entity classes

Am I wrong in that?
Is there anyone that has had the same case and found a different approach?
Edit:
TL;DR answer is that trying to replace this specific hook, will cause more confusion, rather than improve code clarity.
Comment: Why did you pick this hook out of the hundreds of hooks in Drupal? This would be quite chaotic if you want to replace all hooks by OOP. The correct approach would be to change EntityFieldManager not to invoke Drupal hooks and instead dispatch Symfony events. But don't do this on your own. This only makes sense in a core effort, so that all modules use the same API.
Comment: Yeah, I see there is a trend in trying to replace hooks with events in core.. like the entity insert, update, presave, etc hooks. I guess then, trying to replace this specific hook with something else, would actually cause more harm and confusion, than clarity.
Answer: Without using any hook, it's not possible, since to change the class used for an entity, it's necessary to implement hook_entity_type_alter(), which is problematic to implement when more modules need to alter the entity definition, for example changing the same entity handler, or the entity class, for the same entity type.
Imagine two different modules that try to add two different fields to the User entity by replacing the entity class used for it. For example, the first module could use the following code.
/**
 * Implements hook_entity_type_alter().
 */
function login_id_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setClass(LoginIdUser::class);
}

namespace Drupal\login_id\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\Entity\User;

class LoginIdUser extends User {

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = parent::baseFieldDefinitions();

    $fields['login_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Login ID'))
      ->setDescription(t('The ID used for the login credentials.'))
      ->setRequired(TRUE)
      ->setConstraints([
        'LoginId' => [],
        'LoginIdUnique' => [],
    ]);

    $fields['name']->getItemDefinition()
      ->setClass('\\Drupal\\login_id\\LoginIdItem');

    return $fields;
  }

}

The second module could use the following code.
/**
 * Implements hook_entity_type_alter().
 */
function admin_email_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setClass(AdminEmailUser::class);
}

namespace Drupal\admin_email\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\Entity\User;

class AdminEmailUser extends User {

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = parent::baseFieldDefinitions();

    $fields['admin_mail'] = BaseFieldDefinition::create('email')
      ->setLabel(t('Admin email'))
      ->setDescription(t('The email used from administrator users to contact the user.'))
      ->setDefaultValue('')
      ->addConstraint('UserMailUnique')
      ->addConstraint('UserMailRequired')
      ->addConstraint('ProtectedUserField');

    return $fields;
  }

}

With two modules implementing that code, only a field would be added to the entity. To get both the entity fields, LoginIdUser should extend AdminEmailUser, which would mean that a module should have the other one as dependency.
This assumes that admin_email_entity_type_alter() is executed before login_id_entity_type_alter(). This is what normally happens when the hook execution order isn't altered by a hook_module_implements_alter() implementation, or when the weight associated to module isn't altered by a call to module_set_weight(). In the case login_id_entity_type_alter() is invoked before admin_email_entity_type_alter(), for example because a module implements hook_module_implements_alter() and changes the order of those hook implementations, AdminEmailUser should extend LoginIdUser.
Implementing hook_entity_base_field_info() allows to modules to add different fields without interfering with each other.
As side note, hooks can be placed in a file different from a .module file, which is automatically loaded from Drupal. Which files are loaded from Drupal when looking for hooks is influenced by hook_hook_info(). With the implementations of that hook done from Drupal core modules, the files Drupal core looks for are the following.

<module_name>.tokens.inc
<module_name>.views.inc

If you are interested in reducing the size of the .module file, implementing hook_hook_info() to tell Drupal where your module hooks are could be a way to achieve it.
Answer: You could override the class being used for the entity type, and add your base field definitions there.
For example, if you wanted to add a base field definition to the Node entity, you could do this:
namespace Drupal\[EXAMPLE]\entity;

use Drupal\node\Entity\Node as NodeBase;

class Node extends NodeBase {

  /**
   * {@inheritdoc}
   */
  public function baseFieldDefinitions() {
    $definitions = parent::baseFieldDefinitions();
    // Add your field definition here

    return $definitions;
  }

}

Then you would override the class used as the backend for nodes, overriding the default node class with your class that extends it:
/**
 * Implements hook_entity_type_alter().
 */
function HOOK_entity_type_alter(array &$entity_types) {
  $node = &$entity_types['node'];
  $node->setClass('Drupal\[EXAMPLE]\Entity\Node');
}

I would suggest that if you are creating a contributed module to be used across projects, you're better off using a hook to add your field definition. This method should only be used for projects in which you're able to control the inheritance/hierarchy of the objects backing an entity type.
Comment: Replacing the node class would make sense for a module which advertises to implement a new enhanced node with a whole set of new features so that it's clear if you install two of that kind there will be a conflict. But not for a module which just wants to add a base field.
Comment: Yes I thought of that as well and it would be ok to do this in your custom project's module etc, but would that not be bad to exist in a contrib module since it would not be compatible with other modules doing the same thing? Or do i get that wrong?
Comment: It could. If you found on your system that a different module had extended the Node object, you would then need to extend that instead if you wanted to maintain the changes made by that module. Of course if multiple modules did this, you'd run into issues. Hence hooks, which don't require overriding the Node class. It's really a matter of which best suits your needs and preferred architectural type.
Comment: That's a good point.

OO way of adding base field definitions


Mailgun and Laravel returning T_Double_Arrow error

Question: I am trying to get Mailgun to work as my email provider.
By adding the services.php page into app/config and filling in the credentials, I'm left with this:
<?php
'mailgun' => array(
    'domain' => 'domain.com',
    'secret' => 'key-removedforprivacy',
),

When I go to execute a Mail:: function, it returns this error:
syntax error, unexpected '=>' (T_DOUBLE_ARROW)
It relates to this line:
'mailgun' => array(
If I remove <?php, it actually gets past this step, but returns the error where it can't find the array with the domain and secret values.
I've copied the code from Laravel's website! Any help would be greatly appreciated.
Answer: What you have so far is not valid PHP (The interpreter is correct.  It's always correct.)
I think this is what you're trying to do
<?php
return array(
    'mailgun' => array(
        'domain' => 'domain.com',
        'secret' => 'key-removedforprivacy',
    ),
);


Make the user avatar picture mandatory

Question: In Drupal 7 is it please possible to enforce all new users to upload an avatar picture during the registration process? I.e. how to make the user picture field mandatory?
When I try to edit the registration form fields at /admin/config/people/accounts/fields there are no settings for the user picture, I only see it being an account widget:
Comment: Please switch your site to English when taking screenshots. It'll make it easier for us to understand what's the problem. fields can be set to be required, shouldn't be a problem.
Comment: @Mołot I have uploaded english screenshot. Please tell me, how to set the avatar field to required, I don't see any settings for this.
Answer: Sounds like you need the register with picture module
Comment: Thank you, I hope it works well tih Drupal 7.24 and will migrate the existing user avatars too...
Comment: No worries. I hope it does what you need.
Comment: Yep, I didn't know of this module. @AlexanderFarber , please let us know what happened, if it was a good solution. Regards
Answer: Can you use hook_form_alter.
UPDATE : this hook_form_alter must be put in a custom module, lets say mymodule
the location of this module will be sites/all/modules/mymodule.
In order to use dpm(), you need to install the Devel module.
Here you can have a tutorial, explaining the basics for creating a custom module.
In your case, this is going to be only .info file and a .module file.
The hook_form_alter should look like
/**
* Implements hook_form_alter().
*/
 function mymodule_form_alter(&$form, $form_state, $form_id) {
  drupal_set_message("Form ID is : " . $form_id);
  dpm($form,'form');
 }

A lot of nice snippets can be borrowed from here.
drupal forum . After that you can use dpm ($form, 'form');
And see exactly the construction.
Those forms use the Drupal 7 Form API construction mechanism. The idea would be to add '#required' => TRUE  to the corresponding image field.
I hope this helps in a way.
UPDATE: Do not forget to clear your caches(even twice) after enabling a module.
Otherwise, some hooks (but not all) will not be recognized. This problem only caused a lot of frustartion when working with Drupal.
Best regards !
Oleg
Comment: I will clarify it in the edited answer
Comment: IMPORTANT: In the permissions of Devel information, add anonymous user to see debug information.
Comment: I have installed the `devel` module on my Drupal 7.24 website and added the line `dpm ($form, 'form');` to the function `hook_form_alter` in the file `modules/system/system.api.php` but unfortunately I don't see any additional information in the browser, when registering as a new user?
Answer: I think you can add a new image field, called 'avatar' and mark it as required in the field's settings.
Comment: Yes I could do that (same as I added the field "gender" and "city" and made them mandatory), BUT: that image wouldn't be shown as user pic at the user profile page and in blog/forum comments. That is why I'd better would like to find out, how to to make the REAL avatar mandatory.
Answer: user picture field module allow you add an image field to user, and show it on user register form, after user register an account, this module will use the fid that upload by image field as user picture's fid.
Usage:
1, Add a image field to user, for example "field_user_avatar"
2,config this field,and make it show on user register form.
3,install this module, navigate to "admin/config/people/user_picture_field", here you can config the "Machine name of source field that used as user picture"

When user register an account, he/she upload an image through image
  field "field_user_avatar", this image will be used as user's
  picture(avatar).

Make the user avatar picture mandatory


Facebook integration "error occurred try again later"?

Question: I'm trying to connect my app with facebook. I created app on facebook and this is my code:
<code>private void CheckAuthorization()
        {
            string app_id = "appID";
            string app_secret = "appSecret";
            string scope = "publish_stream,manage_pages";

            if (Request["code"] == null)
            {
                Response.Redirect(string.Format(
                    "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                    app_id, Request.Url.AbsoluteUri, scope));
            }
            else
            {
                Dictionary<string, string> tokens = new Dictionary<string, string>();

                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                    app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string vals = reader.ReadToEnd();

                    foreach (string token in vals.Split('&'))
                    {
                        //meh.aspx?token1=steve&token2=jake&...
                        tokens.Add(token.Substring(0, token.IndexOf("=")),
                            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                }

                string access_token = tokens["access_token"];

                var client = new FacebookClient(access_token);

                client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
            }
        }
</code>
When page loads login Pop Up is shown. When i login with email of user who created facebook app everithing works perfect. But every other different login results in message "error occurred try again later". Can someone tell me where i m making mistake?
Answer: Make sure the application Sandbox Mode is set to "Off"


Como salvar data fornecida pelo usuário no MySQL?

Question: Tenho um form que possui um campo onde é inserido a data de nascimento do usuário, este campo possui um datepicker que já retorna a data no formato ano,mês,dia, esta data é acessada através de $_GET['birthdate'] seu formato é string, então meu questionamento é como inseri-la no banco de dados? Tenho que atribuir esta data a um objeto intermediário?
Comment: Acho que isto foi respondido provavelmente de várias formas diferentes: http://pt.stackoverflow.com/q/26968/101 http://pt.stackoverflow.com/q/40262/101 http://pt.stackoverflow.com/q/40731/101 http://pt.stackoverflow.com/search?q=php+formato+data
Comment: Olá bigown, verifiquei os links o que mais me preocupa é o formato da data que possui este formato: 1980/01/13, qual modificação deveria ser feita para inseri-la no mysql e como faria
Comment: Este é um dos formatos aceitos pelo MySQL, você está tendo algum problema? http://dev.mysql.com/doc/refman/5.6/en/date-and-time-literals.html
Comment: devo mudar para algum tipo especial do php ou posso inserir direto na forma string?
Answer: Seria assim:
$date = date("Y-m-d", strtotime($_GET['birthdate'])); //converte para tipo date
mysqli_query($conexao, "INSERT INTO tabela (birthday) VALUES ($date)");

Veja funcionando no ideonena medida do possível. E no repl.it. Também coloquei no GitHub para referência futura.
Documentação do MySQL sobre datas.
Documentação do strtotime().
Documentação do date().
Note que a string com data precisa estar em um formato minimamente reconhecível pelo PHP. Caso contrário ou falhará ou precisará fazer um parse mais completo para identificá-la.
Comment: Era esta modificação que procurava
Comment: É sempre bom checar o que o usuário está enviando, antes de salvar no banco. Sugiro uma olhada nas respostas [desta](http://stackoverflow.com/questions/19773418/regex-to-validate-date-in-php-using-format-as-yyyy-mm-dd) pergunta.


selecting certain elements in a list - python

Question: I am looking to edit elements in a list bar one element - I am wondering how to do so? I am making one element go up, the one selected, and the others to go down. I have worked out how to do the first bit, just not the second. Here is my code so far
score = [70,60,80]
action = ["one person off", 2, 200]

def take_action(score, action):
    x = action[1]
    if action[0] = "one person off":
        score[x] += 30

I am looking for 80 to go to 110 and the others to go down by 10 each.
Any help would be greatly appreciated!
Comment: Do you mean to add an `else:` part to the `if` statement with `score[x] -= 10` in it?
Comment: @mkrieger1 no, I want it to both happen, so want score[x] += 30 and the something underneath that would represent elements that are not score[x] going down by 10 - sorry new to stack overflow
Answer: You could implement the action as loop:
for i,s in enumerate(score):
    score[i] = s+30 if i == x else s-10

Comment: thank you very much! this has worked spot on!
Answer: You can use a list comprehension:
score = [value+30 if i==x else value-10 for i,value in enumerate(score)]

This will give you back a new list, with the xth element increased by 30 and the others decreased by 10.
In order to modify the list that was passed in (rather than creating a new local variable named score) you would need to perform the assignment slightly differently:
score[:] = [value+30 if i==x else value-10 for i,value in enumerate(score)]

Comment: This will not update the score variable passed as parameter because it creates a new list in a local variable (also named score).
Comment: @AlainT. Ah, you're correct. I was assuming there was a return that wasn't shown, but that may be a bad assumption.
Comment: you could assign `score[:] = ...` instead and it would work.


Elementary derivation of the Taylor series of $\sin x$ that might have been devised by Madhava of Sangamagrama

Question: I can derive the Taylor series expansion of $\sin x$ by the Taylor's theorem.
But what is an elementary approach to derive this series?
I mean the way Madhava of Sangamagrama (c.1340–c.1425) or his contemporaries had possibly derived.
Comment: I searched google and found this

https://pdfs.semanticscholar.org/5cb2/4ef31a09a66625a26a74de59273dff5bb232.pdf
Comment: I highly recommend The Mathematics of the Heavens and the Earth The Early History of Trigonometry https://press.princeton.edu/titles/8956.html
Answer: I suppose, Madhava of Sangamagrama had enough of calculus available to know what we would write as $\frac {\mathrm d}{\mathrm dx}\sin x=\cos x$ and $\frac {\mathrm d}{\mathrm dx}\cos x=\sin x$, hence $\frac {\mathrm d^2}{\mathrm dx^2}\sin x=-\sin x$ as well as $\frac {\mathrm d}{\mathrm dx}x^n=nx^{n-1}$. Then comparing coefficients of a series ansatz
$$\sin x=a_0+a_1x+a_2x^2+a_3x^3+a_4x^4+\ldots $$
with its second derivative together with the elementary observation that $a_0=0$ and $a_1=1$ (i.e., $\sin x\approx x$ for small $x$) directly leads to
$$\sin x=x-\frac16x^3+\frac1{120}x^5\mp\ldots $$
though the question of convergence may not have been dealt with rigorously (beyond justification by numerical evidence perhaps).
Comment: Comparing coefficients requires the knowledge of Taylor's theorem which he was perhaps unaware of. One may obtain the series of $e^x$ (by Binomial theorem) or, arctan (x) without any sort to Taylor's theorem. I was looking for similar approach.


Can't do ORDER BY with Summed Value

Question: An error occurred with MySQL query below:
SELECT Id, (
SUM( poskusi ) *3 + SUM( cas )
) AS totals
FROM igralci
GROUP BY totals
LIMIT 5

I want to sum up two columns and then I want to get top 5 result of the result. I wrote this code but it doesn't work at line GROUP BY totals. Any ideas?
Thank you for your time!
Comment: "Does not work" means exactly what? Do you get an error, the wrong result, ...? It would also be helpful to show your table definition.
Comment: Oh yeah, I get an error('Can't group on 'totals'). My table definition is:
CREATE TABLE igralci

(

Id int(11), PRIMARY KEY

poskusi int(11),

cas int(11),

);
Comment: Show some input data and the expected outcome.
Comment: Id| poskusi| cas

1| 1     | 32
2| 2     | 34
3| 5     | 42
4| 8     | 29
.
.
The expected outcome would be for each Id the summed "poskusi" and "cas" column and at the end would get top 5(the lowest 5) sums.
Comment: Are you trying `ORDER BY` (as mentioned in the title) or `GROUP BY` (as mentioned in the question itself)?
Answer: Try this one:
SELECT Id,(
SUM(poskusi) * 3 + SUM(cas)
) AS totals
FROM igralci
GROUP BY Id
LIMIT 5

You cannot use Alias in GROUP BY clause.
Comment: This only bring out the top 5 Id's. not the top 5 sums
Comment: Yes, it brings out the top 5 ID's with their corresponding sums.

Can't do ORDER BY with Summed Value


Qual a diferença entre AppCompatActivity e Activity?

Question:
Qual a diferença da AppCompatActivity para Activity ?
A partir de qual versão a AppCompatActivity foi adicionada ao Android?
Answer: A diferença reside em que a AppCompactActivity permite, recorrendo à support library, usar o ActionBar(introduzido na API level 11) em aplicações a partir da API level 7.
Após a revisão 22.1 a support library inclui também suporte ao material color palette, widget tinting e Toolbar.
A partir da revisão 24.2 a classe ActionBarActivity, que até aí servia para esse propósito, foi considerada obsoleta.
Assim, para que as aplicações que usam as facilidades atrás referidas possam correr na API level 7 ou superior, terá de fazer as suas Activities herdar de AppCompactActivity.
Em relação em qual versão a classe foi adicionada julgo que ela existe desde que a support library(v4) foi introduzida em Março de 2011. No entanto foi com a sua actualização na revisão 22.1(Abril de 2015) que ela passou a ser a classe base para as Activities utilizarem ActionBar em "modo de compatibilidade".


Precision vs. Accuracy when talking about MSE

Question: This is more of a semantic question. I'm working on translating a work from French to English related to statistics. In French, there is only 1 word as far as I can tell to describe both bias and variance, and that is 'précision'.
In English, there is 'accuracy' for essentially bias, and 'precision' when talking about variance.
Here, the author is talking about two estimators, one of which has always lower MSE than the other, and uses the word 'précis' in French. For English, would this be more 'accurate' or 'precise' when talking about MSE?
Answer: Note that French indeed has two words: biais and variance.
For your actual question, recall that MSE is composed of both bias and variance, via the bias-variance tradeoff and related decomposition. So if all we know is that one estimator has lower MSE than another one, we don't know whether this is due to lower bias or lower variance (i.e., higher precision).
I personally would not quibble overmuch and simply use "more accurate". Or "lower MSE" when precision is required (yes, pun intended).


RxJS Pause timer Observable

Question: I have done a small timer, with 3 buttons:
start
stop
pause/resume (which I haven't done yet)
here is my code so far:
class StopwatchWidgetComponent {
      private readonly _start$: Subject<void> = new Subject();
      private readonly _stop$: Subject<void> = new Subject();
      private readonly _paused$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
      readonly counter$: Observable<number>;

      constructor() {
        this.counter$ = this._start$.pipe(
          startWith(0), // trigger emission at launch
          switchMap(() => timer(0, 1000).pipe(
            takeUntil(this._stop$)
          ))
        );

        // Subscribe done later
      }

      start(): void {
        this._start$.next();
      }

      stop(): void {
        this._stop$.next();
      }

      togglePause(): void {
        this._paused$.next(!this._paused$.getValue());
      }
}

However, I didn't manage to use the _paused$ subject properly so far.
By looking at github, I found a few topics about this subject:
https://github.com/ReactiveX/rxjs/issues/1542
but I feel that in my case, I would need to get rid of the current timer observable, and trigger a new one starting from the value we stopped at when pausing (and thus having to store that value).
Any other operator could help me out here to not have to do that?
Answer: An Implementation:
I create a timer with observables a while back. Perhaps it will give you some insight?
How does this work? The custom observable creates a stream that outputs the number on the stopwatch and is controlled by a separate stream (Here called control$).
When control$ emits "START", the stopWatch starts, when it emits "STOP", the stopwatch stops, and when it emits "RESET" the stopwatch sets the counter back to zero. When control$ errors or completes, the stopwatch errors or completes.
Implemented with switchMap and Timer
function createStopwatch(control$: Observable<string>, interval = 1000): Observable<number>{
  return defer(() => {
    let toggle: boolean = false;
    let count: number = 0;

    const ticker = timer(0, interval).pipe(
      map(x => count++)
    );
    const end$ = of("END");

    return concat(
      control$,
      end$
    ).pipe(
      catchError(_ => end$),
      filter(control =>
        control === "START" ||
        control === "STOP" ||
        control === "RESET" ||
        control === "END"
      ),
      switchMap(control => {
        if(control === "START" && !toggle){
          toggle = true;
          return ticker;
        }else if(control === "STOP" && toggle){
          toggle = false;
          return EMPTY;
        }else if(control === "RESET"){
          count = 0;
          if(toggle){
            return ticker;
          }
        }
        return EMPTY;
      })
    );
  });
}

Create a stopwatch as an object
If the control stream is going to be a subject, this is a good way to create the stopwatch.
function getStopWatch(interval: number = 1000): {
  control$: Subject<string>,
  display$: Observable<number>
} {
  const control$ = new Subject<string>();
  return {
    control$,
    display$: createStopwatch(control$, interval)
  }
}

Stopwatch Object in Use:
const watch = getStopWatch();
watch.display$.subscribe(/*Numbers emitted here every interval once started by control$*/);
watch.control$.next("START");
watch.control$.next("STOP");
watch.control$.next("RESET");
// Completing the control cleans up everything
watch.control$.complete();

Create a stopwatch that gets a stream of DOM Events
createStopwatch(merge(
  fromEvent(startBtn, 'click').pipe(mapTo("START")),
  fromEvent(stopBtn, 'click').pipe(mapTo("STOP"))
  fromEvent(resetBtn, 'click').pipe(mapTo("RESET"))
)).subscribe(seconds => {
  secondsField.innerHTML  = seconds % 60;
  minuitesField.innerHTML = Math.floor(seconds / 60) % 60;
  hoursField.innerHTML    = Math.floor(seconds / 3600);
});

RxJS Pause timer Observable


Fedora Core 6 Migration

Question: I am at a loss as to what I should to for this server. I need it to run php5.3 and corresponding version of mysql.
I received a client today through work that is using Fedora core 6 running 10 very small websites on some very hodge podge setup. My original idea was just upgrade to php5.3. I have yum (installed 3.0.8) reconfigured for the fedora archive. The latest version of php it allows is 5.1.8. I am still relatively new to server setups and am nervous about wiping their server to upgrade it. Since it is about 6-8 years old I'm not sure if it will even support the newest version of fedora.
The server specs are:
<code>Parallels Plesk Panel version   9.5.4
Operating system    Linux 2.6.9-023stab048.4-smp
CPU GenuineIntel, Intel(R) Xeon(R)CPU E5335 @ 2.00GHz
(10gb disk space and 1gb of memory).
</code>
I use fedora for my personal server so I was a little familiar with it. I haven't done anything too extravagant. Is there a way I can escape this nightmare with installing php5.3 or do I need to migrate these sites to a new server?
Comment: Rebuild it from scratch on a modern operating system that will be supported for more than 13 months.
Comment: This is why you don't run Fedora (a desktop OS) on a server. Support ends quickly for it and development jumps to the next version. You should strongly persuade them to move to something like CentOS.
Comment: Another thing you need to be concerned about is Plesk. In my past work experience with Plesk, it was not friendly to performing upgrades outside the Plesk app and caused some issues. I'd get a VPS for their site (at least temporarily) or migrate your existing data & sites to a new machine with a server-grade OS and bring their site over.
Answer: Fedora Core 6 makes up RHEL5 (at least according to wikipedia). You can try adding repository IUS Community which provides latest php for RHEL which hopefully compatible with Fedora (RHEL5 in your case).
As for whether it'll be supported on newer OS or not, I believe it should be supported. Linux rarely breaks compatibility of older hardware (assuming you're not using a binary-only driver).
Though if I read kernel, ram, and cpu correctly, it looks like an OpenVZ (or similar) instance, not a real machine.

Fedora Core 6 Migration


Violated non-proportional hazards - Cox regression model of time-dependent covariable

Question: I have been reading a lot on Cross Validated for a while now, but this is my first post here. Thanks for all the help I've received!
I am currently working on a project where we are trying to estimate the effects of a drug on overall and disease-specific mortality. This is a prospective observational study, where patients are enrolled when they have a blood test, which happens at different time points. Patients are then followed until death, emigration, or the end of the study. To figure out if the drug impacts mortality, we have set up a Cox regression model where drug exposure is allowed to accumulate over time with the cumtdc function specified here.
The problem is that the proportional hazards assumption is severely violated - with p-values approaching 0 for most of the covariates. I am a beginner to this type of analysis and what I have read and tried so far is:

Splitting continuous variables (such as age) into categories, which did not make a difference.
Could interaction variables be helpful here - if so, how do I best implement them?
Would this analysis be better suited to be performed with an accelerated failure time model?
Is it possible that the analysis could be valid despite the non-proportional hazards? I am asking this since, intuitively, there are many individuals in the study (> 300 000) and many events (> 30 000), so even minimal violations might be registered as significant.

I am attaching the Schoenfeld plots with the respective p-values for the covariables.

I would be most appreciative of any suggestions to this problem. There seem to be many different approaches out there, making it a bit tricky to navigate for a beginner.
Thank you!
ADDITON TO ORGINAL QUESTION
These are the log hazards for the variables age and X. I have now attempted both restricted cubic splines and categorization without meaningful changes to the Schoenfeld residuals.

ADDITION 2 TO ORIGINAL QUESTION
The output from cox.zph:

The requested plots from cox.zph for A and age:
Answer: With a data set this large, you are facing a problem similar to that with normality testing: any large real-world data set will tend to show a statistically "significant" deviation from an ideal. You thus have to engage closely with the data, using your knowledge of the subject matter to evaluate whether any deviations from proportional hazards (PH) are large enough to matter. This answer addresses the problem in the PH context, with suggestions for some graphical evaluations and for further reading.
With respect to your data set, it looks to me like most of your predictors don't deviate very far from constant hazards over time. The apparently categorical predictors (the last 6) seem quite flat. The coefficient for predictor A does, however, seem to show a tendency to increase over time. There also seem to be more high-positive residuals for X at early times than at late times. You might want to evaluate those more closely, based on your understanding of the subject matter. With continuous predictors (as A and X seem to be), an improper transformation might be the underlying problem, if their values aren't linearly associated with log hazards. Flexible modeling of those predictors with restricted cubic splines might fix the problem.
With the risk of survivorship bias, modeling with time-dependent covariates as you are doing is tricky enough. Be extra cautious if you think that you also need to move to time-dependent coefficients as in the vignette that you cite. Be warned that if you use the time-transform formalism to express coefficients as a function of time, the cox.zph() function can't be used to evaluate PH. This answer describes that and some other things that you might need to consider when using recent versions of the R survival package.
Comment: Thank you so much for the great reply! I have attached another image showing the log hazard relationship between age and X. It actually seems to be age that is causing a lot of the problems with the non-proportional hazards. It does not help with restricted cubic splines or categorization - am I missing something here? It appears to be the older ages causing the problems, since restricting age to < 75 fixes the problem. Is this due to the non-linear effect of mortality on age or something else I have not thought of?
Comment: Two other things that would be good to see are the text output of R `survival::cox.zph` and the residual plots without the points, which may distort the scale.  You may also want to further check your accelerated failure time idea to see if residuals from e.g. a log-normal survival model are better behaved (noting that your Cox residuals may already be well behaved enough).  See my case study in parametric survival modeling for an example, [here](https://hbiostat.org/rms) - in the course notes.
Comment: @LarsB the information that Frank Harrell requested would help evaluate the Cox model, and do explore his suggestion about accelerated failure time models as an alternative. The "fix" of the Cox model by restricting age to <75 indicates that you might have found something of biological/clinical importance. Look at interactions of one or more of your predictors with age, or try a model stratified by age (again, potentially with an interaction of age strata with one or more predictors) to follow up on that.
Comment: Thanks, @FrankHarrell and EdM, for your suggestions. I have attached some of the requested plots and text output of the cox.zph function. Perhaps a way to proceed would be to use the SurvSplit function and interpret HRs for different time spans for the variable I am interested in.
Comment: For the plots it's best to combine the effects of the spline terms.  I think that `cox.zph` has a new option to do that easiily.
Comment: @LarsB note, for example, that the smoothed coefficient for `age` only goes from 0.9 to 1.1 over the entire time span. Yes, that trend is statistically significant with your very large number of events, but is it _practically_ significant? Similarly, the coefficient for `A` only goes from -0.05 to +0.05, which is pretty small in magnitude (in either direction) for a binary predictor. Splitting into different periods of time after study entry is a valid approach. The question is: do these differences over time really matter, based on the goals of your study? Also, have you tried AFT modeling?
Comment: @EdM, Thank you so much for this pragmatic comment. I do not believe this is clinically significant. However, I want to be sure that what I am doing is statistically valid. I will look into AFT further, which unfortunately takes a little while since I am still very new to these methods.
Answer: I have a very similar related question.
Not an expert, but based on what I've researched so far and what is highlighted on this page, here are some points that may be helpful in answer to your last question
Is it possible that the analysis could be valid despite the non-proportional hazards?

As others have mentioned, large sample size may be a factor leading to the violation of the statistical test of the PH assumption. As @EdM mentioned, it will depend on your context/knowledge of the subject as to whether the deviations matter.

From page 1461 of this paper

When the sample size is small, this method may lack power to detect deviations from PH; while for large sample sizes, hypothesis tests may be over sensitive to slight deviations from this assumption.

The answer to this question suggests that the effect of fitting a Cox model with non-proportional hazards is "slightly less power" which can be recovered with robust standard errors, leading to the hazard ratios being interpreted as the time-weighted average of the hazard ratio

This interesting paper (Why Test for Proportional Hazards?) was published recently highlighting that there are legitimate reasons to assume violation of PH, and that one of the effects is on the interpretation rather than invalidity of the results. They actually suggest that statistical testing of PH is unnecessary if it's expected that the hazard ratio varies over time. (I'd be interested to hear what others think of this paper)

In the section "How should hazard ratios be interpreted?" on page 1402

As a weighted average of the time-varying hazard ratios, the hazard ratio estimate from a Cox proportional hazards model is often used as a convenient summary of the treatment effect during the follow-up. However, a hazard ratio from a Cox model needs to be interpreted as a weighted average of the true hazard ratios over the entire follow-up period. The 95% confidence interval should be estimated using a valid method such as bootstrapping and also using inverse probability weighting to adjust for losses to follow-up.


A group of order $8$ has a subgroup of order $4$

Question: Let $G$ be a group of order $8$. Prove that there is a subgroup of order $4$.
I know that if $G$ is cyclic then there is such a subgroup (if $G=\langle a\rangle$ then the order of $\langle a^2\rangle$ is $4$). But how do I prove this when $G$ is not cyclic? Also, I know that $G$ has an element of order $2$, because the order of $G$ is even. I suspect that assuming all elements of $G$ are of order $2$ somehow leads to a contradiction but am unable to show it. Is this correct or is there a different approach that I'm missing? thanks
Comment: The group might have all elements of order $2$, but then it is abelian (standard exercise), and the result is easy.
Comment: A more general question is answered here: http://math.stackexchange.com/questions/306343/subgroups-of-order-p-and-pn-1-in-a-group-of-order-pn?
Comment: @GerryMyerson Though that requires quite a bit more than this special case.
Comment: @Tobias, yes, which is why I'm not suggesting closing this question as a duplicate. But if OP wants to see something a little more hefty, I've pointed to a place to look.
Answer: You already noted that if $G$ has an element of order $8$ or $4$ then we are done.
Thus we can assume all elements have order $2$ (except the identity element). Then $G$ is abelian (this is a standard exercise, and I am certain it has been asked on MSE several times).
Let $a$ and $b$ be distinct elements of order $2$. Now it is straightforward to check that $\{e,a,b,ab\}$ is a subgroup of order $4$ (where $e$ is the identity element of $G$).
Answer: If $G$ is abelian so according to the Fundamental theorem for finite abelian groups we have: $$G\cong~~~\mathbb Z_8,~~\mathbb Z_4\times\mathbb Z_2,~~\mathbb Z_2\times\mathbb Z_2\times\mathbb Z_2$$ So lets assume that $G$ is not abelian. If there is an element in $G$ which is of order $8$ then we have a contradiction. If all non trivial elements of $G$ be of order $2$ so again we have $G=\mathbb Z_2\times\mathbb Z_2\times\mathbb Z_2$ which is a new contradiction, so we at least know that there is an elemnt of order $4$. I think we can stop here cause you wanted to know that. For the next you can use the subgroup generated by $x$ to show that $G=\langle y,x\rangle$ in which $y\in G-\langle x\rangle$ and of course $$G\cong \text{Q}_8,~~\text{or}~~\text{D}_8$$
Comment: @amWhy: Yes Amy. What can I say about the event for my small job here? My English is not good as I can defend my self. :( Some one did the wrong job and someone else should pay the price. I think to myself I have been suggesting everyone I know here to be honest with policy but you see that I am a clueless victim. Sorry for saying these upsetting words but I don't have a tribune for saying it. I have just you to hear my stroy. Sorry Amy.
Comment: @BabakS.: Sorry that you are going through this! I cannot even understand what happened, how is it possible to lose 5k rep in a day? It just does not make sense and must be a bug of some kind! Hope it gets resolved and it is not likely not something you did my friend! as amWhy said, hang in there!
Comment: @amWhy: I am warned in a kind way. I don't know what happened because as I read somewhere in Meta, we cannot trace who downvote or upvote others. They think, I have another account and that is why I have more than 5k. Yes, I have and I told rob about it but that account was lost. I have nothing from that account. Even, I wanted rob to merge it for me. I have just 2 questions there. It is ridiculous for me having another active account just making plus.
Comment: @amWhy:Where will I reach by doing this? More than you or Brian?? Where? What benefit will be for me? ISI Papers? Noble Prize? Believe me, I want to devote all reputations. A real sale is on the way. Sorry my friend.
Comment: @BabakS. I defended your honor: I told Alexander Gruber that you are the most humble, gracious, and honest person that I know: and I said that with **all sincerity**. I think we all know you too well: I told him that you have had students who participate, and that I've **see you** suggest to them (at least, e.g., Flashdesign, that they accept others' answers...that you tend to answer them only when no one else has. I suspect that you've had an admiring student or two who enthusiastically upvoted some of your posts too eagerly, not knowing the consequences.
Comment: @amWhy: Thanks for all you have done for me. I wrote for Alexander the same pattern and he kindly explained the case. Thinking about the event take me to nothing. You touched my feelings, thanks again.
Comment: I also suggested Alexander contact me directly if he has any questions. I believe that you have been the victim of an admiring student or two...And I know all too well that it is **not** lost points that troubles you, but rather, your "honor": and that, my friend, has **not** suffered. Of **all** users at math.se, you rank #$1$ with respect to honor: one needs only to read your answers and your comments to agree with my ranking of your honor! ;-)
Answer: This is a direct consequence of the following theorem.
Let $G$ be a group of order $p^{n}$ for $p$ a prime. Then for each $m$ with $0 \leq m \leq n$, $G$ has a subgroup of order $p^{m}$.
The proof is here.
Comment: This is the result pointed to by Gerry Meyerson. The proof takes considerably more than is needed for this special case.
Answer: I would consider elements of different orders and take cases accordingly.
You already are happy with what to do if there is an element of order 8 (and hence the group is generated by this element and cyclic).
Next, if there is a generator of order four, there clearly can only be one other generator, and this must be of order two. If we have $a$ and $b$ of orders 2 and 4 respectively  you can easily check check what all the elements are, and it should be obvious what the subgroup of order 4 is.
Lastly, if you have a generator of order two, you could have another generator of order 4, but we have already considered this. The only other alternative is to have two more generators of order 2, which must commute (else the group they generate would be too large) and again, if you consider the abelian group generated by $a$, $b$ and $c$, all of order two, it should be clear how you can generate a group of order four.
Note that this is not the most elegant solution, but it is (probably) the most concrete. And please ask if anything is not clear.
Comment: When you say G is generated by a, b and c you mean G = {e, a, b, c, a*b, a*c, b*c...}?
Comment: "if there is an element of order four, there clearly can only be one other element" Huh? Surely, that's not what you meant to write.
Comment: If there is an element of order $4$, you are clearly done. And the fact that the elements of order $2$ will commute follows only once you use that all the elements have order $2$.
Comment: @GerryMyerson sorry, I meant to talk about generators, not elements. Thank you!
Comment: A group of order $8$ cannot have a generator of order $4$.
Comment: OK, that's better, BUT there's a group of order 8 that can be generated by two elements of order 4 but not by an element of order 4 and an element of order 2.
Comment: @TobiasKildetoft What is wrong with $\mathbb Z_2 \times \mathbb Z_4$?
Comment: That group has plenty of elements of order $4$, sure. None of them generate it.
Comment: @TobiasKildetoft so it is not generated by $(1,0)$ and $(0,1)$?
Comment: Sure. That does not make either of those elements generators.
Comment: @TobiasKildetoft I don't follow. These are two elements that generate the group but they are not generators? What is your definition of a generator?
Comment: A generator is an element which generates the group. So even though those two elements together generate the group, that does not mean either of them is by itself a generator.


How many Markov chains are there for 2 states in 1, 2 and 3 steps?

Question: wiki uses this example to illustrate Markov chains.

The probabilities of weather conditions (modeled as either rainy or
sunny), given the weather on the preceding day, can be represented by
a transition matrix:
${\displaystyle P={\begin{bmatrix}0.9&0.1\\0.5&0.5\end{bmatrix}}}$
The matrix P represents the weather model in which a sunny day is 90% likely to be followed by another sunny day, and a rainy day is 50% likely to be followed by another rainy day. The columns can be labelled "sunny" and "rainy", and the rows can be labelled in the same order.
The weather on day 1 is known to be sunny. This is represented by a vector in which the "sunny" entry is 100%, and the "rainy" entry is 0%:
${\displaystyle \mathbf {x} ^{(0)}={\begin{bmatrix}1&0\end{bmatrix}}}$

for day n + 1(Note: the original value on wiki is n, which seems to be incorrect)

${\mathbf  {x}}^{{(n)}}={\mathbf  {x}}^{{(0)}}P^{n}$

The superscript (n) is an index, and not an exponent.
In the particular case, the state space of the chain is {rainy , sunny}
how many Markov chains are there respectively on day1, day2 and day3?
for example, on day1
${\displaystyle \Pr(X_0=sunny) = 1,}$ ${\displaystyle \Pr(X_0=rainy) = 0,}$
how many Markov chains are there on day1, 1 or 2?
how many Markov chains are there on day2 and day3 respectively?
Comment: are you wanting to know how many sequence-permutations to expect depending on how long the chain is?
Comment: @ReneBt Yes. and how to compute how long. does day 1 count 1 or 0?
Comment: Your question is worded that day 1 is non-probabilistic, but would you always want to start the chain on a sunny day or will you sometimes start it on a rainy day with some probability of occurrence? That would influence how you count day 1 and determine possible permutations.
Comment: @ReneBt Your comments is very helpful! To make things unambiguous, I would like to have the chain always start with a sunny day (day 1 is non-probabilistic),  day 2 and next are probabilistic.
Answer: Let $\{X_n:n=0,1,2\ldots\}$ be a Markov chain with transition matrix $P$. Then the $(i,j)$-entry of $P$ is the probability of transitioning from state $i$ to state $j$ in $n$ steps:
$$
P_{ij} = \mathbb P(X_n = j\mid X_0 = i).
$$
Here we have
$$
P = \left(
\begin{array}{cc}
 \frac{9}{10} & \frac{1}{10} \\
 \frac{1}{2} & \frac{1}{2} \\
\end{array}
\right),\quad P^2 = \left(
\begin{array}{cc}
 \frac{43}{50} & \frac{7}{50} \\
 \frac{7}{10} & \frac{3}{10} \\
\end{array}
\right),
$$
and in general
$$
P^n = \left(
\begin{array}{cc}
 \frac{1}{6} \left(\left(\frac{2}{5}\right)^n+5\right) & \frac{1}{6} \left(1-\left(\frac{2}{5}\right)^n\right) \\
 \frac{5}{6} \left(1-\left(\frac{2}{5}\right)^n\right) & \frac{1}{3} \left(\frac{2}{5}\right)^{n-1}+\frac{1}{6} \\
\end{array}
\right),
$$
so that
$$
\lim_{n\to\infty} P^n = \begin{pmatrix}
\frac56&\frac16\\\frac56&\frac16.
\end{pmatrix}
$$
Hence $X_n$ has limiting distribution
$$
\lim_{n\to\infty} \mathbb P(X_n = j) = \begin{cases}\frac56,&j=\mathrm{sunny}\\
\frac16,&j=\mathrm{rainy}
\end{cases},
$$
independent of the distribution of $X_0$.


velocity template format

Question: I Have velocity template like this one :
<code>+-----------------------------------------------------------+-------------+-------------+-------------+-------------+
| $totalPel  Pelanggan                                      |    $totalBk |   $totalAdm |   $totalTag | $totalTotal |
+-----------------------------------------------------------+-------------+-------------+-------------+-------------+
</code>
When i put $totalPel -> 100, the result is :
<code>+-----------------------------------------------------------+-------------+-------------+-------------+-------------+
| 100  Pelanggan                                      |    $totalBk |   $totalAdm |   $totalTag | $totalTotal |
+-----------------------------------------------------------+-------------+-------------+-------------+-------------+
</code>
Actually I want to get the result like this :
<code>+-----------------------------------------------------------+-------------+-------------+-------------+-------------+
| 100        Pelanggan                                      |    $totalBk |   $totalAdm |   $totalTag | $totalTotal |
+-----------------------------------------------------------+-------------+-------------+-------------+-------------+
</code>
Anyone can show me how to make it?
I use this java code :
<code>Velocity.init();

VelocityContext context = new VelocityContext();
context.put("totalPel", 100);

Template template = Velocity.getTemplate("LaporanTagihan.txt");

StringWriter writer = new StringWriter();

template.merge(context, writer);

System.out.println(writer.toString());
</code>
Comment: I can't really understand what you want here... what's the difference? just more space? That's usually controlled in the template.
Comment: yes, I just want to automatic add space for the result. It's is useful when I put a lot of parameter :D
Answer: Pad your strings before adding them to your template.  See How can I pad a String in Java? for advice on how to do this.
Answer: You can either transform the value into a String and pad it, or you can simply add more space in your template, I believe velocity maintains whitespace that you define.

velocity template format


Apply a loop in JS between X and XX

Question: So I have been trying to think of how to explain this in a way that makes sense, but I will show you below, as it makes more sense.
I have this code that works fine but I want to shorten it down into a for each loop or something.
$('.holder1').on({
    click: function(){
    $('.box1').css({display: 'none'});
    $('.text1').css({display: 'block'});
    }
});

$('.holder2').on({
    click: function(){
    $('.box2').css({display: 'none'});
    $('.text2').css({display: 'block'});
    }
});

$('.holder3').on({
    click: function(){
    $('.box3').css({display: 'none'});
    $('.text3').css({display: 'block'});
    }
});

I have this going on up to 40+, and obviously this code is horrific.
Comment: You should consider adding a general class to all of them, so you only have one selector. If possible.
Comment: show some html, that will help to provide good answer
Comment: Agree with @gowri, your markup is important, please post it.
Answer: You can refactor the HTML code to use a common class and data attributes. Something like this:

Then you can have a single click handler for all classes:
$('.holder').on({
    click: function(){
        $('.' + $(this).data('box')).css({ display: 'none' });
        $('.' + $(this).data('text')).css({ display: 'block' });
    }
});

This avoids the needs for ugly loops to add multiple handlers and iterative id attributes, which always turns in to a maintenance nightmare.
Answer: To solve this problem it is possible to iterate over holder elements using jQuery Attribute Starts With selector (API docs):
$.each('[class^="holder"]', function(index, item) {
    $(item).on('click', function() {
        $('.box' + index).css({display: 'none'});
        $('.text' + index).css({display: 'block'});
    });
});

I would prefer using some common class, though, as Rory McCrossan pointed out in his answer.
Comment: @briosheje `^` selector means, All elements with a title attribute value starting with "holder"
Comment: +1 I missed to give a jQuery version of looping.  I like this
Comment: Sick marmelade, sir. Never seen a such beautiful way to do that. what does the "^" stand for after "class"?
Comment: @briosheje [name^="value"]  selects elements that have the specified attribute with a value beginning exactly with the given string.. read on at... http://api.jquery.com/attribute-starts-with-selector/
Comment: The caveat to this approach is if the `index` is not sequential.
Comment: yes, it is assumed, that blocks are ordered, otherwise it might be needed to extract current `index` manually
Answer: for (var i = 0; i< 40; i++) {
 $('.holder' + i ).on({
    click: function(){
    $('.box' + i).css({display: 'none'});
    $('.text' + i).css({display: 'block'});
    }
 });
}

or just add a common class and use it.
Answer: try this:
     use class .box and .text instead
  var holder = $(".holder1");
  for (var i = 2; i<= 40; i++) {
      holder.add($(".holder"+i));
 }
  $(holder).on(
   'click', function(){
    $('.box').css({display: 'none'});
    $('.text').css({display: 'block'});
   }
  });

Comment: The problem is `.box` and `.text1` change in each handler.
Answer: Use:
$("*[class^='holder']").on({
    click: function(){
        var id = $(this).attr("class").replace("holder","");
        $('.box'+id).css({display: 'none'});
        $('.text'+id).css({display: 'block'});
    }
});

Comment: `I have this going on up to 40+`
Answer: Assuming holders and boxes sit in their respective containers, like

a

b

c

d

a

b

c

d

you can get rid of box/text numbers altogether:
    $(".holder").click(function() {
        var n = $(this).index();
        $(".box").eq(n).show();
    });

This way it will be much easier to add new elements or change their order.

Apply a loop in JS between X and XX


Exibição da pesquisa no wordpress

Question: Fala amigos,
Gostaria de saber se tem algum modo de exibir a pesquisa feita em um site wordpress dessa forma:
Post = no formato "x", e, Página = no formato "y"
valeu!
Comment: Ficou meio confusa sua pergunta, consegue explicar um pouco melhor?
Comment: @DanielCosta man, assim.. Fiz uma pesquisa... a exibição é padrão para páginas e posts.
Eu quero que quando aparecer uma página do WP, apareça em retângulo. E quando for post quero que apareça em quadrado...

Ai exemplo, pesquisei sobre "Arroz"... Tenho 2 páginas que falam sobre o arroz e 3 posts que tbm falam sobre o arroz...

A exibição que eu quero é a seguinte...

Arroz - Retângulo, Arroz - Retângulo, Arroz - Quadrado, Arroz - Quadrado, Arroz - Quadrado.

Não sei se da para fazer isso com um simples "if"...
If(página){ Exibição Retângulo}
else if(post){ Exibição Quadrada}
Answer: No arquivo search.php do seu tema no WordPress, você pode utilizar o método get_post_type(); para verificar o tipo de conteúdo do post.
Exemplo:
<?php
get_header();
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        //verifica se é post ou página
        if (get_post_type() == "page") {
            //exibe título da página em um retangulo
            echo "
";
            the_title();
            echo "
";
        }
        else if (get_post_type() == "post") {
            //exibe título do post em um quadrado
            echo "
";
            the_title();
            echo "
";
        }
    }
}

Comment: Vlw amigo! É mais simples do que eu imaginava.

Exibição da pesquisa no wordpress


Real Time search with API results using React Native

Question: I'm following a tutorial to create my first React Native app. I'm using the search API from themoviedb.org and I want to refresh the results each time the user changes their input (instead of refreshing when they click a Search button.)
I'm using TextInput and onChangeText but if the user types too fast, there is a problem. I've found a possible solution is to use a "debounce" but I don't really know how to use it in my code.
Here is my code:
//Search.js

import React from 'react'
import { StyleSheet, View, TextInput, Button, FlatList, Text, ActivityIndicator } from 'react-native'

import FilmItem from './FilmItem'
import { getFilmsFromApiWithSearchedText} from '../API/TMDBApi'
import { debounce } from 'lodash'

class Search extends React.Component {

constructor(props){
  super(props)
  this.page = 0
  this.totalPages = 0
  this.state = { films: [], isLoading: false, searchedText:""}
}

_loadFilms(){
  if(this.state.searchedText.length > 0){
    this.setState({isLoading:true})
    console.log(this.state.films)
    getFilmsFromApiWithSearchedText(this.state.searchedText, this.page+1).then(data => {
      this.page = data.page
      this.totalPages = data.total_pages
      this.setState({ films: [...this.state.films, ...data.results]
        , isLoading:false})
    })
  }
}

_displayLoading(){
  if(this.state.isLoading){
    return (
      <View style={styles.loading_container}>
        <ActivityIndicator size='large' color='blue'/>
      </View>
    )
  }
}

_searchFilms(text){
    this.page = 0
    this.totalPages = 0
    this.setState({
      films:[], searchedText:text
    }, () => {
      this._loadFilms()
    })
}

_displayDetailForFilm = (idFilm) => {
  console.log("Display film with id " + idFilm)
  this.props.navigation.navigate("FilmDetail", {idFilm: idFilm})
}

/*_searchTextInputChanged(text){
  this.searchedText = text
}*/

render(){
  return (
    <View style={styles.main_container}>
      <TextInput style={styles.textinput}
      placeholder = 'titre du film'
      onChangeText={(text) => this._searchFilms(text)}
      />
      <Button title = 'Rechercher' /*onPress={()=>this._loadFilms()}*//>
      {this._displayLoading()}
      <FlatList
        data={this.state.films}
        keyExtractor={item => item.id.toString()}
        renderItem={({item}) => <FilmItem film={item} displayDetailForFilm={this._displayDetailForFilm} />}
        onEndReachedThreshold={0.5}
        onEndReached={() => {
          if(this.page < this.totalPages){
            this._loadFilms()
          }
        }}
      />
    </View>
  )
}

Answer: You can try with a timer to wait for user finished to type. Try something like
constructor(props){
    super(props)

    this.searchTimer = null
}

setSearchTimer(text){
    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
        this._searchFilms(text)
    }, 1000);
}

...

<TextInput style={styles.textinput}
    placeholder = 'titre du film'
    onChangeText={(text) => this.setSearchTimer(text)}
/>


Present Facebook likes (shares) in one page

Question: My site includes a search results page in which basic information about searched places (say hotels) is shown:

Place 1:
Address YYY
Availabilty 3
Price: 999$

Place 2:
Address YXV
Availabilty 1
Price: 99$

etc.
Clicking on a place renders a detailed info page.
Within the detailed info page there are Facebook Like and G+ buttons that users click on (and the info about how many likes the place got so far is also shown).
My question is:
Can I show (only show and not allow clicks) the number of likes from the detailed info page in the search page for each respective place.
The wanted result is:

Place 1:
667 Likes, 23 G+ <-this info from Place 1 detailed info page
Address YYY
Availabilty 3
Price: 999$

Place 2:
777 Likes, 44 G+ <-this info from Place 2 detailed info page
Address YXV
Availabilty 1
Price: 99$

I developed in VS, .NET MVC.
I'd appreciate a detailed answer.
Thnx.
Comment: Since this doesn't look (at least to me) like you did any proper research on your own before asking, I suggest you start with something like https://www.google.com/search?q=facebook+api+how+to+get+number+of+page+likes
Comment: @CBroe Unfortunately, I was not able to find a complete answer for my specific problem although I did research beforehand. An "answer" like yours did not help and I guess it deterred others from commenting.
Answer: I could not find a complete answer for my EXACT problem (working in MVC) so I am posting my solution which works great by the way.
The View renders outer divs, one for each place containing some data. Each dive is actually a form. I place the input and counter div inside the outer one:

  <input class="likes1" type="hidden" id="institueId" value="SpecificPlaceUrl" data-link="" />

Then this function countFacebookLikes, which should be preferably deferred till the page fully loads, loops through the divs
function countFacebookLikes() {
    $('.likes2').each(function () {
        var $currentForm = $(this).closest('.enterFormClass');
        var token = 'yyyyyyyyyyy|xxxxxxxxxxxx',
            resultsId = $('.likes1',$currentForm).val(),
            urlName = resultsId;

        $.ajax({
            url: 'https://graph.facebook.com/v2.7',
            dataType: 'jsonp',
            type: 'GET',
            data: { access_token: token, id: urlName },
            success: function (data) {
                if (data !=undefined && data.share != undefined)
                {
                    $('#results' + resultsId).html('' + data.share.share_count + '  ' + '' + '  ' + '' + '');
                }
            }
        });
    });
};

1) One can change Facebook data param to whatever he/she wants to count - total, shares etc.
2) For multiple urls there are q&a in stackoverflow and elsewhere that use https://graph.facebook.com/?ids=url1,url2 etc. this may be useful for some but for me it wasn't working due to the large number of urls and the work for reconstructing specific url strings each time.