Alinhar botão no centro wordpress

Question: Já tentei um monte de coisas e não consigo de jeito nenhum alinhar ao centro esse botão de "esqueceu a senha" do wordpress da página de login.
wp-login completo: https://pastebin.com/7RBesXpG

    <?php if ( ! $interim_login ) { ?>

<?php if ( ! isset( $_GET['checkemail'] ) || ! in_array( $_GET['checkemail'], array( 'confirm', 'newpass' ) ) ) :
    if ( get_option( 'users_can_register' ) ) :
        $registration_url = sprintf( '%s', esc_url( wp_registration_url() ), __( 'Register' ) );

        /** This filter is documented in wp-includes/general-template.php */
        echo apply_filters( 'register', $registration_url );

        echo esc_html( $login_link_separator );
    endif;
    ?>
    <a style="color: #FFFFFF" href="<?php echo esc_url( wp_lostpassword_url() ); ?>"><?php _e( 'Lost your password?' ); ?>
<?php endif; ?>

<?php } ?>

Comment: Tente: `.button .button-primary .button-large { text-align:center !important; }` Está meio difícil para entender o que vc quer... Tem como postar uma imagem de onde o BTN está e de onde vc queria que ficasse?
Comment: Não funcionou, adicionei uma imagem.
Comment: wp-login completo: https://pastebin.com/7RBesXpG
Answer: Na linha:

Acrescente

 // Bootstrap 4

Ou

 // Bootstrap 3

Mas talvez você deverá inserir as classes mx-auto .text-center (Bootstrap 4) ou .center-block .text-center (Bootstrap 3) no container e não no parágrafo
Comment: Não funcionou, adicionei uma imagem.
Comment: wp-login completo: https://pastebin.com/7RBesXpG
Comment: Tem como você informar o link da página pra que eu possa testar o alinhamento no container, parte do código não me ajuda muito a te ajudar.
Comment: vlw pela força, mas o camarada ali chegou primeiro rsrsrs.. mas vlww mesmo abraço
Comment: O importante é que deu certo.
Answer: Vc tem duas opções, a primeira é trabalhando com essa div

Nela coloque assim
.mx-auto {
    display: flex;
    justify-content: center;
}

Opção número 2, trabalhar direto no botão e deixar ele do tamanho do container, dessa forma
.wp-core-ui .button-group.button-large .button, .wp-core-ui .button.button-large {
    height: 30px;
    line-height: 28px;
    padding: 0 12px 2px;
    width: 100%;
    text-align: center;
}

OBS: Como essa mesma classe pode se repetir em outros elementos de outras página considere "encapsular" as classes só para o login tipo .login .mx-auto {estilos...}
OBS2: Das duas forma fica responsivo sem bugs
Comment: muuuiitoo obrigado, funcionou, preferi usar sua segunda opção, muito obrigado mesmo.
Comment: Daniel inclusive eu estava vendo aqui e a primeira opção não estou achando a classe .mx-auto  novamente rss... queria testar nela uma classes, Mas de qualquer forma que bom que resolveu!

Alinhar botão no centro wordpress


Vectors: Why $a_1\mathbf{x}+b_1\mathbf{y}+c_1\mathbf{z}=a_2\mathbf{x}+b_2\mathbf{y}+c_2\mathbf{z}\implies a_1=b_1$ etc?

Question: I was solving this problem earlier:
Points $X$, $Y$ and $Z$ in have the (three dimensional) coordinate vectors $\bf{x},\bf{y},\bf{z}$ respectively. Prove that the lines joining the vertices of $\triangle XYZ$ to the midpoints of the opposite sides are concurrent.
My problem is that at some point in the problem I ended up with equations of the form $a_1\mathbf{x}+b_1\mathbf{y}+c_1\mathbf{z}=a_2\mathbf{x}+b_2\mathbf{y}+c_2\mathbf{z}$ and the only way I could progress was by assuming that this implies $a_1=a_2$, $b_1=b_2$, $c_1=c_2$. Unfortunately I don't clearly see why this is and I only assumed it was true to solve the problem. (I indeed got the correct answer of the vectors passing through the same point $\frac{1}{3}(\bf{x+y+z})$ (and hence being concurrent at this point).)
One way I tried to justify this (the equalities just mentioned) is by assuming (wlog) that the vectors x,y,z are not coplanar, and then this would mean that they form a basis for 3D space (according to my textbook), which means the above equalities do indeed hold. The reason I gave for being able to assume wlog that the vectors are not coplanar is that whether they are ccoplanar or not does not affect the conclusion of the problem, which is simply concerned with proving concurrency of certain lines. In other words, if the position vectors are coplanar then rotating the triangle so that the position vectors are no longer coplanar doesn't affect the triangle and therefore doesn't affect the conclusion of the problem.
Is this reasoning correct, or is there another reason why the equalities hold?
Thanks
Edit: My question is regarding the title, please ignore the centroid problem as I only mentioned it for context.
Edit2: Here is how I arrived at the equation. First I let the midpoints of the size opposite $X$ be $X_1$, and similarly for $Y,Z$. Clearly, $\vec X_1=\frac{\mathbf{y}+\mathbf{z}}{2}$. The line $XX_1$ has direction $$\vec{XX_1}=\vec X_1-\vec X=\frac{\mathbf{y}+\mathbf{z}}{2}-\mathbb{x}=\frac{\mathbf{y}+\mathbf{z}-2\mathbf{x}}{2}$$ so its equation is $$\mathbf{r_x}=\mathbf{x}+a(\mathbf{y}+\mathbf{z}-2\mathbf{x})=(1-2a)\mathbf{x}+a\mathbf{y}+a\mathbf{z}.$$ By symmetry $$\mathbf{r_y}=b\mathbf{x}+(1-2b)\mathbf{y}+b\mathbf{z},\quad \mathbf{r_z}=c\mathbf{x}+c\mathbf{y}+(1-2c)\mathbf{z}.$$ We want the point where these lines meet, and for this we only need to calculate the point where a pair of them meet and then verify that the third line crosses that point. So we have to solve $$(1-2a)\mathbf{x}+a\mathbf{y}+a\mathbf{z}=b\mathbf{x}+(1-2b)\mathbf{y}+b\mathbf{z}$$ and here is where I met my problem, but as I said I just assumed (and tried to justify this assumption using the "base vectors" reasoning in the main post) that $$1-2a=b,\quad a=1-2b,\quad a=b$$ $$\implies a=b=\frac{1}{3},$$ i.e. the common point is $$\frac{1}{3}(\mathbf{x}+\mathbf{y}+\mathbf{z}).$$ It is easy to verify that this lies on the third line when its parameter is $c=\frac{1}{3}$.
Comment: You can make that deduction if and only if the vectors $\bf{x},\bf{y},\bf{z}$ are *linearly independent*. As you observed, this can be can diagnosed geometrically: the linear independence holds if and only if $X,Y,Z$ are not on the same plane as the origin. Unless $X,Y,Z$ are on the same line you can always achieve this by moving the origin to a suitable place. But, why would the location of the origin have anything to do with the truth of the claim?? This is a symptom that your approach, while basically ok, is using perhaps too many vectors.
Comment: (cont'd) Because the triangle is a 2-dimensional object (even in 3D-space), you should aim to write everything in terms of two known vectors intrinsic to the problem (such as two sides of your triangle). Otherwise you will inevitably run into this kind of difficulty that several combinations of coefficients $a,b,c$ may lead to identical vectors.
Comment: @JyrkiLahtonen: Thank you, I really appreciate the intuition you provided.
Comment: Three points in $\mathbb R^3$ are *always* coplanar. There wouldn't be a triangle to talk about otherwise. I'm guessing that you mean that they're not all on a plane through the origin, which isn't quite the same thing.
Comment: @amd: The context is vectors: What I meant is that the position vectors of the points cannot be coplanar. (My original post says "the vectors are not coplanar".)
Comment: @kesra You're going to encounter many sources that treat points and their position vectors as interchangeable, so you'll see things like "the plane defined by the vectors $u$, $v$ and $w$," not meaning a subspace of $\mathbb R^3$. Saying that $\mathbf x$, $\mathbf y$ and $\mathbf z$ are assumed to be linearly independent would make this unambiguous.
Answer: You don't mention your approach, but I think you've done an overly complicated approach.
The midpoints on the of the sides are ${X+Y\over2}$, ${Y+Z\over2}$ and $Z+X\over2$, and the oposite corners are $Z$, $X$ and $Y$ respectively. Now take the point one third to the oposite corner and you get for example:
$${2\over3}{X+Y\over2} + {1\over3}Z = {X+Y+Z\over3}$$
Doing the same for the other midpoints and oposite vertex gives the same result.
The trick here is of course to realize that they will cross at ${X+Y+Z\over3}$, but this can be seen as it would need it to be a linear combination of $X$, $Y$ and $Z$ and since such a line is for example $\theta{X+Y\over2}+(1-\theta)Z$ the coefficient of $X$ and $Y$ must bu the same, similarily the coefficient of $Y$ and $Z$ must be the same. So we have $\theta/2 = 1-\theta$ which means that $\theta = 2/3$.
Comment: Thank you, but your answer does not touch on my question at all..
Comment: @kesra The problem I have with your question is that you didn't mention your approach. The question would be easier to understand if you mention how you arrive at your equation.
Answer: $\newcommand{\Vec}[1]{\mathbf{#1}}$In algebra and analysis, it's often best to write an equation of the form $X = Y$ in the form $X - Y = 0$. Here,
$$
a_{1}\Vec{x} + b_{1}\Vec{y} + c_{1}\Vec{z} = a_{2}\Vec{x} + b_{2}\Vec{y} + c_{2}\Vec{z}
\tag{1}
$$
is equivalent, after rearranging, to
$$
(a_{1} - a_{2}) \Vec{x} + (b_{1} - b_{2}) \Vec{y} + (c_{1} - c_{2}) \Vec{z} = \Vec{0}.
\tag{2}
$$
As Jyrki Lahtonen notes in the comments, an ordered triple of vectors $(\Vec{x}, \Vec{y}, \Vec{z})$ is said to be linearly independent if

For all real $a$, $b$, $c$, the equation $a \Vec{x} + b \Vec{y} + c \Vec{z} = \Vec{0}$ implies $a = b = c = 0$.

Equation (2) has this form with $a = a_{1} - a_{2}$, etc., so if your vectors are linearly independent (i.e., their tips are non-coplanar with the zero vector), then (2) implies $a_{1} = a_{2}$, etc., just as you say.
The deeper issue is, the tips of three vectors in an arbitrary vector space are coplanar and there's nothing in the problem to prevent the zero vector from lying in the plane of the triangle. In a meta way, this means (as JL notes) your proof "contains too much infrastructure". Skyking's argument avoids this technical issue; it even works if the vertices are collinear.


Branched website - All .SLN files opening the same branch - VS2012

Question: I recently added branching to a website solution (webforms) in Visual Studio 2012. I now have a main branch and 2 dev branches.
The problem is that the when I open the solution file, it always opens the DEV1 branch.  I go to Source Control Explorer, drill down to the DEV2 branch and double click the .sln file and assume I'm opening the DEV2 branch.  But when I check changes in, they always list the checked in files as located in: <code>$/MyDev/MyApp-DEV1/MyWebSite</code>.  The same thing happens if I do anything in the main branch.
How do I get the .sln file in the DEV2 branch to actually open the DEV2 solution instead of DEV1?
Comment: Do your solution files have absolute or relative paths to the projects?
Comment: If you open the problem SLN file with a text editor, does it have relative paths ("../folder/project.proj") or abolute ("c:\folder\project.proj")?
Comment: Did you create the branch by using the TFS branch command in the UI or command prompt?
Comment: I used the UI to create the branches.  I'm not sure about your second question.  Each branch is mapped to its own absolute local path, e.g. `C:\Users\...\Projects\MyApp-DEV1`.  And the Source location is relative, e.g. `$/MyDev/MyApp-DEV1`.  But that's probably not what you're asking.  I'm not sure how to see how the actual solution is mapped.
Comment: Hmm, they're relative, but the .sln files are identical, all pointing to `"..\MyApp-DEV1\MyWebSite\"`  I tried just editing the file in notepad, but I'm getting errors opening the one I edited to point to DEV2.
Comment: I closed (and saved) the solution & reopened it and didn't get errors opening it the 2nd time.  But it looks like VS _corrected_ the error by changing the .sln file back to pointing at DEV1. :(
Answer: Thanks to StingyJack, I think I got this cleared up.
From his suggestion I looked at the .sln files in a text editor and saw that they were identical (all 3 pointed at the DEV1 branch).  I changed the paths in the DEV2 .sln file, and at first it didn't work, but it turned out the local path was messed up.  I removed the local mapping for the DEV2 branch, remapped it, and ran a get all.
After doing this, I can finally use my different branches as they are supposed to be used!


How do I modify a webform submission field right before it is saved?

Question: When an end-user is submitting data entered in a Drupal 8 webform, I would like my custom module to modify a field that is on the same form based on values of other fields. I am having trouble accessing the values of the submitted data and also setting the value of the field that I wish to change before being saved.
There is a sample webform API file included which has some starters for hooks. A hook which I found may be useful is the following.
function hook_webform_submission_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {}

I used the dpm() to print the values of these variables. The $form_state variable has the data submitted, and I know I can use the $form variable to change these values before being saved.
How can I get values of the data submitted and also set the value of another field on that same page before the submission is saved? In Drupal 7 this was fairly straightforward, but with Drupal 8 navigating the array and object structures of variables is not as transparent.
Answer: You can use preSave method in your handler. Please check out the Webform module handler tests module which is part of Webform codebase, it has TestWebformHandler.php file which defines the submission test handler which displays a status message for every handler event.
For example:
<?php

namespace Drupal\webform_test_handler\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission test handler.
 *
 * @WebformHandler(
 *   id = "test",
 *   label = @Translation("Test"),
 *   category = @Translation("Testing"),
 *   description = @Translation("Tests webform submission handler behaviors."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class TestWebformHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function preCreate(array $values) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postCreate(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postLoad(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $this->displayMessage(__FUNCTION__, $update ? 'update' : 'insert');
  }
}

Then you can use a standard ways of modifying your $webform_submission.
See also: Way to do an action after a webform submission has been created.
Answer: After much trial and error, I found an answer with the help of these pages:
https://www.drupal.org/node/2841729
https://www.drupal.org/node/2637958
The idea is to create a custom module and add a validation function using hook_form_alter(). The validation function then sets the values before the form is saved permanently with the setValues() method.
Here, I am setting the webform element observations to an arbitrary value.
function MYMODULE_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'MYFORM') {
    $form['actions']['submit']['#validate'][] = 'MYMODULE_operation_form_validate';
    }
}

function MYMODULE_operation_form_validate(&$form, $form_state, $form_id) {
  $values = ['observations' => 777];
  $form_state->setValues($values);
}

Comment: Thanks very much for this - I was getting very frustrated trying to find a hook to fire before the webform module purges `$_POST`. One thing I will point out however is that only the first 2 parameters get passed to the `_validate` function, so the inclusion of `$form_id` causes an undefined notice to be triggered.
Answer: In Drupal 8 you can use hook_ENTITY_TYPE_presave, for example:
/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function mymodule_webform_submission_presave(\Drupal\webform\Entity\WebformSubmission $submission) {
  // var_dump($submission); exit;
}

in order to access, validate or modify the elements of your webform $submission.
See: How to track webform element create, update, and delete operations.
For Drupal 7, see: How to alter the Webform submission information.
Answer: Use this hook hook_webform_element_alter
/**
 * Implements hook_webform_element_alter().
 *
 * @param array              $element
 * @param FormStateInterface $form_state
 * @param array              $context
 */
function module_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
    //use kint
    kint($element);
    //alter location field
    if ($element['#webform_id'] === 'my_form--location') {
        //do the logic
    }
}

Bingo!
Answer: There are multiple ways of doing this.You can use :-
1.hook_webform_element_alter()
function your_module_name_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
  if (isset($element['#webform_id'])){
    if ($element['#webform_id'] === 'abc') {
        //do the logic
    }
  }
}

Follow this for better understanding https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element
2.hook_form_alter()
function your_module_name_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form['#validate'][] = 'your_module_name_form_validate';
  }
}

And your logic goes into validate function
function your_module_name_form_validate($form, &$form_state) {
  $values = $form_state->getValues();
  //Your logic goes here.
}

hook_ENTITY_TYPE_presave()

function your_module_name_webform_submission_presave(EntityInterface $entity) {
  // Entity new will only allow you to modify the value for first time.
  if ($entity->isNew()) {
      $entity->setElementData('key', value);
  }
}


Existe algum problema de race condition no meu código?

Question: Existe algum problema de race condition no código abaixo?
Private Shared Sub TestRandomNumberGeneration(ByVal random As Random)
    Dim failed As Boolean = False
    Parallel.For(0, 100000, Sub(i, state)
        Dim [next] As Integer = random.Next()
        If [next] = 0 Then
            Volatile.Write(failed, True)
            state.Stop()
        End If
    End Sub)
    Assert.IsFalse(failed)
End Sub

Comment: @HorácioJ.C.Filho você pode aprender o essencial de edição aqui: http://pt.stackoverflow.com/editing-help , para as próximas perguntas :)
Comment: Muito obrigado pela formatação :D
Comment: De nada! Agora em cores :)
Comment: Ficooooou massa :D :D :D :D
Answer: Depende. Se o método Stop do objeto state só pode ser chamado uma vez (o que não está claro na questão), então sim, há uma possibilidade, ainda que pequena, de mais de um thread chamar esse método. E é possível, mesmo sem o paralelismo, que o Assert.IsFalse(failed) falhe - zero é um resultado possível pra função random.Next() (assumindo que random é do tipo System.Random).
Se o método Stop pode ser chamado mais de uma vez, e se for aceitável que o Assert.IsFalse falhe, então não há uma condição de corrida no código. Isso depende da hipótese que você tem sobre o seu código.


Converse direction of Cartan's criterion

Question: Choose a algebraically closed field $k$ with $\text{char}(k)= 0$ and a finite dimensional solvable Lie algebra $L$ over $k.$
As an corollary from Lie's theorem I have proved that there is a flag $(L_i)$ of $L$ such that each $L_i$ is an ideal of $L$. Consider $u\in [L,L]$. I have read a remark that claims $$\text{ad}(u)(L_i)\subset L_{i-1}$$ and $$\text{Tr}_L(\text{ad}(x)\text{ad}(y))=0~\forall x\in [L,L],y\in L.$$
Since this was marked as a remark the proof of this two statements shouldn't be such hard but I don't get along well.
Comment: I am very confused by the first part of this. Lie's theorem does not hold in non-zero characteristic. But the claim you make follows immediately from the definition of a solvable Lie algebra anyway.
Comment: I am very sorry, I just made a typo. The characteristic is asumed to be $0$. How do the two parts follow now?
Answer: By Lie theorem, $L$ has a basis such that $ad(x)$ is an upper triangular
matrix relative to this basis. Hence
$$
ad ([x,y]) = ad(x)ady-ad(y)ad(x)
$$
is a strictly upper triangular matrix. Then $ad[xy]ad(y)$ is a strictly upper triangular matrix for all $x,y$, hence we have
$$tr(ad[xy]ady) = 0$$
for all $x,y$. This shows the second claim. The first one also follows directly from Lie's Theorem.
Comment: Got it! Thanky a lot. Do you want to write a line for the first part? I thought Lie theorem gives us $ad(u)L_i\subset L_i$ instead of $ad(u)L_i\subset L_{i-1}$.
Comment: Yes, but again we have that $ad(u)$ is strictly upper-triangular, hence $ad(u)(L_i)\subseteq L_{i-1}$.


Why should the degree of freedom of the last row be k-1 not k

Question:
In the goodness of fit chi squared test, the proof as below shows
the way how to compute chisquared distribution value(learned in elementary course, just how to compute without the speicific reason) is applied to chisquared distribution mathematically.
The proof is for special case : k row by 2 col
As you know, in this case, degree of freedom should be (k-1) * (2-1),
so it must be k-1.
my question is in this point,
at the sight of last row of the proof, the degree of freedom of the last row
should be k not k-1 because, it is the summation of standard normalized binomial distribution (quantity of "k" not "k-1)
i was wondering if you could let me know the reason why.
Thank you in advnace.
Comment: I don't see any claim of degrees of freedom being $k$ anywhere
Comment: Z^2 ~ Chi df:1 // Z^2 + Z^2 + Z^2 + ... + Z^2 quantity of "k" shoud be ~ Chi df:k. by CLT, as you see the last row is the summation of the squre of standard normalized binomial (Z^2) quantity of "k" should be "k"
Comment: http://www.randomservices.org/random/special/ChiSquare.html  like term 17
Answer: Note that the link you point to in comments refers to

a sequence of independent standard normal variables

You don't have that here, because of the fact that $\hat{\theta}$ is estimated -- the deviations from $\hat{\theta}$ are dependent, since both the row and column totals of the $f$ terms in the $2\times k$ table sum to the same as the row and column totals of the $e$ terms (the expected values).
Under the model, this dependence is of exactly the form that would decrease the contribution of the $k$ degrees of freedom by $1$.


How can I add group by with ascending and decs values in odoo?

Question: I have two fields one is date and one more is function field with integer values so I wanted to add group by function field in ascending or descending order?
<code><search string="Feedback">
    <group expand="0" string="Group By">
        <filter string="Task Name" icon="terp-personal" domain="[]" context="{'group_by':'folionum'}"/>
        <filter string="Folio Number" icon="terp-personal" domain="[]" context="{'group_by':'folio_number'}"/>
    </group>
</search>
</code>
I wanted to add a group which can get max folio_number comes first
Comment: What you mean with group?
Comment: I have edited my qun ?
Comment: Just change the order in the xml :)
Comment: Ordering will be done directly from listview.
Comment: yeah how to do can you please add xml tag
Answer: <code> <field name="context">{'order':'date_of asc'}</field>
</code>
Solved my problem
Comment: I get context field does not exist. Where do I put this?


How can i solve the error internal PostCss Failed to load when running npm run dev?

Question: Here is the error message that i am getting:
> node:internal/process/promises:288
>             triggerUncaughtException(err, true /* fromPromise */);
>             ^
>
> [Failed to load PostCSS config: Failed to load PostCSS config
> (searchPath: /home/amaya/Desktop/LOANSPUR/prime-crm): [Error] Loading
> PostCSS Plugin failed: Cannot find module 'autoprefixer' Require
> stack:
> - /home/amaya/Desktop/LOANSPUR/prime-crm/postcss.config.js
>
> (@/home/amaya/Desktop/LOANSPUR/prime-crm/postcss.config.js) Error:
> Loading PostCSS Plugin failed: Cannot find module 'autoprefixer'
> Require stack:
> - /home/amaya/Desktop/LOANSPUR/prime-crm/postcss.config.js
>
> (@/home/amaya/Desktop/LOANSPUR/prime-crm/postcss.config.js)
>     at load (file:///home/amaya/Desktop/LOANSPUR/prime-crm/node_modules/vite/dist/node/chunks/dep-8609dc5d.js:36388:11)
>     at file:///home/amaya/Desktop/LOANSPUR/prime-crm/node_modules/vite/dist/node/chunks/dep-8609dc5d.js:36413:16
>     at Array.map (<anonymous>)
>     at plugins (file:///home/amaya/Desktop/LOANSPUR/prime-crm/node_modules/vite/dist/node/chunks/dep-8609dc5d.js:36412:8)
>     at processResult (file:///home/amaya/Desktop/LOANSPUR/prime-crm/node_modules/vite/dist/node/chunks/dep-8609dc5d.js:36482:14)
>     at file:///home/amaya/Desktop/LOANSPUR/prime-crm/node_modules/vite/dist/node/chunks/dep-8609dc5d.js:36606:14]
>
> Node.js v18.16.0

How can i solve it?
This is what i have tried:
I have run:
1. npm update

2.npm install

then when i run again npm run dev,the same error is there.
Answer: I have done the following and it has worked.
1.i run npm update;
2.npm install autoprefixer;
3.npm run dev;
I did those 3 steps and the error was solved
Answer: If you are using the Laravel Breeze package, you may encounter an error while running the npm run dev command.
Error Screenshot: https://prnt.sc/y5XzQ7AlBZoC
To resolve this issue, follow these steps:

Open the postcss.config.js file. Replace the existing code with the
updated code.
//Old code
export default {
    plugins: {
       tailwindcss: {},
       autoprefixer: {},
    },
};
// New code
module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
  };

Run npm run dev again.

Error fix screenshot: https://prnt.sc/NjpyNVeF8iR3
By following these steps, you should be able to fix the error and successfully run the npm run dev command without any issues.
Answer: I ran into the same issue and realized there was a conflict in my .local try clear cache or change folder path or name
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Unit test for custom content type

Question: I created my custom content type 'Proposal' in D7 and used field API to attach fields.
In order to write unit test for it using "simpletest" (core module), do I need to setup my proposal content type in the unit test method from scratch or will the content schema be available to the unit tests?
Answer: If the custom content type is set up from within a module you're testing, then no you won't have to implement hooks from within the testing environment or anything. However, if your custom content type is set up through the interface on your site then yes you will need to do the same in your test. It is very important to realize that tests run in Simpletest are from the perspective of an absolutely clean environment - no users, no permissions, no custom content types, etc - so all of that needs to be implemented in code.
It's not such a big task once you get used to writing tests though. You can probably set up your custom content type in the DrupalWebTestCase::setUp() method. A simple series of form posts (with $this->drupalPost('path/to/form', $form_values, t('Save'));) and your custom content type will be set up in no time.

Unit test for custom content type


Difference between static linking and dynamic linking

Question: What is the difference between static linking and dynamic linking?
Comment: @Andrey: This is not an exact duplicate. There are really three possibilities: static linking, load-time dynamic linking, and run-time dynamic linking. The other question is asking about the difference between the second and third, while this is talking about the difference between the first and a group of the second and third taken together.
Answer: In static linking, functions and variables which are defined in external library files are linked inside your executable. That means that the code is actually linked against your code when compiling/linking.
With dynamic linking external functions that you use in your software are not linked against your executable. Instead they reside in a external library files which are only referenced by your software. Ie: the compiler/linker instructs the software on where to find the used functions.
On windows platforms you can even explicitly load DLL files at run time and hook up the functions contained in the DLL.
Comment: This response would fit nicely in [c\# \- What do 'statically linked' and 'dynamically linked' mean? \- Stack Overflow](https://stackoverflow.com/questions/311882/what-do-statically-linked-and-dynamically-linked-mean) therefore this question is a duplicate.
Answer: Static linking is done at 'compile time' by a tool called a linker.  Dynamic linking is done at run time, by the operating system.
Comment: [Advantages and disadvantages of static and dynamic linking](http://www.engineeous.com/prepnote/static-linking-and-dynamic-linking)
Answer: static linking increase the file size of your program and it may increase the code size in memory if other applications are running on the system...
on the other hand dynamic linked program take up less space and less virtual memory
Answer: In static linking libraries linked at compile time, but code size is more when you this static linking ,when you only one or two programs then you use static linking
In dynamic linking libraries linked at run time(or) execution time ,but code size is less,when you have more programs then use dynamic linking.
Comment: What is the difference between `execution time` and `run time`?
Answer: If we compile simple helloworld program with static and dynamic linking, we will easily see the size difference as below,
#include <stdio.h>
int main(int argc, char **argv) {
    printf("Hello World !");
    return 0;
}

Create a dynamic linked executable as,
 $ gcc -o helloworld helloworld.c
Also, create a statically linked executable as,
 $ gcc -o helloworld_static helloworld.c -static
 $ ls -alh helloworld
-rwxrwxr-x 1 myuser myuser 7.2K Sep  2 21:08 helloworld
$ size helloworld
   text    data     bss     dec     hex filename
   1124     276       4    1404     57c helloworld

$ ls -alh helloworld_static
-rwxrwxr-x 1 myuser myuser 712K Sep  2 21:08 helloworld_static

$ size helloworld_static    text      data     bss     dec     hex filename
 658287    4096    3644  666027   a29ab helloworld_static

hence, the observations of executing simple helloworld program are as below,

A statically linked executable requires more space compared to a dynamically linked executable. The is a disadvantage of static linking and advantage of dynamic linking.
Only one copy of a shared library resides in memory for dynamically-linked executables. If several processes call the same object module of a shared library simultaneously, they all use the same copy of the library. Whereas, for static linking, all used objects of a library are copied into each executable. Thus, copies of each library object reside in memory for each of the different processes. This results in more RAM used for the static-linked executables than dynamically-linked executables.
Dynamic linking has more system calls, which means dynamically-linked executables will need more time for running/execution.

If you want a more extensive explanation, with actual system call tracing using strace during the program execution, you can visit a page I wrote about this issue on my website.
Comment: Excessive promotion of a specific product/resource may be perceived by the community as **spam**. Take a look at the [help], specially [What kind of behavior is expected of users?](//stackoverflow.com/help/behavior)'s last section: _Avoid overt self-promotion_. You might also be interested in [How to not be a spammer](//stackoverflow.com/help/promotion) and [How do I advertise on Stack Overflow?](http://stackoverflow.com/help/advertising).
Comment: @Makyen thanks for the suggestions, this was my first post. Corrected the answers, please check and let me know if any feedback / suggestions.


Uniquely identify a Computer by it's hardware profile (GetCurrentHwProfile)

Question: Using the GetCurrentHwProfile , we can retrieve the szHwProfileGuid, which is the hardware profile GUID of the machine, i suppose.
what is exactly a hardware profile and how is it editable?
is the Hardware profile GUID unique by machine?
Is the value stored somewhere in the registry and is it updatable?
If it is not unique, when exactly does this value change?
Comment: Just a guess, but you can specify 'hardware profiles' at boot time and  there is a built-in OS facility to save profiles. Useful for rolling back after driver/software setup. I think mostly it keeps a copy of the registry at a point in time, but... UPDATE: It appears this feature was removed after WinXP.
Comment: Well i just used this method on a 64bit windows 7 and it returned to me a GUID.
Answer: Yes, it is just an accessor to the registry key

HKLM\System\CurrentControlSet\Control\IDConfigDB\Hardware Profiles

And as someone discovered none of the following affects it: changing Primary HD, adding a second HD, re-Installing or upgrading the OS, replacing video cards, or changing user. Changing network card would surely affect it, as it is involved in the creation of any GUID.
My guess is it was just a way to tell whether a laptop is docked, that was designed as a base for accessing a broader range hardware changes -  but that never really took place. 'Hardware profile' would probably stay a vague term forever, in this API context.
Comment: Good link, although it says that changing the primary HD and upgrading the OS DOES change it.  :-)  Also you can manually edit the key, not sure what effect that has and not sure on its reliability based on that.


Problem with creating own module Block with an SQL query

Question: I'm trying to create a custom module that implements a block to display something I haven't been able to do with the Views 2 module.
I've tried to look at some guides and tutorials, but I haven't got any result yet.
I can print out the first SELECT attribute in the first row. The first row make sense since I don't loop through it but still I'm confused on how to do the rest.
function sn_most_contributed_block($op='list', $delta=0) {
  if ($op == "list") {
    // Generate listing of blocks from this module, for the admin/block page
    $block = array();
    $block[0]["info"] = t('Most Contribution this week (custom module');
    return $block;
  }
  elseif ($op == 'view') {
    $mce = db_result(
      db_query("SELECT node.uid, COUNT(nid), users.picture AS users_picture, users.uid AS users_uid, users.name AS users_name, users.mail AS users_mail FROM node node INNER JOIN users users ON node.uid = users.uid WHERE (node.type IN ('leads',  'qa',  'qa_comments',  'til_salg',  'tips_tricks')) AND node.created >= UNIX_TIMESTAMP( CURDATE( ) - INTERVAL 1 WEEK ) AND node.created <= UNIX_TIMESTAMP( CURDATE( ) + INTERVAL 1 DAY ) GROUP BY uid ORDER BY COUNT(nid) DESC LIMIT 0 , 5")
    );

    $block_content .= "Most contributed members are: " . $mce';
    $block_content .= "
In here should be the user image
";
    $block_content .= "
In here should be the username
";

    if ($block_content == '') {
      $block['subject'] = 'contribution test';
      $block['content'] = 'yay';
      return $block;
    }
    else {
      // set up the block
      $block = array();
      $block['subject'] = 'Most contribution this week';
      $block['content'] = $block_content;
      return $block;
    }
  }
}

I've tested my query in the database environment for my Drupal site and it works and print everything it should out correctly.

For looping the query, I tried this code with no result.

while ($contriUser = db_fetch_object($mce)) {
  $contriUser [] = $contriUser->uid;
}

I have also tried the following code.

while ($contriUser = db_fetch_object($mce)) {
  var_dump($contriUser);
}

Any help on how to solve this or if someone has an alternative solution to get the most contributing members last seven days it would be much appreciated.
Comment: Hi, there is a syntax error inside `"Most contributed members are: " . $mce';`. The `'` at the end is wrong. But I think that's not the actual problem.
Comment: Is the block even being created at all?  You seem to be using the Drupal 6 version of hook_block but the post is tagged 7?
Answer: For most contributing members you may want to look at the user points modules, they give you a lot of very nice features.
A couple of quick pointers with your code as you are asking.
Your query should use parameters and be formatted according to drupal coding standards, this helps for security and portability. The coder module can help you with this.
To get the results you will probably want something like db_fetch_array in a loop
 $result_set = db_query("SELECT ...");
 while ($result = db_fetch_array($result_set)) {
   $block_content .= ...;
 }

I hope this helps a little.
Comment: To further add, `db_result()` should be used when the query is returning a single field, such as `SELECT nid FROM {node} WHERE …`. If you need to get only a result but the query is not selecting a single field, then you should use `db_query_range()`.
Answer: I made some changes to the interesting part. Check out this untested code:
$block_content = "";
$result_set = db_query("SELECT node.uid,
  COUNT(nid),
  users.picture AS users_picture,
  users.uid AS users_uid,
  users.name AS users_name,
  users.mail AS users_mail
  FROM {node}
  INNER JOIN {users} ON node.uid = users.uid
  WHERE (node.type IN ('leads',  'qa',  'qa_comments',  'til_salg',  'tips_tricks'))
  AND node.created >= UNIX_TIMESTAMP( CURDATE( ) - INTERVAL 1 WEEK )
  AND node.created <= UNIX_TIMESTAMP( CURDATE( ) + INTERVAL 1 DAY )
  GROUP BY uid
  ORDER BY COUNT( nid ) DESC
  LIMIT 0 , 5"
);

$block_content .= t("Most contributed members are: ");
while ($result = db_fetch_array($result_set)) {
  $block_content .= '

';
  $block_content .= '
'.$result['users_name'].'
';
}

Comment: [db_query_range()](http://api.drupal.org/api/drupal/includes--database.mysql.inc/function/db_query_range/6) should be used when you want to limit the number of returned table rows.
Answer: If you have views 3, dereine has kindly posted an import for this http://drupal.org/node/1186598#comment-4593972


Save output and exit code of command to files on windows

Question: I want to run a command and save its output and its exit code, in different files.
Here's what i am doing:
cmd.exe /C command 1> %TEMP%\output.log 2> %TEMP%\error.log && echo %ERRORLEVEL% > %TEMP%\status || echo %ERRORLEVEL% > %TEMP%\status

If i don't do output redirection (into %TEMP%\output.log and/or %TEMP%\error.log), then exit code is saved just fine.
However, when i run the line as shown above more than once (just get back to previous line in command prompt and rerun it), i get 0 in %TEMP%\status regardless of the real exit code.
What am i missing?
Or maybe there's a better way of doing this?
Answer: What you're doing won't save the exit code, as you're not capturing it. The simplest way is to run the command from inside a batch file. Redirect the output as normal and have the batch file save the ERRORLEVEL value to the second file.
Comment: What do you mean i am not capturing it? Should't %ERRORLEVEL% env contain exit code of last executed command in session?
Comment: Yes, it does but any other operation will change it. In this instance the piping operations will themselves produce exit codes and that's what you will be getting, not the exit code from the command. Doing it in a batch file changes how the system does things.


Change of variables in Einstein summation

Question: This should be trivial, but I am not able to work it out. How is the following equality true?
$$ \frac{\partial}{\partial p^2} = \frac{1}{2p^2}p^\mu\frac{\partial}{\partial p^\mu} \,,$$
where $ p^2 = p^\mu p_\mu$.
Basically, it involves calculating the partial derivative $$\frac{\partial p^\mu}{\partial p^2} = \Big(\frac{\partial p^2}{\partial p^\mu}\Big)^{-1}=\frac{1}{2}(p^\mu)^{-1} \,,$$ and showing that $$ \boxed{\color{blue}{(p^\mu)^{-1} = \frac{p^\mu}{p^2}}} \,. $$
I am not sure if what I have done above is rigorous at all.
NOTE: I am not sure if the argument about multiplying and dividing $(p^\mu)^{-1}$ by a factor of $p^\mu$ works rigorously because there would be an implicit summation in the denominator.
Answer: It is is
$$
  \frac{\partial}{\partial p^\mu}=\frac{\partial p^2}{\partial p^\mu}\frac{\partial}{\partial p^2}.
$$
Then,
$$
  \frac{\partial}{\partial p^\mu}=2p_\mu\frac{\partial}{\partial p^2}.
$$
Now, multiply by $p^\mu$ both side and you get
$$
   p^\mu\frac{\partial}{\partial p^\mu}=2p^2\frac{\partial}{\partial p^2}
$$
and you are done.


Find generating function for the following conditions:

Question: $a_n=$ $2^{n+1}$ for $n:3|n$
$a_n=$ $0$ for the rest
So theres what I tried to do:
$$\sum_{n=0}^{\infty}a_nz^{n}=2*z^0+0*z^1+0*z^2+2^4z^3+0*z^4+0*z^5+2^7z^6+...2^{k+1}z^k$$
$$2^{k+1}z^k=b^k$$
$$\frac{b^{k+1}}{b^k}$$
$$\frac{2^{k+2}z^{k+1}}{2^{k+1}z^{k}}=4z$$
$$q=4z$$
$$W_0=(4z)^2$$
$$A(z)=\frac{4^{z}}{1+(4z)^2}$$
Is this the right answer?
Comment: $3 \mid 0$ is $\displaystyle\color{red}{\texttt{true}}$ !!!.
Answer: With $\displaystyle\left\vert z\right\vert < {1 \over 2}$,
$\displaystyle\quad\sum_{n = 0}^{\infty}a_{n}z^{n} = \sum_{n = 0}^{\infty}2^{3n + 1}\, z^{3n} =
2\sum_{n = 0}^{\infty}\left[\left(2z\right)^{3}\right]^{n} =\
\bbox[#ffd,10px,border:1px groove navy]{2 \over 1 - \left(2z\right)^{3}}$
Comment: Or explained with less notation, the series is a geometric series: $2 + 2^4z^3 + 2^7z^6+\cdots = 2+2(8z^3)+2(8z^3)^2+\cdots$. The first term is $2$ and the common ratio is $8z^3$, so the sum is $\displaystyle{ 2\over{1-8z^3}}$.
Comment: @SteveKass Fine. Thanks.


Node limit for published nodes per user

Question: I am interested in limiting the nodes a user can publish.So Node limit module cannot help on this.
Someone suggested using userpoints and rules to achieve this.
How is this possible with these 2 modules?
Any help would be appreciated.
thanks!
Answer: Give a try to User Points Contributed module: This module includes the module called userpoints_nodelimit which enables a limit on node creation based on user points.

However if you want to do it with the userpoints and rules module than the idea would be to create the rule to grant certain point on publishing the new nodes, and than create another rule whose event would be the node creation and in the condition  check if the user already has reached limit than prevent node creation and display the custom message.

Alternatively one easy way to achieve the same is using the hook_node_validate(), one example of using the same is as below:
/**
 * Implements hook_node_validate().
 */
function MyModule_node_validate($node, $form, &$form_state) {
  // For now assign the static value to MAX_NODES (No. of nodes),
  // however you can make it dynamic, and get those values using variable_get().
  $max_nodes = 'MAX_NODES';
  $node_count = 0;

  // Get the user uid from the global user variable.
  global $user;
  $user_id = $user->uid;

  if ((isset($node->uid))) {
    // Use entity query to get the number of nodes already published by this user.
    $query = new EntityFieldQuery;
    $node_count = $query->entityCondition('entity_type', 'node')
      ->propertyCondition('uid', $user_id)
      ->propertyCondition('status', 1)
      ->count()
      ->execute();

    // Check if the node count exceeds the max_node value.
    if ($node_count > $max_nodes) {
      form_set_error('FIELD_NAME', t('Reached the maximum limit of creation of nodes.'));
    }
  }
}

Comment: I cannot make this work,is this possible you export the rules and pastes them here?
Comment: @sokratis I will try that, but meanwhile can you try the alternate method I have added in my answer just now.

Node limit for published nodes per user


Como inserir uma variável no meio do endereço que eu passar para UrlLib2?

Question: Estou usando a função urllib2 em Python e preciso colocar uma variável no meio do link que eu passar pra função.
Por exemplo:
request = urllib2.Request('https://api.stackexchange.com/2.2/users/id_user?order=desc&sort=reputation&site=stackoverflow')

Onde o id_user é uma variável. Como faço ele reconhecer o id_user como uma variável?
Comment: Resolvido, url = "%s%d%s"%("https://api.stackexchange.com/2.2/users/",id_user ,"?order=desc&sort=reputation&site=stackoverflow"). Dessa forma ele reconhece em cada intervalo antes, entre e depois das virgulas onde cada argumento será predefinido. String vírgula inteiro vírgula string. Obrigado a todos que tentaram ajudar.
Comment: Senhor Sunstreaker, dê uma lida direito na pergunta, você vai perceber que existe um "user_id" no meio da link, e logo após eu deixei explicativo "Onde o id_user é uma variável." Muito obrigado pela atenção.
Answer: Há algumas formas de fazer isso.
Operador modulo %:
id_User = "IdUserNameAqui"
request = urllib2.Request('https://api.stackexchange.com/2.2/users/%s?order=desc&sort=reputation&site=stackoverflow' % id_User)

Operador unário +:
id_User = "IdUserNameAqui"
request = urllib2.Request('https://api.stackexchange.com/2.2/users/' + str(id_User) + '?order=desc&sort=reputation&site=stackoverflow')

Função str.format():
id_User = "IdUserNameAqui"
request = urllib2.Request("https://api.stackexchange.com/2.2/users/{0}?order=desc&sort=reputation&site=stackoverflow".format(id_User))

Exemplo
O exemplo abaixo vai inserir o conteúdo de uma variável no meio da URL, fazer a requisição e pegar algumas informações do JSON retornado.
import requests
#Para instalar: sudo pip install requests

id_User = "1"
url = "https://api.stackexchange.com/2.2/users/{0}?order=desc&sort=reputation&site=stackoverflow".format(id_User)
json = requests.get(url).json()

accountID  = json['items'][0]['account_id']
websiteURL = json['items'][0]['website_url']
userName   = json['items'][0]['display_name']

print ("ID: {0}\nNome de exibicao: {1}\nSite: {2}\n".format(accountID, userName, websiteURL))

# Saída
# ID: 1
# Nome de exibicao: Jeff Atwood
# Site: http://www.codinghorror.com/blog/

Answer: Use o método format().
id_user = 1
url = 'https://api.stackexchange.com/2.2/users/{0}?order=desc&sort=reputation&site=stackoverflow'
request = urllib2.Request(url.format(id_user))

Você pode usar o %, desta forma:
url = "...users/%s?order..." % id_user

Irá funcionar, mas prefira sempre o método format(). Como descrito pela documentação oficial, ele trata erros comuns de concatenação, e será o método oficial usado pelo Python daqui para frente. A idéia é que em breve o % não seja mais aceito.
Você também pode usar o "plus operation":
url = '...user/' + id_user + '?order...'

Mas é uma péssima prática. Quando o código se torna maior (e você deve sempre pensar nisso), esta url será ilegível. Caso precise juntar duas strings de forma rápida, prefira usar o join().
url = ''.join(['...user/',
               id_user,
               '?order...'])

Resumindo, use o format(). É o que o Python pede para que você use, no fim das contas.


cfengine: No access to workspace

Question: I'm completely new to Cfengine and I've just installed it on my Debian system. But when I try to invoke any of its executables as a non-privileged user, here is what I always get:
<code>$ /usr/sbin/cf-key
Fatal cfengine error:  !!! No access to workspace
</code>
Strangely enough, it looks like my local workspace got correctly created:
<code>$ tree .cfagent/
.cfagent/
|-- bin
|-- lastseen
|-- outputs
`-- reports
</code>
So any idea what I'm doing wrong here? Googling for this error message drew a blank...
Answer: You're missing the inputs directory.
Doing mkdir ~/.cfagent/inputs should do the trick.

cfengine: No access to workspace


Golang SQL query syntax validator

Question: Is there any third-party tool for validate SQL query before I execute it with the database/sql pacakge or any way to check the SQL query is right without getting a panic from database/sql that the query is invalid?
Answer: Finally, I found this SQL parser package. I colud use it for validate it.
<code>func isSQLValid(sql string) (bool, error) {
    _, err := sqlparser.Parse(sql)
    if err != nil {
        return false, err
    }
    return true, nil
}
</code>
Comment: It only supports MySQL SQL

Golang SQL query syntax validator


Esperar uma função executar para realizar a próxima

Question: Estou fazendo um Script em JS porém estou com uma pequena dificuldade.
Queria fazer com que minha função Loop() fosse novamente chamada somente quando a minha Função FaTown() já tivesse sido totalmente executada, hoje quando executo o Script a função Loop() é chamada antes da função FaTown() ser executada por completo
Segue o trecho do código

(function loop() {
  var rand = Math.round(Math.random() * (minutoMax - minutoMin)) + minutoMin;
  console.log(new Date().toLocaleString());
  setTimeout(function() {
    FaTown();
    loop();
  }, rand);
}());

function FaTown() {
  setTimeout(function() {
    uw.FarmTown.openFarm();
    setTimeout(function() {
      try {
        $('.checkbox.selcionar_tudo').click();
      } catch (e) {
        //
      }
      setTimeout(function() {
        document.getElementById("pegar_button").click()
        setTimeout(function() {
          $('.btn_confirmar_sim').click();
          setTimeout(function() {
            var janelas = GPWindowMgr.getOpenedClosableWindows();
            for (var i = 0; i < janelas.length; i++) {
              if (janelas[i].type === 589) {
                janelas[i].close();
                break;
              }
            }
          }, timeOpen)
        }, time1)
      }, time2)
    }, time3)
  }, time4)
}
Comment: Não entendi nada. Explique melhor e com mais detalhes o que voce já tentou.
Comment: Estou fazendo o edit da pergunta
Answer: Me parece que você está simulando um intervalo entre um clique e outro com esses setTimeout.
Você pode obter o mesmo resultado usando await dentro de uma função assíncrona, e como resultado você também poderia utilizar o await para esperar pela resolução da função antes de roda-la novamente:
async function sleep(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}

async function FaTown() {
    await sleep(time4);
    uw.FarmTown.openFarm();

    await sleep(time3);
    const checkbox = $('.checkbox.selcionar_tudo');
    if (checkbox) checkbox.click();

    await sleep(time2);
    document.getElementById('pegar_button').click();

    await sleep(time1);
    $('.btn_confirmar_sim').click();

    await sleep(timeOpen);
    const janelas = GPWindowMgr.getOpenedClosableWindows();
    for (let i = 0; i < janelas.length; i++) {
        if (janelas[i].type === 589) {
            janelas[i].close();
            break;
        }
    }
}

(async function loop() {
    const rand = Math.round(Math.random() * (minutoMax - minutoMin)) + minutoMin;
    console.log(new Date().toLocaleString());
    await sleep(rand);

    await FaTown();
    loop();
})();

Mas isso é uma sugestão, se você pretende continuar com o setTimeout pode utilizar uma função de callback para a FaTown invocar após terminar de executar, no caso, essa função seria o próprio loop:
function FaTown(callback) {
    setTimeout(function () {
        uw.FarmTown.openFarm();
        setTimeout(function () {
            try {
                $('.checkbox.selcionar_tudo').click();
            } catch (e) {
                //
            }
            setTimeout(function () {
                document.getElementById("pegar_button").click()
                setTimeout(function () {
                    $('.btn_confirmar_sim').click();
                    setTimeout(function () {
                        var janelas = GPWindowMgr.getOpenedClosableWindows();
                        for (var i = 0; i < janelas.length; i++) {
                            if (janelas[i].type === 589) {
                                janelas[i].close();
                                break;
                            }
                        }
                        callback();
                    }, timeOpen)
                }, time1)
            }, time2)
        }, time3)
    }, time4)
}

(function loop() {
    var rand = Math.round(Math.random() * (minutoMax - minutoMin)) + minutoMin;
    console.log(new Date().toLocaleString());
    setTimeout(function () {
        FaTown(loop);
    }, rand);
}());

Mais sobre async/await e função callback.


Limit Rule $\lim f(x)^{g(x)}$

Question: I want to know the following is true : If $$ c,\ d\in {\bf R},\  \lim_{x\rightarrow 0} f(x)=c>0,\ \lim_{x\rightarrow 0} g(x) =d>0$$ then $$ \lim_{x\rightarrow 0} f(x)^{g(x)} = c^d$$
In calculus book such formula cannot be found.
Consider the problem : $$\lim_{x\rightarrow 0} (1+\sin\ 4x)^{\cot\ x} $$
To find a limit, we must use ${\rm log}$ and L'Hospital. But some student suggests that $$ \lim_{x\rightarrow 0} (1+\sin\ 4x)^{\frac{1}{\sin\ 4x} \frac{\sin\ 4x}{\sin\ x}\cos\ x}=e^4$$
This argument is clear. But I know that it is informal. Is there a minus point in such way ?
Comment: The result you have mentioned is true (as shown in the answer) but it is much better to take logs and then evaluate the logarithm. The formula is valid for all $c > 0$ and any finite value of $d$. But the technique of taking logs works in other cases too one of $c, d$ is infinite or if $c = 0$.
Comment: @ParamanandSingh Here how can we apply $\ln$ without knowing inner limit exist?
Comment: @MeetPatel: this works because $\ln$ is a continuous bijection. The interplay of $\ln$ and its inverse $\exp $ is needed here. See more details at https://paramanands.blogspot.com/2013/11/teach-yourself-limits-in-8-hours-part-3.html?m=0
Answer: Assuming $f(x)>0$ for some open set surrounding $x_0$, we know that because the natural logarithm is continuous on $(0,\infty)$ that
\begin{align}
\ln \left( \lim_{x\rightarrow x_0}{f(x)^{g(x)}}\right) & =\lim_{x\rightarrow x_0}{\ln \left(f(x)^{g(x)}\right)} \\
& =\lim_{x\rightarrow x_0}{g(x)\ln f(x)} \\
& =\left(\lim_{x\rightarrow x_0}{g(x)} \right)\left(\lim_{x\rightarrow x_0}{\ln f(x)}\right) \\
& =\left(\lim_{x\rightarrow x_0}{g(x)}\right)\ln \left( \lim_{x\rightarrow x_0}{f(x)}\right) \\
&  =\ln \left[\left( \lim_{x\rightarrow x_0}{f(x)}\right)^{\left( \lim_{x\rightarrow x_0}{g(x)}\right)}\right]
\end{align}
Then, because the natural logarithm is injective, we find that $$\lim_{x\rightarrow x_0}{f(x)^{g(x)}}=\left( \lim_{x\rightarrow x_0}{f(x)}\right)^{\left( \lim_{x\rightarrow x_0}{g(x)}\right)}$$
Comment: The limit might now exist at the left of $x=x_0$.Then how do I assume that the log goes inside?
Answer: Yes. Note that the function $f(x,y)=x^y=e^{y\ln(x)}$ is continuous for $x,y>0$, so if $(x_n,y_n)\to (x,y)$ with $x,y>0$ then $f(x_n,y_n)\to f(x,y)$.
Answer: Because

$y(x)=ln(x)$ is continuous at $x = c > 0$
$\lim\limits_{x\to 0}f(x) = c$

according to the composition law, we have
$$\lim\limits_{x \to 0}lnf(x) = ln\lim\limits_{x \to 0}f(x) = lnc$$
Because $\lim\limits_{x \to 0}g(x) = d$, we have
$$\lim\limits_{x\to 0}g(x)lnf(x) = \lim\limits_{x\to 0}g(x)\cdot\lim\limits_{x \to 0}lnf(x) = dlnc$$
Apply composition law again, we get
$$\lim\limits_{x\to 0}f(x)^{g(x)} = \lim\limits_{x\to 0}e^{g(x)lnf(x)} = e^{\lim\limits_{x\to 0}g(x)lnf(x)} = e^{dlnc} = c^d$$

Limit Rule $\lim f(x)^{g(x)}$


Switching the "Event State" with the "Censor State" in Survival Analysis?

Question: Suppose there is a university that has data on different students. The university is trying to build a statistical model that will help them understand which "types of students" (e.g. males, low income, etc.) are at higher risk of dropping out of the university - based on the results of this model, the university would try to help these "types of students" prior to them dropping out in the future.
The university has 10 years of historical data (e.g. 2008 - 2018). Let's say that students can either "drop out" of the university, "successfully graduate" from the university, be "expelled" from the university for bad behavior, or "currently enrolled in the university" (e.g. as of 2018, the student was still currently enrolled in the university). The university has data (e.g. age, gender, employment, placement exam score - recorded once a year on the first day of school, September 1st) on students up until a year before one of these events happen. The data looks something like this (let's imagine that on September 1st, the student are required to take a placement exam and receive a score):
<code>  student_id gender age date_measurements_taken employement Placement_Exam Year_Expelled Year_Drop_Out Year_Graduated
1          1   male  19             Sept-1-2010         yes      73.39544            NA          2013             NA
2          1   male  20             Sept-1-2011         yes      54.40925            NA          2013             NA
3          1   male  21             Sept-1-2012          no      43.70675            NA          2013             NA
4          2 female  24             Sept-1-2009         yes      84.69812          2011            NA             NA
5          2 female  25             Sept-1-2010         yes      92.73473          2011            NA             NA
6          3   male  19             Sept-1-2010          no      65.44966            NA            NA           2014
7          3   male  20             Sept-1-2011          no      77.61102            NA            NA           2014
8          3   male  21             Sept-1-2012          no      69.92497            NA            NA           2014
9          3   male  22             Sept-1-2013          no      84.74314            NA            NA           2014
</code>
My initial idea was to fit a Discrete Time Survival Model to this data (e.g. c-log-log link) or to just treat this problem as continuous time and use a classical Cox Proportional Hazards - this way, I could find out the effect of different covariates on the hazard, and if these effects were statistically significant.
The problem I have is deciding how to define the "Event" and "Censoring" - two issues come to mind:

Issue 1: In this example, the university only records data on the first of September and does not record the exact date at which the student drops out, nor does the university record measurements at the the exact time at which the student drops out. As an example, the student may not be employed on September 1st - but starts working in November, can't handle the stress and ends dropping out by March.

Issue 2: It seems to me that in the traditional sense, "Drop Out" (e.g. prematurely dropping out of a medical study) is generally considered to be "Censoring". However in my case, I am interested in identifying "the last known September 1st in which the student was present at the university" (so that the university has a few months to take some action)

With this being said, I thought of the following approach. In this problem, I would define:

Event: "Drop Out" (occurring at "Year_Drop_Out")
Censoring: "Graduation" (occurring at "Year_Graduated"), "Expelled" (occurring at "Year_Expelled") , "Currently Enrolled At University"

Thus, it would appear as though I have interchanged "Censor" and "Event" definitions in this problem - can someone please tell me if the modelling framework that I have proposed in this question is logical and corresponds to a Survival Model?
Notes:

I would obviously restructure my data according to the necessary software package/library specifications prior to starting analysis
In the comments, a "Competing Risks Survival Model" was suggested for this problem. While in theory I think this is a suitable approach - suppose the university is only interested in studying "students who drop out" vs. "students who do not drop out". Given this, is the approach I have outlined suitable?
Comment: These seem like competing "risks" requiring more than 1 type of event. Have you looked into the methods explained by the R [competing risks](https://cran.r-project.org/web/packages/survival/vignettes/compete.pdf) vignette?
Comment: @ EdM: thank you for your reply! I looked at this ... in my case, I am not particularly interested in knowing about graduation or being expelled - just dropping out. In this case, does it make sense to "clump" graduation, currently enrolled and getting expelled into a single "state" (censored) and dropping out as the event?
Comment: Conceptually, does it make sense - "creating a survival model to estimate the start of the last year the student will be in prior to dropping out"?
Comment: I think this is a common problem - when measurement on an individual patient are only available at some time point before the actual event occurs? Is this a major violation of survival analysis assumptions?
Answer: Most useful here might be a multi-state model. In particular, someone who "drops out" might re-enroll and then be once again "at risk" of the other fates. The institution could be interested in evaluating factors associated with re-enrollment and eventual success.
That said, you can define the "event" as anything that makes sense. If all you care about is the first drop-out event and not subsequent re-enrollment, you could model this as a competing risks problem.
Even with competing risks, however, in a proportional hazards setting you get the correct hazard ratios for the event of interest if you censor at the times of other events that aren't of interest (in addition to right-censoring at last observation times of those still at risk for all event types). See the R survival package's competing risks vignette, for example. When you do that censoring you don't get estimates of the probability of being in the other states over time, which are often of interest.
You speak of a "Discrete Time Survival Model" and a "Cox Proportional Hazards" model as being synonymous. Although you are correct that a Cox model is evaluated at discrete event times, it's considered to be working at samples of an underlying continuous time. What's conventionally considered a discrete-time survival model typically considers only a restricted number of time points, as what you might have with panel data.
Your hypothetical data, with events apparently only known to have occurred within an academic term or academic year, is what's considered interval censored: you have both lower and upper limits to event times. The discrete-time model most closely related to a Cox model in this case is a binomial regression with a complementary log-log link, on properly formatted data. See this page.


Are very cheap cellos acceptable for a beginner?

Question: I'm looking at getting a 1/2 cello for my son. My options are either rent a mid-end one for 50$ a month, or buy a very cheap one (there seem to be some online for 150$~200$).
My experience with very cheap instruments is mixed:
The cheap ~100$ guitars are usually so bad as to be completely unplayable.
Cheap Keyboards and Electric Pianos, though annoying, are good enough for a child learner waiting to see whether they will stick to the instrument.
If 3~4 months rent will buy me a new cello, I would just go with the cheap cello and wait later for when he grows tall enough for a full size to buy a quality instrument.
But am I worried that the super cheap one will be like the cheap guitars, so bad that they can't be played correctly. Is that the case? Should I just rent instead?
Comment: Is second-hand cello an option? Used instruments tend to have better value than new (i.e. the same money buys you better one) and, most importantly, they can be sold at about the same price, so you're not at loss if your kid looses interest.
Comment: @Strawberry quality of cheap instruments has enormous variance, so getting decent one, however not impossible, involves either lots of luch or spending lots of time browsing.
Comment: My guitar cost less then $100. I adore it. But I know I have a less developed ear than most. That said, unless you know you can care for it immaculately, I think it's crazy to spend a fortune on an instrument that your son will soon outgrow.
Comment: @BlueRaja-DannyPflughoeft: You didn't buy a $20 guitar. You paid $20 for a decent used classical guitar.
Comment: If you do not have the experience or expertise to determine the quality of a particular type of instrument, have your child's teacher or some other experienced person advise you on a potential purchase. Sometimes an inexpensive instrument (used or new) turns out to be a gem. Or at least much better than you'd expect at the price.
Comment: Can't you test it at the store before you buy? Or buy on Amazon and return it if it doesn't sound ok?
Comment: Not all sub-$100 guitars are unusable, it's mainly the ones at Wal-Mart.  I have a classical guitar I got on craigslist for $20 ten years ago, it sounds pretty decent.
Comment: Whereabouts are you? In some places you'll find that schools will have schemes in place to help kids get into music; when I was young I got my first violin through a sort of hire-purchase plan. I don't remember the exact details (I was only 6 at the time) but basically you paid a monthly fee to the school's music department, and that got you violin tuition and a rental violin. At the end of the school year, you could either give the violin back, or make an extra payment to own the violin.
Answer: I'm going to suggest an alternative route.  Get him an electric cello.
The weak point in cheap instruments is the acoustics, and to meet the price point they have to be constructed in a more rough-and-ready manner.  As soon as you go electric, you don't need those acoustics.  Production is much more straightforward, and there are simply fewer variables with an electric instrument.
$100 electric guitars are usually absolutely fine for a beginner.  A while ago now, I bought an electric violin for £50, new.  That included violin, case, bow and rosin.  The bow was a POS, but the violin was and is perfectly OK - it even sounds acceptable acoustically for quiet practise.  (Another bonus for you: it's quieter when he's still making noises like a creaky door!)  Cheap instruments generally need a setup, so you should probably expect to have to file the bridge shape on the cello to make the action better, but that's about it.
Where you must invest is in the bow.  Whatever the instrument is, buy the bow separately, and expect to spend around $50 for something halfway acceptable.  Much more of the playability of a bowed instrument is in the bow than the instrument.  Even if you decide to go down the rental route in the end, the bow should be his.
Comment: I would never never never start a beginner on an electric instrument. It's impossible to learn good bowing technique on an electric - it will not be applicable to an acoustic instrument later on. At least not in terms of subtleties and fine control. It would be like learning a completely new skill almost from scratch. On the other hand, bowing technique learned on an acoustic is very helpful to playing an electric instrument. Easiest way to explain: the electric has less variation in sound and is therefore more forgiving and requires less control/expertise, so there's not reason to learn it.
Comment: @thecoder16 Good point.  But he won't be playing in the orchestra until he's a bit better, will he?  And for a school orchestra, I'd honestly be amazed if they wouldn't allow an electric instrument - generally they're happy to include anyone keen enough to learn.  It's not like he's going to be auditioning for the RSO next week. ;)
Comment: @MAA I can't speak for cello, because I don't play that myself.  For electric violin though, I can definitely tell the difference between good and bad bowing technique.  Of course it's possible to turn down the treble on the amp or pickup and sound more "mellow", so a teacher should nip that in the bud. If/when he upgrades to a full-size instrument further down the road, there's going to be some readjustment needed there anyway.
Comment: @Graham it is of course possible to tell the difference between good and bad bowing technique on both kinds of instruments - especially if you are an advanced player, and not a beginner - it's just that there is greater fudge factor on an electric instrument when it comes to speed, weight, and contact point. Having a straight bow is equally important either way, but sound variation on an acoustic instrument is extremely subtle, and 100% controlled by the bowing technique of the player. At best, going from electric to acoustic would be frustrating for a student, because sounding good (cont)
Comment: @Graham on the electric is easier.
Answer: Your mixed feelings about cheap instruments are correct. For electronic instruments such as keyboards, cheap ones are somewhat acceptable, because they are mass-produced from stable materials and structures, and most importantly, they work because their software works. Once they are correctly designed, they can be correctly made, and they will be playable - think about a cheap calculator, which can still add up numbers for you as long as it has batteries installed.
Acoustic instruments, especially wooden ones, are a totally different story. For starters, good quality tonewood, essential to get an instrument to sound right, is expensive. It takes patience, experience, and talent for a luthier to work with it, create an instrument and release its potential. To build cheap acoustic instruments relies on automated manufacturing.  They use cheap woods such as laminates, which sound terrible but are easy to machine process. Cheap instruments won't be correctly set up, either, because it takes a lot of experienced manual work. Also, because of the drive to reduce cost, the instruments may be produced without decent precision (which is very common in cheap instruments), resulting serious intonation issues. A badly set up, bad sounding instrument will be a pain to play, and diminish your enthusiasm really quickly. So my advice to all people who want to buy an acoustic instrument is: always set your budget as high as possible.
So my answer to your question is: buy a good one (I don't know but a mortgage might be an option, if you can't afford it for now). To rent is also a good idea, as kids can get bored and stop learning instruments very fast. In any case, stay away from cheap ones.
Answer: They are absolutely acceptable. I recommend you look around on forums and generally on the internet to hear what real people are saying about the cello you're thinking about.
I'm an adult beginner and I bought a cecilio CCO-500. It doesn't sound or look amazing, but it is serviceable. I spent money on Helicore strings and a new bow and it really gets the job done.
I recommend the same for you. Get the most expensive one you can afford (my cello costed sub $500 at the time and I am satisfied with it for now). Be prepared to spend a little on modifications the teacher recommends if necessary and you should be able to get through the beginner hump without worries.
Finally my teacher, who is a Julliard graduate said plainly to me, at this point she would only recommend I get a new cello if my current one was mechanically unsound. That is, if it made it impossible for me play somehow. And it is fine in that regard.
EDIT
The model that I got is functionally identical to the cheaper models and costed more due to the ebony fittings. I see cheaper models from the same manufacturer on ebay and amazon for a lot less than I paid. I'm not endorsing that brand in particular, however they do have a reputation of making servicable  beginner instruments at low cost. Nothing impressive, but nothing bent out of shape and unplayable either.
Comment: the difference between a $150-200 instrument and a $200-300 instrument is often the difference between an instrument that requires constant maintenance and repair, and one that will actually make it through a set without something falling out of adjustment.  Sadly this difference may be smaller than one would hope in this price bracket these days.  I'm torn between this answer and the one that recommends taking out a mortgage.
Comment: @el.pescado To be fair, I could have broken down the cost better in my post. The C500 is identical to the C300, except for the ebony fittings. It costs about $100 more. Also Helicore string full size cost ~$120. Those prices are before shipping. So a C300 without strings would be $200-$300 and would be functionally identical
Comment: Are you also taking into account that you'll need an amplifier with this? Do you already own one? Can your child easily and safely bring this amp along to play at lessons? Will he play with peers in some sort of ensemble? An electric instrument doesn't have the same tone either.
Comment: You might have written this comment on the wrong answer by accident. Another one spoke about electric cellos not mine.
Comment: I bought the Cecilio CCO-Purple Student Cello (some places thats $200 and comes with extras), and I am fairly happy with it. Let a friend who play cello (mostly by ear) use it and they said it sounds good. (This was without me telling them it cost 200). My only complaint is the finish on leaves something to be desired in some places (little nooks and crannies) and is more colored wood than metallic like I thought it would be. And my cello teacher hasn't said anything about the sound from it being bad, but did ask if I changed the finish on it. I'll upgrade someday, but I'm happy for now.
Answer: Cheap instruments are almost always going to be a pain to play and upkeep, but you are right in that some are more playable than others. Cheap woodwinds and brass are especially bad in that the cheap, weaker metal that's used to make them along with awful designs make it really easy to damage them beyond repair. Luckily cheaps strings aren't nearly as bad in this regard. The neck is less prone to warping than a cheap guitar, and since there aren't any frets intonation is purely up to the player. If the set up is bad you may need to take it to a luthier to get it actually set up. If you want to instantly make it sound better I suggest picking up new strings; even Red Labels will be better than the stock strings.
A 1/2 size cello at the $150-$200 price point should be enough to get him started, and after 3-4 months you can always reevaluate your decision and start renting.
Answer: I've had the opportunity of playing one of those $50-$100 case and bow included violins.  Now make no mistake: a cheap guitar with a soon-warped neck becomes completely unplayable because the frets will stop working (you press second fret and get fifth with a snare instead).  A violin or cello does not have frets and fretboards are separate parts.  Nevertheless, the playability was awful.  This starts at the strength to need for fingering and ends with the sound quality because there is a difference on working with high-density wood manually following its grain or CNC-milling something out of a block of cheap wood.
Getting a nice tone out of the instrument is the major challenge on bowed string instruments for a long time.  Starting on an instrument that would challenge a professional is cheaper but you'll reach a point of diminuishing returns over the expected length of career.
The advantage over a rented instrument is that if your child throws in the towel after all, the instrument stays around in case of a change of mind for trying things.
Obviously you don't need a Stradivarius, but the least you should aim for is an instrument that would be fun enough for a fiddler.
Note that even where no tone wood or other largely manual part construction is involved, like with accordions or many woodwinds, Chinese brands and/or makes without Western companies involved in the manufacture and quality control tend to be comparatively bad for whatever reason.
A few hundred years ago, cheap string instruments were mass-manufactured in the area in the Saxonian/Bohemian border region, with a similar low evaluation of manual labor over machines than might be the case now in China.
Those instruments, when kept in reasonable playing shape, tend to be tolerably good these days: probably there was more of an accumulation of knowledge and competition among workers for manual skills and more long-term perspective than there is these days in China.  And when push comes to shove, they had to work for adult semi-professionals with modest means even then.  This is not the case for today's cheap instruments.  I don't really know the intended target for the kind of instrument I was able to test a decade ago or so.
Basically, it's like training for running on a mud slide: part of your skill set and work is invested in stuff that is only marginally related to future progress.  Can be fine for testing determination, but you need to find the right point of time to move on.  And of course, you need an active player to figure out when the instrument has already moved beyond playability which can happen in few years (possibly even of just storage) with instruments milled from cheap wood.
Answer: 1/2 cellos tend to be pass-on trophies since children grow out of them comparatively fast.  So the initial investment is recovered at sale to a good degree if you buy a solid instrument.  Of course, this depends on the instrument actually surviving this time, so instrument insurance makes sense (and should be quite affordable) depending on how much of a risk you are willing to bear unmitigated.
Cheap instruments have little resale value.  Of course, once you are willing to pay more, you should buy from a reputed source or with someone able to judge the instrument, or you might still get small value from a larger investment.  Your prospective teacher might know pupils having outgrown their original instrument, so it definitely makes sense to ask there first.
Answer: Quick answer, not sure if anyone else mentioned it: rent your son's instrument.
This is a win win for all parties - most hire schemes are hire-to-buy or hire purchase, so you're actually paying towards finally owning the instrument. Some schemes even allow you to carry this over to the next instrument, if he wants a full-size one later.
It works out in case he decides he doesn't like it too, as you're paying a nominal monthly fee only - no big payout. You get a very decent instrument of course, with no obligation or high cost.
Shar Music (online store) do rentals, as do most luthier/instrument outlets.
Answer: This depends on the person of course but I would say most beginners and especially children, would not notice the difference between a cheap and quality instrument. The purpose of a cheap beginner instrument to me would to test if the kid wants to pursue playing. I'd suggest that you could look for a used one. Might be a little more than a cheap, new one but cheaper than an expensive new one. If you're gonna force the kid to play at least for a year or so, I'd invest in something they might not hate, if you think they'll be able to tell a difference. I'm not keen on instrument buying but there might be a great place for coupons, deals, or a good time of year to buy (like if there's a Black Friday equivalent for musical instruments).
These instruments exist though so someone must use them. Buying one is a gift for the kid so if there's the possibility they won't appreciate it, especially if money is an issue, don't break the bank.
Answer: You might look into rent-to-own from a reputable shop.
Some instrument shops will allow you to rent an instrument, then put the money spent on the rental towards a new or used instrument in their inventory. Not to mention, the rentals are typically student-grade or intermediate level instruments, and if your child takes a good liking to it you might consider spending some of that money onto a good instrument. However, if your child decides that the cello is not for him, then you won't have spent the money on an expensive instrument.
You might end up spending a little more than $150-200 total, but if you have split this up over the course of several months with the rental, you have the added benefit of 1. having more time to put together some extra cash, and 2. lowering the sticker price on an instrument as you've already paid a part towards it.
Answer: I know this question has a lot of answers already, but I have very strong feelings on the issue, so I'm adding mine:
Especially for a young child, having an instrument that sounds good is essential - if you want them to enjoy playing and want to continue doing it. If you decide to take up a new activity, are you going to buy equipment that limits your ability? Or equipment whose ability is greater than yours and can therefore be grown into?
If cost is an issue, the rent-to-own suggestion is a good one. Other things to keep in mind are that most shops will accept trade-ins, so when it's time for the next size up, you can get much of the value of the smaller instrument applied to the bigger one; also you can sometimes resell to other students (though usually not at 100% of the original purchase price); or if you have more than one child, the younger ones may play it later on.
Bottom line: make sure it's a good sounding instrument, and set up to play easily. There's no specific price attached to this, but you do need to get your hands on the instrument prior to purchase.
Answer: In my town, we have a thriving public school string program that begins in elementary school. Of course, the new students all need to get an instrument, somehow. Students who need an instrument are directed to an instrument rental agency in the area. These are typically very helpful; the staff there can help choose an instrument (cello, in your case) that will suit your child best. This includes finding the right sized cello and bow. Rental agency staff are usually very knowledgeable about the instruments themselves. In addition, smaller instruments are quickly outgrown and with a rental you won't have them piling up.
The reason I wouldn't recommend buying a cheap cello online is mostly the sizing issue; also, if the cello sounds horrible enough, it can drive the student away from the instrument. In addition, shipping a cello is pretty dangerous (for the cello). And if the instrument really is that bad, returns can be a hassle and it's still over a hundred dollars that's been shelled out. Also, if your child continues the cello, you'll definitely need a better cello in the future; if he doesn't, then you're stuck with a crappy cello that no one really wants to buy.
When I started out playing, my own teacher had a stash of cellos that he would rent to his students; this probably isn't helpful in your case. I'll admit that I did consider buying a cheap cello online to use at school, because I was afraid to accidentally break my instrument when I brought it to school for orchestra. I have a friend who did that; it was convenient because she didn't have to lug around her giant instrument, she merely left it in the rehearsal room. If there isn't a good rental agency in the area, then I'd buy a cheap one.
But!! (sorry this is very long, and this post is old lol)
If you've already found a teacher, ask them what would be best! They'd have to be from your area, and are probably familiar with beginning cello players. Therefore, they'll be able to help you more than anyone one this website (probably).
Hope this helps, if it's still relevant to your situation!
Answer: As a cellist I've been through four cellos, and would recommend spending less on 1/2 and 3/4 sizes, which are outgrown relatively quickly, and investing in a full size cello of good quality if your son sticks with cello. There will always be a difference in craftsmanship when deciding between price points, but for a (I'm assuming) beginner at the cello this wouldn't be an issue until a performing level is reached. Another option, and what I did, would be to part exchange cellos as the size is outgrown (the shop would calculate the value of the returned cello you bought from them, and subtract it from the cost of the new cello)
Answer: I would always recommend a cheap instrument for a first-timer. Yes, have a look at it to make sure it is playable, but it is just not worth putting in the investment until you know they'll want to continue.
With guitars, you can pick up perfectly suitable electric ones from about £50 and acoustics for not much more. And for a beginner it doesn't matter that they don't have perfect intonation or tone, or perfectly straight frets and smoothed fret edges. A beginner has much bigger issues to contend with.
Similarly with cellos or almost any instrument. Get them something cheap that is playable, and like I did with my daughter, suggest that if they practice and improve, they can choose their next one. My daughter chose a bright green strat copy after proving she had the commitment to practice and playing. She also put some money towards it. That way, she really protects and looks after it, which wasn't the case with her first one.


Estimating time remaining using conditional expectation

Question: I'm interested in the following scenario:
The duration of a certain (natural) process is estimated using a random variable with mean $\mu$ and standard deviation $\sigma$, which we can approximate using normal distribution (with the stated parameters) for any practical purposes.
Let $X^t$ a random variable describing the expected amount of time left for an observed process to end, given that observation is made at time $t$ ($t$ time elapsed since the process has started).
How can I compute the probability of $X^t$ ?
Answer: The probability of $X^t$ is given by a truncated normal distribution (truncation of lower tail at $t$) and you can compute it using Bayes theorem. Let's say $X=X^t + t$, where $X$ is another random variable describing the total lifetime of the observed process, then you are interested in finding the posterior probability
$$
p\left(X=x \mid t^* \right) = \frac{p\left(t^* \mid X=x \right) \, p\left(X=x \right)}{p\left(t^*\right)}
$$
where I have used the notation $t^*$ to indicate the observation that the process is still running at time $t$ (there is probably a better notation for this, but I don't know it).
The prior probability is known
$$
p\left(X=x \right) = \frac{1}{\sigma}\phi\left(\frac{x-\mu}{\sigma}\right)
$$
where $\phi$ indicates the probability density function of the standard normal distribution.
The likelihood is
$$
p\left(t^* \mid X=x \right) =
\begin{cases}
    1, & \text{if } x\geq t\\
    0,              & \text{otherwise}
\end{cases}
$$
The marginal likelihood of $t^*$ is
$$
\begin{align}
p\left(t^*\right) &= \int_{-\infty}^{\infty} p\left(t^* \mid X=x \right) p\left(X=x \right) dx\\
&= 0 \cdot \left[ \int_{-\infty}^{t} p\left(X=x \right)dx \right] + 1 \cdot \left[\int_{t}^{\infty} p\left(X=x \right) dx \right]\\
&= 1 - \Phi\left( \frac{t - \mu}{\sigma}\right)
\end{align}
$$
where $\Phi$ is the cumulative distribution function of the standard normal distribution.
Finally, putting everything together and applying Bayes theorem yields the posterior probability density
$$
p\left(X=x \mid t^* \right) =
\begin{cases}
    \frac{\phi\left(\frac{x-\mu}{\sigma}\right)}{\sigma \left[ 1 - \Phi\left( \frac{t - \mu}{\sigma}\right)\right]}, & \text{if } x\geq t\\
    0,              & \text{otherwise}
\end{cases}
$$
The probability density for the cases where $x \geq t$ is a truncated Gaussian distribution (see one side truncation of lower tail on Wikipedia). Based on this you can, for example, compute the expectation
$$
\mathbf{E} \left[X \mid t^* \right] = \mu + \sigma \frac{\phi\left(\frac{t - \mu}{\sigma} \right)}{1 - \Phi\left(\frac{t - \mu}{\sigma}\right)}
$$
and, clearly, $\mathbf{E} \left[X^t \mid t^* \right] = \mathbf{E} \left[X \mid t^* \right] - t$.
Comment: You're totally right :-) it should be correct now
Comment: Shouldn't it be $(t- \mu) / \sigma$ instead of $t$ in the one sided truncation? In wikipedia, they use the parameter $\alpha = \frac{a - \mu}{\sigma}$


White screen of Death after clearing cache, can't find a way to get the site back up

Question: My problem is that I keep getting the white screen of Death ever since I cleared the cache of my Drupal website.
The error is the following :
<code>PHP Fatal error:  Call to undefined function uc_address_property_info() in
sites/all/modules/ubercart/shipping/uc_shipping/uc_shipping.rules.inc on line 12
</code>
It happened after I cleared all the cache using the button from the Drupal configuration page. I'm pretty sure the Ubercart Store module is enabled, and I tried clearing the cache from the database already. Before clearing the cache, the site was working fine. The only thing I did is trying to hide some profile2 fields that I created and since they were still there, I thought that clearing the cache would do the trick.
Answer: If you have Drush, I would try doing another cache-clear. If that doesn't work, I would also try a registry rebuild.
Other than that, just make sure that file exists and that function exists.
Comment: I tried both and it still didn't work. The uc_store.module file exists and the function too.
Comment: Did you get any additional information out of the registry rebuild?


lvs-tun node not connecting

Question: I'm setting up a LVS cluster using tunneling. The goal is to have two director servers (in different datacenters), and a single real server (for the moment, more will be added later in load-balance). The real server is accessed over ports 80, 443 and 8080
I've managed to configure my main director and it's working just fine, all ports are open and data is flowing well
But, the backup director is only able to connect to the real server on port 443. Here's the output I get in /var/log/messages:
Oct 27 12:25:20 vps4252 pulse[2819]: STARTING PULSE AS MASTER
Oct 27 12:25:38 vps4252 pulse[2819]: partner dead: activating lvs
Oct 27 12:25:38 vps4252 lvsd[2821]: starting virtual service https active: 443
Oct 27 12:25:38 vps4252 lvsd[2821]: create_monitor for https/node1 running as pid 2831
Oct 27 12:25:38 vps4252 lvsd[2821]: starting virtual service http_8080 active: 8080
Oct 27 12:25:38 vps4252 lvsd[2821]: create_monitor for http_8080/node1 running as pid 2833
Oct 27 12:25:38 vps4252 nanny[2831]: starting LVS client monitor for 103.13.xxx.xxx:443 -> 103.29.zzz.zzz:443
Oct 27 12:25:38 vps4252 nanny[2833]: starting LVS client monitor for 103.13.xxx.xxx:8080 -> 103.29.zzz.zzz:8080
Oct 27 12:25:38 vps4252 nanny[2831]: [ active ] making 103.29.zzz.zzz:443 available
Oct 27 12:25:43 vps4252 pulse[2823]: gratuitous lvs arps finished

(ignore the missing port 80 lines, I disabled it at the time for testing)
It seems the nanny process is only able to connect to the real server on port 443. Yet, with netcat or curl, I get a correct response over those other 2 ports.
Here's my lvs.cf (as a single server):
serial_no = 36
primary = 103.13.yyy.yyy
service = lvs
backup = 0.0.0.0
heartbeat = 1
heartbeat_port = 539
keepalive = 6
deadtime = 18
network = tunnel
debug_level = NONE
virtual http {
    active = 1
    address = 103.13.xxx.xxx eth0:1
    vip_nmask = 255.255.255.255
    port = 80
    send = "GET / HTTP/1.0\r\n\r\n"
    expect = "HTTP"
    use_regex = 0
    load_monitor = none
    scheduler = rr
    protocol = tcp
    timeout = 6
    reentry = 15
    quiesce_server = 0
    #Define nodes
    server node1 {
        address = 103.29.zzz.zzz
        active = 1
        port = 80
        weight = 1
    }
}
virtual https {
    active = 1
    address = 103.13.xxx.xxx eth0:1
    vip_nmask = 255.255.255.255
    port = 443
    send = "GET / HTTP/1.0\r\n\r\n"
    expect = "HTTP"
    use_regex = 0
    load_monitor = none
    scheduler = rr
    protocol = tcp
    timeout = 6
    reentry = 15
    quiesce_server = 0
    #Define nodes
    server node1 {
        address = 103.29.zzz.zzz
        active = 1
        port = 443
        weight = 1
    }
}
virtual http_8080 {
    active = 1
    address = 103.13.xxx.xxx eth0:1
    vip_nmask = 255.255.255.255
    port = 8080
    send = "GET / HTTP/1.0\r\n\r\n"
    expect = "HTTP"
    use_regex = 1
    protocol = tcp
    #Define nodes
    server node1 {
        address = 103.29.zzz.zzz
        active = 1
        port = 8080
        weight = 1
    }
}

The tunnel on the real server has been set correctly (after all, port 443 is working)
So I am stumped... Is there a way to force the node to be active, even if nanny does not find it?
Answer: This was solved by creating a bash script to ping the real servers, and calling it from the lvs config file

lvs-tun node not connecting


Is there an exisiting file sharing module that allows multiple file upload?

Question: I've been doing some module searching and have had little luck. I was wondering if any of you knew of a file sharing module that has:

Ability to upload multiple files at once
Ability to share files and folders with specific users or all users
Ability to delete or archive files
Ability to upload most types of files

I found most of this functionality in file depot but it doesn't allow multiple files to be uploaded at once.
Answer: Aside from archiving files (I'm not even sure what that means for files in-use on a Node). Media Browser Plus can do all of this:

This is an enhancement module for the Media module. The focus is on UX
  improvements for Media that won't bloat the main module. Currently the
  additions are:

Adding tags to media when uploading
Pulling down title and description information from web based media sources

The module is still in
  development and more features should be coming soon. Based on the
  feature requests in the issue queue and my own thoughts I would
  organize the features for Media Browser Plus into two categories.
  Functional and organizational.
Functional:

Click and drag to select multiple files
Selecting multiple files with shift or ctrl
Searching media
Contextual links and actions

Organizational:

Hierarchical taxonomy based organization e.g. "folders"
Uploading or importing a file structure into a taxonomy hierarchy e.g.
  the directory tree in a zipped upload gets converted into the
  "folders" taxonomy
Updating and applying taxonomies read from media
  files e.g. tags added to images
Personal and public "folders"
Shared "folders" either by user or role

If you have ideas or want to help
  out, please feel encouraged to join in the issue queue. Feedback,
  requests, testing, and patches are always appreciated.
Comment: Thanks for the suggestion. Sadly I've been told to keep looking to try and find something that isn't in beta still.
Answer: There's a multiupload module for FileDepot which integrates Plupload.
This allows for drag-and-drop multiple uploads from the browser into FileDepot.
The module is here: https://www.drupal.org/project/filedepot_multiupload


Expected number of coin flips until number of tails equals number of heads

Question: Here is a simple probability question: An unfair coin with probability of heads equals $p$ is flipped once and lands heads. Compute the expected number of flips until the number of heads equals the number of tails.
The expected number of coin flips to get a tail is 1/(1-p) since it follows a geometric distribution. How to use this to answer the question? Does it have anything to do with catalan numbers?
Thanks.
Comment: This is the Gambler's Ruin problem, with a starting bankroll of 1 dollar.  You want expected time until bankruptcy.  There are many solutions on this site.  Also there is a nice treatment in chapter 12 of Grinstead and Snell's free book https://math.dartmouth.edu/~prob/prob/prob.pdf
Answer: Using linearity of expectation,
$1 + np = n(1-p) \implies n = \frac{1}{1-2p}$
Where $n$ is additional flips after the first.
And given you have the first landing as a head, we need $p \lt \frac{1}{2}$.
Another way to look at it -
I am starting with a difference of $1$ ($1$ head more than tail). So if it takes me $n$ flips to bridge that gap,
$n = 1 + p \times (n + n) \implies n = \frac{1}{1-2p}$ (I either bridge that gap with probability $(1-p)$ or I increase the gap by $1$ with probability $p$).
Comment: @nicomezi I do not think your expression is correct. The reason is this - you are choosing $L$ out of $2L$ flips. But that will have many arrangements where you reach the equal number of heads and tails much earlier. $2L$ has to be the number of flips where you reach equal number of H and T for the first time.
Comment: This is true ! However that does not prove your result but may be thats just me since I have problems with this exercise apparently ...
Comment: Thanks for the answer @MathLover but I'm afraid I don't understand it. Where exactly is the linearity of expectations used in the first approach? Also, where you write 'I either bridge that gap with probability $(1−)$ or I increase the gap by 1 with probability $$', I don't see a $1-p$ in the expression. Could you pls elaborate? Thanks.
Comment: OK I see now. So to your first question, what is the expected number of H in a flip? It is $p$ and for T, it is $(1-p)$ and this expectation is linear for every flip. So in $n$ flips after the first flip which is H, expected number of H = $1 + np$ and expected number of  T = $n(1-p)$.
Comment: On the second, it is the same thing as first but you are just thinking about it differently.  If we are taking $n$ flips, every flip the gap increases by $1$ with probability $p$ and reduces with probability $(1-p)$ and so the increase in gap and decrease in gap are equal after $n$ flips. So $0 = 1 + np - (n-np)$ or $n = 1 +  p (n + n)$