Speed up Eloquent query

Question: I'm trying to query a large amount of data (40K records), and planning to query much larger datasets in the future.  Eloquent seems to take a very long time to load this data. I wondered if there is a faster way to process this data. I'm attempting to look at the validity of my data, and hence checking to see if all fields are null.
I've used regular Eloquent calls. I don't think chunking the data is appropriate as I'm not planning on modifying the data in any way. I debated whether running a job every so often and calling the results of this job might be a better approach.
<code>$journal = Journal::where('issn', $this->issn)->first();
$collection = $journal->outputs;
$collectionUnique = $collection->unique('doi');
$collectionDupes = $collection->diff($collectionUnique);

dd('Total Articles '.$this->getTotal(), 'Total Articles '.count($collection));
</code>
Comment: Does have your tables set indexes and foreign keys? I had similar issue recently and then found, that there were missing indexes in my table and thus the request took ages.
Comment: I've got indexes and foreign keys.
Comment: Can you avoid the use of Eloquent and implement the unique() and diff() with query builder?
Answer: Just use Query Builders !
Why we should use Query Builders for lots of records instead of Eloquent ?!
Here is the reason :

Query Builder is so faster than Eloquent  :

Comparison (Eloquent vs Query Builder ) :

To insert 1000 rows for a simple table Eloquent takes 1.2 seconds and in that case DB facades take only 800 mili seconds(ms).

Another comparison :

Eloquent ORM average response time
<code>Joins | Average (ms)
------+-------------
1     | 162,2
3     | 1002,7
4     | 1540,0

Result of select operation average response time for Eloquent ORM
</code>
Raw SQL average response time
<code> Joins | Average (ms)
------+-------------
1     | 116,4
3     | 130,6
4     | 155,2

Result of select operation average response time for Raw SQL
</code>

For more information : Laravel Eloquent vs Query Builder

Edited :
Your code should be :
<code>$journal = DB::table('journals')->where('issn', $this->issn)->first();
</code>

And Then For using Collection ( Simple way ) :
<code>$journal = Collection::make($journal); //For use Collection Methods
$collection = $journal->get("outputs");//Changed
$collectionUnique = $collection->unique('doi');
$collectionDupes = $collection->diff($collectionUnique);

dd('Total Articles '.$this->getTotal(), 'Total Articles '.count($collection));
</code>
Best Performance :

Use queries and Query Builder instead of collections . Because operations in SQL often is faster .

Please compare time for your last code and this code and please let me know in comments :)
Comment: I cant run $journal->outputs with this (it throws an error).

If I try to run it by searching the journal_id on the output table as Raw SQL queries it takes a long time. Dumping out the collection is fast, I believe its the unique / diff methods on the collection which is slowing it down.
Comment: Yes , Sorry I missed that , Eloquent just has Eloquent Collection , I will Edit this now ;)

Speed up Eloquent query


500 Internal Server Error Wordpress htaccess

Question: My wordpress site says "500 Internal Server Error" after I modify my url site in wordpress setting. Then I google to fix that problem. They suggest to rename my htaccess file in wp file manager and my website load after that but it became a plain html only.
How to fix this problem?
Answer: You'll want to access the database, change the value of the option_value column in the siteurl & home rows in the wp_options table.
Set them to be the url which you used previously, before crashing the site by changing the urls on the settings-page in wp-admin.
Here's a graphic for your reference


Angularjs com Guid em Asp.NET MVC

Question: Estou usando pela primeira vez o AngularJs e gostaria de saber por que isto não é possível, noto que durante o debug, acontece vários erros de Parse dentro do min.js do angular, acredito que seja por que o tipo que estou passando para o controller dele é do tipo Guid. Alguma solução?

@using (Html.BeginForm())
{

                    NOME

                @{
    int classAux = 0;
    string classe;

    foreach (var item in Model)
    {
        if (classAux > 0)
        {
            classe = "warning";
            classAux = 0;
        }
        else
        {
            classe = String.Empty;
            classAux++;
        }

                @Html.DisplayFor(x => item.Nome)

    }
                }

        Editar

}

as tags que inicializam o Angularjs estão em outro arquivo, mas tudo esta funcionando, pois o alert dentro do script funciona quando altero o valor que é passado pelo controller.
Answer: Declaração da div

Chamada do controler setando a variável com o Id do item atual.

        @Html.HiddenFor(x => item.Id)
        @Html.DisplayFor(x => item.Nome)

Controller

Comment: Luiz, se a sua resposta respondeu a sua pergunta, você pode marcá-la como *resposta*. Isso ajuda os outros a identificarem que essa pergunta já foi respondida.

Angularjs com Guid em Asp.NET MVC


My documents in Group Policy

Question: OK, I've done something dumb in Group Policy. Set up a blanket policy to deny users who like to play with the system very restricted access. Now that policy denies access to the My doscument folder which is set to pint to a network documents share. I've gone through the RSOP and can't figure out which policy I've tagged in error. Any ideas?
Comment: Can you edit your question to add some additional information? There isn't really enough detail for anybody to be able to realistically provide you with a useful answer. What settings have you applied? What existing settings already existed? Is this in a test environment? What error messages do users see? What are you actually trying to achieve? etc, etc.
Comment: Bryan. This is a test environment, where I'm trying to tie the users down as much as possible (I'm currently applying the GPO to one user only). Previously, there were no GPO's applied. The user gets a message " This operation has been cancelled due to policies appliedto this computer". No settings have been applied to the computer config in GPO, only user settings have been changed. Folder redirection applies to a network share \\server\documents to which domain users has at least read, read & execute and list rights. I changed too many settings at once, bit of a prattish way to do it really!
Comment: Roll back your changes. Roll them forward ***ONE AT A TIME*** until you find the one that causes the problem, then evaluate that change to decide if it's necessary or not.  For the future don't make a bunch of changes at once -- Do regression testing for each change :-)
Answer: First of all, I'd open Group Policy Management console and navigate to 'Group Policy Objects' and right click the policy, then export/backup all the settings.
Next, open the policy in policy editor and filter the view so that only configured settings are displayed.
Choose a batch of settings (for example in groups of 10 settings), and de-configure them, then test. Repeat until the problem goes away.
Now you know which batch of settings is responsible, you need to isolate the setting that is causing you problems. Restore your policy from the backup you took earlier and tweak  the last batch of settings until you isolate the culprit.
Note this isn't foolproof, as it might be a combination of settings. Unfortunately, it's going to need a bit of work on your part.
If you make any progress, but still have problems, please edit your question with your findings, and I'll come back and try to help further.
Comment: Thanks Bryan. It turned out to be the "prevent access to drives in my computer" which was doing it!I'd already removed these from the Start Menu and Desktop. Propbably a case of out of sight out of mind!! Thanks for you help!
Comment: Glad you managed to fix it.

My documents in Group Policy


Prove unstable singularity is limit of some solution when $t\to-\infty$.

Question: Consider an ODE $x'=f(x)$, where $f:U\to\mathbb{R}^n$ is $C^1$ and $U$ is some open subset of $R^n$.
Supose $x^*\in U$ is an unstable singularity of the ODE, that is:
$f(x^*)=0$ and there is a neighborhood $W$ of $x^*$ such that there are solutions with initial condition arbitrarily close to $x^*$ that leave $W$.
How can I prove that there is at least one non-trivial solution $x$ such that $\displaystyle \lim_{t\to-\infty}x(t)=x^*$?
I'm not sure this existence is necessary, but every example of unstable singularity that I know of satisfies this property.
My approach so far was the following:
$~$
Let $\Phi(t,x)$ be the flow of the ODE and WLOG we can consider $W=B(x^*,r)$ for some radius $r>0$.
By continuity, the hypothesis of there being initial conditions $x_n\to x^*$ that leave $W$ implies that for each $n$ there is a $t_n>0$ where $\Phi(t_n,x_n)=c_n\in S$ where $S$ is the border of $W$.
Since $S$ is compact, by using a subsequence if necessary, we can consider $c_n\to c\in S$.
We can also rewrite $\Phi(t_n,x_n)=c_n$ as $\Phi(-t_n,c_n)=x_n$.
So, in short, I have the following relevant properties:
$\bullet~c_n\to c$ ;
$\bullet~\Phi(-t_n,c_n)=x_n$ ;
$\bullet~x_n\to x^*$ ;
$\bullet~\Phi$ is differentiable (with respect to both $t$ and $x$) .
The last step would be to show that $x(t):=\Phi(t,c)$ is the solution we are looking for, but I couldn't manage to do it.
Comment: I do not think it is true. Consider $\dot x = x$.
Comment: The solutions would be of the form $c\cdot e^t$, which goest to $0$ (the singularity) when $t\to-\infty$. The linear case $x'=Ax$ I know is true because both the existence of a non-trivial solution $x$ such that $\displaystyle\lim_{t\to-\infty}x(t)\to 0$ and $0$ being unstable are equivalent to $A$ having a eigenvalue with positive real part.
Answer: Turns out it is not only false, but also, unlike I said, there is a linear counterexample in $\mathbb{R}^2$:
$x'=
\begin{bmatrix}
0 & 1\\
0 & 0
\end{bmatrix}x
$ .
All the solutions are of the form:
$x(t)=
\begin{bmatrix}
x_0+ty_0\\
y_0
\end{bmatrix}~$ , with $~x_0,y_0\in\mathbb{R}$ .
Clearly, the limit in question only converges if $y_0=0$, in that case $x(t)\equiv
\begin{bmatrix}
x_0\\
y_0
\end{bmatrix}$ , but we were looking for non-trivial solutions, so there are none.


Find inverse of polynomial function

Question: Do you know how I could compute the inverse function of the following polynomial?
$f(x) = x^5+x^3+x$
Thanks in advance.
Comment: Wolfram|Alpha only gives numerical approximate solutions for $f(x)=2$, so there is probably no formula for the inverse of $f$, though I haven't checked that the Galois group of $f$ is not solvable.
Answer: This function probably won't have a nice inverse, since finding the inverse is equivalent to solving the equation $f(x)=c$, or equivalently finding the roots of the equation $x^5+x^3+x-c=0$.  This is a quintic polynomial, and as such probably will likely not have a general solution (i.e. for all $c$) in terms of radicals.  The best you can do is usually some kind of numerical method.
Comment: It is not true that all quintics are unsolvable by radicals. This one might be.
Comment: We're not looking for the roots of $f(x)$, we're looking for the *inverse* of $f$, so roots of $f(x)-c$.
Comment: that's what I see, thanks.
Comment: Well, you would have to show every polynomial in the family $x^5+x^3+x-c$ is solvable.  This sounds more difficult than showing a single polynomial isn't solvable (I'm not a Galois theory expert though)
Comment: Yes. But my point is that the Abel–Ruffini theorem applies only to the *general* quintic, and the one in question is not general.
Comment: In fact, this *is* solvable by radicals, since $f(x)=x(x^2+x+1)(x^2-x+1)$. The roots are $x=0,\pm((1\pm\sqrt{3}i)/2)$.

Find inverse of polynomial function


A question on distributions

Question: Let $\Delta$ be a smooth distribution on a smooth manifold $M$ and let $X,Y$ be 2 vector fields on $M$ which are tangent to $\Delta$ (namely $X(q),Y(q)\in \Delta_q\leq T_qM$ for every $q\in M$.
I would like to show that if $Y(p)=0$ for some $p\in M$, then $[X,Y](p)\in \Delta_p$.
To show this I am trying to mimic the proof of one of the implications of Frobenius theorem. Since $[X,Y]$ can be computed using Lie derivatives we have $$[X,Y](p)=L_XY(p)=\lim_{t\to 0} \frac{(\theta^X_{-t})_{\ast}Y(\theta^X_t(p))-Y(p)}{t}=\lim_{t\to 0} \frac{(\theta^X_{-t})_{\ast}Y(\theta^X_t(p))}{t}$$
How does one conclude that the latter limit lies in $\Delta_p$?
Comment: Don't you mean lies in $\Delta_p$?
Comment: Thank you, I just edited it.
Comment: You write "Let $X$ be a smooth distribution ...", but maybe you mean "Let $\Delta$ be ... "?
Answer: I'm not sure how to make the flow proof work, but here's how to do it using the algebraic properties of the Lie bracket. Let $e_j$ be a local frame spanning $\Delta$ near $p$ and write $Y = Y^j e_j$. Then we have $$[X,Y] = [X, Y^j e_j] = Y^j [X, e_j] + X(Y^j) e_j.$$ Evaluating this at $p$, the first term vanishes because $Y^j(p)=0$, and the second term lies in $\Delta$ because it is a linear combination of the $e_j$.
Comment: It didn't occur to me to proceed this way. This is nice and simple: thank you!
Answer: The vector $X$ is tangent to $\Delta$ by assumption, and so the curve $\theta^X$
is tangent to $\Delta$.  The vector $Y(\theta_t^X(p))$ is in $\Delta,$
and so if we flow it along the curve $\theta$, it stays in $\Delta$.
Comment: Your notation is sloppy here. $\theta^X$ is a flow, not a curve. And your argument is far from clear if the distribution is not integrable. In particular, I cannot see how you're using the hypothesis that $Y(p)=0$.

A question on distributions


Multivariate time series Euclidean distance

Question: I would like to know how to use Euclidean distance to find similarity between two multivariate time series.
Suppose, I have two $N$-variate time series $u$ and $v$, with $u_i(t)$ denoting the $i$-th component of time series $u$ at time $t$.
Would it make sense to calculate distance between values of same parameters and then sum that distances for all parameters to get the final distance?
$$ d_i = \sqrt{(u_i(0)-v_i(0))^2 + (u_i(1)-v_i(1))^2 + … + (u_i(T)-v_i(T))^2}$$
$$ d = d_0 + d_1 + … + d_N$$
Or would it make sense to treat all the values equally, no matter which parameter is considered?
$$\check{d} = \sqrt{
\hphantom{+\,}(u_1(0)-v_1(0))^2 + (u_1(1)-v_1(1))^2 + … + (u_1(T)-v_1(T))^2 \\
+ (u_2(0)-v_2(0))^2 + (u_2(1)-v_2(1))^2 + … + (u_2(T)-v_2(T))^2 \\
+ … \\
+ (u_N(0)-v_N(0))^2 + (u_N(1)-v_N(1))^2 + … + (u_N(T)-v_N(T))^2
}$$
Or to consider distance between each record (values of each parameter at certain point in time):
$$ \hat{d}_0 = \sqrt{(u_1(0)-v_1(0))^2 + (u_2(0)-v_2(0))^2 + … + (u_m(0)-v_m(0))^2}$$
$$ \hat{d}_1 = \sqrt{(u_1(1)-v_1(1))^2 + (u_2(1)-v_2(1))^2 + … + (u_m(1)-v_m(1))^2}$$
$$ \hat{d}_T = \sqrt{(u_1(T)-v_1(T))^2 + (u_2(T)-v_2(T))^2 + … + (u_m(T)-v_m(T))^2}$$
$$ \hat{d} = \hat{d}_0 + \hat{d}_1 + … + \hat{d}_T$$
Or something else?
Example
Multivariate series 1:
power, current, voltage
100, 10, 10
400, 20, 20
900, 30, 30
Multivariate series 2
power, current, voltage
600, 20, 30
1000, 50, 20
450, 15, 30
What would the Euclidean distance look like?
Answer: You should treat values of same parameters as vectors. E. g. $values_1 = (3, 4, 5)$ and $values_2 = (8, 9, 2)$. The distance between dots that are represented by that vectors is the following: $$distance(values_1, values_2) = \sqrt{(3-8)^2 + (4-9)^2 + (5-2)^2} $$
And general formula:
$$distance(u, v) = \sqrt{\sum_{i=0}^{dimensionsCount} (u_i - v_i)^2}$$
That works for any number of dimensions.
As for timeseries, you could measure average distance between corresponding points, squaring is not required as long as you do not intend to penalize one big difference more than several smaller ones.
Comment: Thank you for your answer, but this is only for one point with three parameters, right? But what about series of those? Please check my edited answer.
Comment: @Marko, I updated my answer
Comment: Could you please show what you mean by that on the example I provided? Is this what you suggested a practice (well defined as Euclidean distance), or is it just a way to handle the concrete problem?
Comment: @Marko I am not aware of such practice, so it is just my suggestion for this problem
Answer: When focussing on it as a comparitve measure, the difference between the three ways boils down to whether you sum the squares of the component-wise or record-wise distances (second method) or not (first and third method):
$$ \sqrt{d_0^2 + d_1^2 + … + d_N^2}\\
= \sqrt{\hat{d}_0^2 + \hat{d}_1^2 + … + \hat{d}_T^2}\\
= \check{d} \\
= \sqrt{
\hphantom{+\,}(u_1(0)-v_1(0))^2 + (u_1(1)-v_1(1))^2 + … + (u_1(T)-v_1(T))^2 \\
+ (u_2(0)-v_2(0))^2 + (u_2(1)-v_2(1))^2 + … + (u_2(T)-v_2(T))^2 \\
+ … \\
+ (u_N(0)-v_N(0))^2 + (u_N(1)-v_N(1))^2 + … + (u_N(T)-v_N(T))^2
}$$
Thus, the main effect of the first approach is that the effect of large component-wise distances is attenuated, while with the third approach, the effect of large record-wise distances is attenuated (both in comparison to the second approach). The reason for this is that squaring before adding increases the relative impact of large summands. Whether this is desired or unwanted, depends on your application.
Either way, what you almost certainly want to do, is to normalise your component time series, as otherwise time series with comparably high values will dominate your measure. For instance, in your example, differences in power would dominate differences in the other quantities. As an illustration why this is bad: Your results would depend on your choice of units.
If the measure you use for your components are linearly scaling with what you are actually interested in (e.g., there is no general offset to one component), a reasonable normalisation would be to make all your component time series to have the same mean. Instead of using $u_i$, you use $\tilde{u}_i$ where
$$\tilde{u}_i(t) := \frac{u_i(t)}{μ_i}$$
and $μ_i$ is the mean over $u_i$ and $v_i$ (and possibly other comparable time series at your disposal).
Note that the standard procedure of subtracting the mean or dividing by the standard deviation may have undesired effects. For example, if a component is constant save for measurement errors, this procedure would blow up the error and let the differences of the measurement error play a considerable part in your analysis.
At the end of the day, what is a reasonable normalisation depends on your application and what you want to extract with your analysis.

Note that there are other ways to determine the similarity of time series that may be better suited to your application. For example, the cross-correlation would be a reasonable approach if you are not interested in differences arising due to linear transformations of an entire time series, i.e., you are only interested in a similar (in the geometric sense) temporal evolution. Again, what is best for you depends on your application.
And finally note that it does not make much sense to use a component that is derived from other components (I mention this because in your example, power always is the product of current and voltage).
Comment: Thank you very much for answer and suggestions. "Thus, the main effect of your second approach is that larger component-wise distances play stronger into the final result." - you mean by the first approach? Do you mean to find average of all values for a parameter (for all time series)? Why divide by mean, as I'm aware of it is practice to divide by max value, or to subtract mean and divide by deviation? Do you have a better similarity measure in mind?
Comment: Please check my edited answer, I have added another possibility. I would like not only to check if values of two time series are different, but also to capture correlation of parameters in best way. To see not only if the second series has different values, but also if parameters are correlated. The third way might be the best one because it observes all parameters at the same time. What do you think?
Comment: @Marko: I addressed most of your comments in an edit to my answer. — *To see not only if the second series has different values, but also if parameters are correlated.* – You should do a separate analysis for this, first. — *The third way might be the best one because it observes all parameters at the same time.* – I fail to see how. Also, you did not say, how you want correlations to influence your measure.
Comment: @Marko: If this answer solves your problem, you probably also want to upvote it. If you do not want to, it would be nice, if you could elaborate why.


How can I create a custom field type for a select with multiple values?

Question: I need a field type with 3 select in it. The field type is created and works like a charm but I'd like one of these select may have multiple values. What must I change? I add '#multiple' => TRUE, in the widget. But I can't save my values. I should probably change the type of field in the FieldType but how? Thanks in advance.
<code>/**
 * Provides a field type of resource.
 *
 * @FieldType(
 *   id = "resource",
 *   label = @Translation("Resource"),
 *   default_formatter = "resource_formatter",
 *   default_widget = "resource_widget",
 * )
 */
class ResourceItem extends FieldItemBase {

  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = [];
    $properties['topic'] = DataDefinition::create('string');
    $properties['material'] = DataDefinition::create('string');
    $properties['add_infos'] = DataDefinition::create('string');
    $properties['columns_display'] = DataDefinition::create('string');

    return $properties;
  }

  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'topic' => [
          'type' => 'varchar',
          'length' => '255',
          'not null' => FALSE,
        ],
        'material' => [
          'type' => 'varchar',
          'length' => '255',
          'not null' => FALSE,
        ],
        'add_infos' => [
          'type' => 'varchar',
          'length' => '255',
          'not null' => FALSE,
        ],
        'columns_display' => [
          'type' => 'varchar',
          'length' => '255',
          'not null' => FALSE,
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value1 = $this->get('topic')->getValue();
    $value2 = $this->get('material')->getValue();
    $value3 = $this->get('add_infos')->getValue();
    $value4 = $this->get('columns_display')->getValue();
    return empty($value1) && empty($value2) && empty($value3) && empty($value4);
  }

}
</code>
<code>/**
 * Plugin implementation of the 'topic_widget' widget.
 *
 * @FieldWidget(
 *   id = "resource_widget",
 *   label = @Translation("Resource default"),
 *   field_types = {
 *     "resource"
 *   }
 * )
 */
class ResourceDefaultWidget extends WidgetBase {

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $config = \Drupal::config('resources.config');

    $json_topics = file_get_contents($config->get('global_config.url_api') . '/topics');
    $topics = Json::decode($json_topics);
    $options_topics[0] = '--- Choose topic ---';
    foreach ($topics as $key => $topic) {
      $options_topics[$topic['name']] = ucfirst($topic['name']);
    }
    $element['topic'] = [
      '#type' => 'select',
      '#title' => t('Topic'),
      '#description' => t('List of topics from osteoporosis-foundation'),
      '#options' => $options_topics,
    ];

    $json_materials = file_get_contents($config->get('global_config.url_api') . '/materials');
    $materials = Json::decode($json_materials);
    $options_mat[0] = '--- Choose material ---';
    foreach ($materials as $key => $material) {
      $options_mat[$material['name']] = ucfirst($material['name']);
    }
    $element['material'] = [
      '#type' => 'select',
      '#title' => t('Material'),
      '#description' => t('List of materials from osteoporosis-foundation'),
      '#options' => $options_mat,
    ];

    $json_add_infos = file_get_contents($config->get('global_config.url_api') . '/additional-information');
    $add_infos = Json::decode($json_add_infos);
    $options_add_infos[0] = '--- Choose additional information ---';
    foreach ($add_infos as $key => $info) {
      $options_add_infos[$info['name']] = ucfirst($info['name']);
    }
    $element['add_infos'] = [
      '#type' => 'select',
      '#title' => t('Additional Information'),
      '#multiple' => TRUE,
      '#description' => t('List of additional information from osteoporosis-foundation'),
      '#options' => $options_add_infos,
    ];

    $element['columns_display'] = [
      '#type' => 'select',
      '#title' => t('Number of column to display'),
      '#options' => [
        'null'     => '--- Choose column(s) to display ---',
        'col-md-3' => '1 column',
        'col-md-6' => '2 columns',
        'col-md-9' => '3 columns',
        'col-md-12' => '4 columns',
      ],
    ];

    //setting default value to all fields from above
    $childs = Element::children($element);
    foreach ($childs as $child) {
      $element[$child]['#default_value'] = isset($items[$delta]->{$child}) ? $items[$delta]->{$child} : NULL;
    }

    return $element;
  }

}

</code>
<code>/**
 * Plugin implementation of the 'resource_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "resource_formatter",
 *   label = @Translation("Resource default"),
 *   field_types = {
 *     "resource"
 *   }
 * )
 */
class ResourceDefaultFormatter extends FormatterBase{

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $config = \Drupal::config('resources.config');

    $element = [];

    foreach ($items as $delta => $item) {
      $column_display = $item->columns_display;

      $topics = 'topics=' . str_replace(' ', '+', $item->topic);
      $materials = '&materials=' . str_replace(' ', '+', $item->material);
      $additional_info = '&additional_info=' . str_replace(' ', '+', $item->add_infos);

      $json_all  = file_get_contents($config->get('global_config.url_api').'/all' . '?' . $topics . $materials . $additional_info);

      $all_content       = Json::decode($json_all);

      foreach ($all_content['rows'] as $key => $content){
        $type_explode = explode('-', $content['type']);
        $type = strtolower(str_replace(' ', '_', trim(end($type_explode))));

        switch($type){
          case ('remote_videos'):
            $element[] = [
              '#theme' => 'video',
              '#resource' => $content,
              '#column_display' => $column_display
            ];
            break;
          default:
            $element[] = [
              '#theme' => 'file',
              '#resource' => $content,
              '#column_display' => $column_display
            ];
        }
      }
    }

    return $element;
  }

}
</code>
Comment: Setting '#multiple' returns an array you can't store in a string without serializing it.
Comment: Serialize in [WidgetBase::massageFormValues](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21WidgetBase.php/function/WidgetBase%3A%3AmassageFormValues/9.0.x). Unserialize when setting the default value.
Comment: Posting the code you have written so far is helpful. Also, read this article: https://ixis.co.uk/blog/drupal-8-creating-field-types-multiple-values
Comment: Thanks. Where can I do this?
Answer: I update my code following the 4k4's comment and now it works. Thanks for your help
<code>/**
 * Plugin implementation of the 'topic_widget' widget.
 *
 * @FieldWidget(
 *   id = "resource_widget",
 *   label = @Translation("Resource default"),
 *   field_types = {
 *     "resource"
 *   }
 * )
 */
class ResourceDefaultWidget extends WidgetBase {

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $config = \Drupal::config('resources.config');

    $json_topics = file_get_contents($config->get('global_config.url_api') . '/topics');
    $topics = Json::decode($json_topics);
    $options_topics[0] = '--- Choose topic ---';
    foreach ($topics as $key => $topic) {
      $options_topics[$topic['name']] = ucfirst($topic['name']);
    }
    $element['topic'] = [
      '#type' => 'select',
      '#title' => t('Topic'),
      '#description' => t('List of topics from osteoporosis-foundation'),
      '#default_value' => isset($items[$delta]->topic) ? $items[$delta]->topic : NULL,
      '#options' => $options_topics,
    ];

    $json_materials = file_get_contents($config->get('global_config.url_api') . '/materials');
    $materials = Json::decode($json_materials);
    $options_mat[0] = '--- Choose material ---';
    foreach ($materials as $key => $material) {
      $options_mat[$material['name']] = ucfirst($material['name']);
    }
    $element['material'] = [
      '#type' => 'select',
      '#title' => t('Material'),
      '#description' => t('List of materials from osteoporosis-foundation'),
      '#default_value' => isset($items[$delta]->material) ? $items[$delta]->material : NULL,
      '#options' => $options_mat,
    ];

    $json_add_infos = file_get_contents($config->get('global_config.url_api') . '/additional-information');
    $add_infos = Json::decode($json_add_infos);
    $options_add_infos[0] = '--- Choose additional information ---';
    foreach ($add_infos as $key => $info) {
      $options_add_infos[$info['name']] = ucfirst($info['name']);
    }
    $element['add_infos'] = [
      '#type' => 'select',
      '#title' => t('Additional Information'),
      '#multiple' => TRUE,
      '#description' => t('List of additional information from osteoporosis-foundation'),
      '#default_value' => isset($items[$delta]->add_infos) ? unserialize($items[$delta]->add_infos) : NULL,
      '#options' => $options_add_infos,
    ];

    $element['columns_display'] = [
      '#type' => 'select',
      '#title' => t('Number of columns to display'),
      '#default_value' => isset($items[$delta]->columns_display) ? $items[$delta]->columns_display : NULL,
      '#options' => [
        'null'     => '--- Choose column(s) to display ---',
        'col-md-12' => '1 column',
        'col-md-9' => '2 columns',
        'col-md-6' => '3 columns',
        'col-md-3' => '4 columns',
      ],
    ];

    //setting default value to all fields from above
    /*$childs = Element::children($element);
    foreach ($childs as $child) {
      $element[$child]['#default_value'] = isset($items[$delta]->{$child}) ? $items[$delta]->{$child} : NULL;
    }*/

    return $element;
  }

  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    if($values[0]['add_infos'] != '0'){
      $values[0]['add_infos'] = serialize($values[0]['add_infos']);
    }

    return $values;
  }

}

</code>
Comment: Please post the code updates in the answer.


Why linear regression choose to minimize the residual on y-axis but not the absolute error between prediction and measurement?

Question: Does anyone know why linear regression choose to minimize only $(y_{predict} - y_{measured})^2$, but not $(y_{predict} - y_{measured})^2 + (x_{predict} - x_{measured})^2 $?
Comment: You are addressing the problem of total least square https://en.wikipedia.org/wiki/Total_least_squares which is much more difficult. This is a very good question. (+1)
Comment: Minimizing $2(y_{predict} - y_{measured})^2$ leads to the same estimated coefficients as minimizing $(y_{predict} - y_{measured})^2$, as it just adds a constant factor. Hence, linear regression minimizes both of these objectives.
Comment: See what's the inventor himself said in those days: https://math.stackexchange.com/questions/3645198/query-on-the-standard-deviation-formula/3645250#3645250
Comment: Perhaps see [this Q&A](https://stats.stackexchange.com/questions/118/why-square-the-difference-instead-of-taking-the-absolute-value-in-standard-devia) and related pages.
Answer: The linear regression belongs to the supervised learning methods: the methods that try to generate predictions of a variable (Y) from values of one or more variables(the Xs). X is consequently not predicted, but only observed, as a regressor. Y is the only variable that will be predicted, so you have to minimize the RSS that you wrote.


Find $P(2\bar{X}-\bar{Z}>3\bar{Y})$

Question: Let $(X_{1},X_{2},X_{3},...,X_{8})\sim N(8,16)$ is independent random sample , $(Y_{1},Y_{2},Y_{3})\sim N(1,9)$ is independent random sample and $(Z_{1},Z_{2},Z_{3})\sim N(6,10)$ is independent random sample. Find $P(2\bar{X}-\bar{Z}>3\bar{Y})$.
Their sample means are (respectively) , $\bar{X}\sim N(8,\frac{16}{8})=N(8,2)$ , $\bar{Y}\sim N(1,\frac{9}{3})=N(1,3)$ and $\bar{Z}\sim N(6,\frac{10}{3})$
from here I can not calculate the probability. How can I express $P(2\bar{X}-\bar{Z}>3\bar{Y})$? Any idea will be appreciated.
Comment: @KaviRamaMurthy. Why not just say what you have to say?
Comment: The questioin is meaningless unless you add some independence assumptions.
Comment: The question is still ill-posed.
Answer: Assuming the necessary independence conditions,
Consider that your probability is the same as the following
$$\mathbb{P}[2\overline{X}_8-\overline{Z}_3-3\overline{Y}_3>0]$$
and  the rv $2\overline{X}_8-\overline{Z}_3-3\overline{Y}_3$ is still gaussian....moreover for independence:
$$W=2\overline{X}_8-\overline{Z}_3-3\overline{Y}_3\sim N\left(7;\frac{115}{3}\right)$$
thus
$$\mathbb{P}[W>0]=1-\Phi\left(\frac{-7}{\sqrt{115}}\sqrt{3}\right)\approx 87.09\%$$
Comment: I think $W\sim N(7,\frac{115}{3})$
Comment: I don't get it what you mean
Comment: @softglance : I edited the answer with all the details...Now is it clear?
Comment: @softglance: no, under independence, a linear combination of gaussians is still gaussian. Then use expectaion and variance proerties to calclulate the new mean and variance
Comment: @softglance:  I t hink you are right! I calculated $W=2\overline{X}-\overline{Y}-3\overline{Z}$. Amended

Find $P(2\bar{X}-\bar{Z}>3\bar{Y})$


NT Service\MSSQL$DEV

Question: I have these services running
I was supposed to change only the SQL Server Agent service but by mistake changed couple of SQL SERVER STORAGE PROCESSING SERVICES which was using
NT Service\MSSQL$DEV account. If I had to put it back how would I do it, as this is not a local service account correct? I do not see anything as NT Service locally on the server.
How can I put back the same NT Service account or chose the account so that the password gets filled automatically?
Answer: Assuming MSSQL$DEV is the service name (not the service display name) then that's a virtual account.
From the Service Accounts Step-by-Step Guide:

To configure a service to use a virtual account

Click Start, point to Administrative Tools, and then click Services.

In the details pane, right-click the service that you want to configure, and then click Properties.

Click the Log On tab, click This account, and then type NT SERVICE\ServiceName. When you are finished, click OK.

Restart the service for the change to take effect.

NT Service\MSSQL$DEV


Pulling multiple excel values for VBA SQL query and using IN

Question: I've a below VBA code and I want to read four values a, b, c, d from an excel column (A1:A4) so those can be part of my SQL query IN statement when I connect to database.
I build up the sWHEREclause to create ('a','b','c','d') string that but the final SQL query SQLStr seems to have some error and my code fails.
Can someone please help.
Thank you so much in advance.
Sub ADOExcelSQLServer()

    Dim Cn As ADODB.Connection 'connection variable
    Dim Server_Name As String ' text type
    Dim Database_Name As String
    Dim User_ID As String
    Dim Password As String
    Dim SQLStr As String
    Dim rs As ADODB.Recordset ' Database connection variable
    Dim rRange As Range
    Dim rCell As Range
    Dim sWHEREclause As String
    Set rs = New ADODB.Recordset

    Server_Name = "server name"
    Database_Name = "Database name"

    Set rRange = Sheet1.Range("A1:A4")

    For Each rCell In rRange
        sWHEREclause = sWHEREclause & "'" & rCell & "',"
    Next rCell

    'SQLStr = "Select * from MASTER_QUERY mq where mq.ModelNum in ('a','b','c','d')" 'commented line
    SQLStr = "Select * from MASTER_QUERY mq where mq.ModelNum  IN (" & sWHEREclause & ")"

    Set Cn = New ADODB.Connection 'set connection with databse
    Cn.Open "Provider=SQLOLEDB;Data Source=" & Server_Name & "; Initial Catalog=" & Database_Name & "; Integrated Security=SSPI;" 'connection parameter to the database

    rs.Open SQLStr, Cn, adOpenStatic
     ' Dump to spreadsheet

    With Worksheets("sheet1").Range("b2:z500") ' Enter your sheet name and range here
   ' Range(A1).Value = "ID)"

        .ClearContents ' clear content first in excel
        .CopyFromRecordset rs
    End With
     '            Tidy up
    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing

End Sub

Answer: Your string ends with a ,
do your loop like this:
Dim delim as string
delim = ""
For Each rCell In rRange
    sWHEREclause = sWHEREclause & delim & "'" & rCell & "'"
    delim = ", "
Next rCell


Why are tennis players so bad at serving?

Question: Tennis players spend countless hours working on their serve for years, or decades, just as they do every other shot.
Yet it's entirely common to see even the top players in the world struggle to get significantly more than half their first serves in. The serve is the one shot you are totally in control for, so clearly this is deliberate - but why?
Comment: It's little bit like questioning race car driver's ability, as they crash way more often than average Joe.
Comment: That's because the penalty for crashing out is much higher than the penalty of first-fault.
Comment: Your question is wrong, as the answer shows.  It's a cost-benefit situation.
Comment: Not really. They don't crash out at every 3rd corner.
Comment: They're not playing it safe. They're trying to win points at the first serve and thus deliberately being risky. The fact that they rarely fail the second serve illustrates it quite clearly. It's like a seasoned driver still deliberately going for 200km/h because of his strategy. Accidents will not be a surprise under such circumstances.
Comment: Can anyone explain how this question got 3k views in a couple days in this forum???
Comment: @40-Love, it was included in the Stack Exchange - Sports Weekly Newsletter - Thursday, November 19, 2015, and it is quite an entertaining question too.
Answer: The strategy is indeed deliberate and it comes from a risk/reward evaluation. Keep in mind that the goal of each serve is not simply to have it be in, but to win a point.  Just as the server has been practicing the serve their whole life, the other person has practiced returning serves their whole life.  Pro tennis players are good enough, I'm sure, to get practically every serve in; but when that's the goal, the risk becomes having easily returnable serves wherein the opponent gets the upper hand.  You could look at first serves as the server pushing the boundaries--they want to maximize the possible reward of an ace or a poorly returned serve and in doing so they risk a lower success rates.  On second serves, less of a chance is taken, they knowingly reduce the effectiveness (reward) of the serve in order to minimize the risk (double fault and giving up point).  It's not that they can't control their serve, it's just that they're aiming for the very best serve they're capable of.
You could liken it to a professional soccer player taking a penalty kick.  Sometimes the kick ends up sailing over the goal or to one of the sides.  It's not because the player isn't any good--they could hit the ball into the net 100% of the time practicing by themself--but the fact that a goalie is trying to stop him causes the player to push the limits of his skill and sometimes fail at it.
Comment: Or volleyball serves: Today's volleyball is basically the receiving (= attacking) team almost always winning the point. To have _some_ chance of successfully defending, the serve must be very good, there's (almost) no point in serving easy balls.
Comment: Another analogy might be a baseball pitcher. With a 3-0 count, he's likely to be fairly cautious. At 0-2, though, he's got a lot more flexibility to challenge the batter.


Covering area as much as possible over $[0,1]^2$ keeping the average of each axis above a certain level

Question: Consider two RV's $X_1$ and $X_2$, independently and uniformly distributed over $[0,1]$.
I want to find the largest possible area $A\subset [0,1]^2$ while keeping the average of $X_1$ and $X_2$ inside of $A$ above a certain level, say $y\in(1/2,1)$. For $y\leq 1/2$, it is easy to see that $A=[0,1]^2$ solves the problem, and that's why I excluded $y$'s below $1/2$.
So, the programming problem should be
$$\max_{A\in[0,1]^2}\int_Adx_1dx_2$$
$$s.t. E[X_1|(X_1,X_2)\in A]\geq y~\textrm{and}\\E[X_2|(X_1,X_2)\in A]\geq y.$$
Is there a general solution to this problem or any reference I can have a look to find similar types of problems?
Answer: Adding the two constraints gives $E[X_1 + X_2 \mid (X_1, X_2) ∈ A] ≥ 2y$.  The optimal $A$ under only this weaker constraint is clearly the region $x_1 + x_2 ≥ c$ for appropriately chosen $c$.  Specifically,

if $\frac12 ≤ y ≤ \frac23$, then $c$ is the root of $3 - c^3 = 3(2 - c^2)y$ with $0 ≤ c ≤ 1$;
if $\frac23 ≤ y ≤ 1$, then $c = 3y - 1$.

But since this $A$ is symmetric in $x_1$ and $x_2$, it happens to satisfy the original stronger constraints—so it's optimal under them as well.
Comment: In a parallel way, if we may consider another weaker constraint, say $E[\alpha X_1+(1-\alpha)X_2|(X_1,X_2)\in A]\geq y$, $\alpha\in(0,1)$. If this is the case, can we say $\alpha x_1+(1-\alpha)x_2\geq c$ for an appropriately chosen $c$ can also be a solution to the problem?
Comment: @Andeanlll No: if $a ≠ \frac12$, that solution won't be symmetric in $x_1$ and $x_2$, so it will fail to satisfy the original stronger constraints.
Comment: Got it. Thanks.


Xcode NSException and NSUnknownKeyException

Question: I new to MacOS and Xcode, I have never used them before.
I have to make a simple game using Xcode for my class. I have managed to set everything up (using VirtualBox), watched some tutorial and made a simple Rock, Paper, Scissors game.
The building is successful but when the Simulator starts my app I get an error about one of my three buttons (Paper_Button). Even if I comment the code of the button in ViewController I still get the error. I looked up in my code but nothing... I am sorry for the dumb question but I didn't seem to find any solution.
This is the error:
Exception   NSException *   "[<RPS.ViewController 0x7fdf76008840> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key PAPER_Button."   0x0000600001ab83f0
name    __NSCFConstantString *  "NSUnknownKeyException" 0x00007fff801e80a0
reason  __NSCFString *  "[<RPS.ViewController 0x7fdf76008840> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key PAPER_Button."   0x00006000025e8280
userInfo    __NSDictionaryI *   2 key/value pairs   0x00006000001a10c0
reserved    __NSDictionaryM *   2 key/value pairs   0x00006000014c5fc0

    //
//  ViewController.swift
//  RPS
//
//  Created by MaiorCristian on 4/21/21.
//

import UIKit

//@interface
//SettingsViewController:
//UITableViewController

//BEFORE: UIViewController
//AFTER: UITableViewController

class ViewController: UIViewController {

    var player_points = 0
    var cpu_points = 0

    @IBOutlet weak var CPU_label: UILabel!
    @IBOutlet weak var YOU_label: UILabel!
    @IBOutlet weak var CPU_Image: UIImageView!
    @IBOutlet weak var WINNER: UILabel!

    var playersChoice = 0;
    @IBAction func ROCK_Button(_ sender: Any) {
        playersChoice = 1
        let cpuNumberChoice = Int.random(in: 1...3)
        setCPUimage(imageView: CPU_Image, imageNumber: cpuNumberChoice)

        //rock 1, paper 2, scissors 3

        //rock - rock
        if cpuNumberChoice == 1 && playersChoice == 1 {
            //tie
            WINNER.text = "WINNER: TIE!"
        }
        //paper - rock
        if cpuNumberChoice == 2 && playersChoice == 1 {
            cpu_points = cpu_points + 1
            WINNER.text = "WINNER: CPU!"        }
        //scissors - rock
        if cpuNumberChoice == 3 && playersChoice == 1 {
            player_points = player_points + 1
            WINNER.text = "WINNER: YOU!"        }

        YOU_label.text = "YOU: \(player_points)"
        CPU_label.text = "CPU: \(cpu_points)"

    }

    /*@IBAction func PAPER_Button(_ sender: Any) {
        playersChoice = 2
        let cpuNumberChoice = Int.random(in: 1...3)
        setCPUimage(imageView: CPU_Image, imageNumber: cpuNumberChoice)

        //rock 1, paper 2, scissors 3

        //paper - paper
        if cpuNumberChoice == 2 && playersChoice == 2 {
            WINNER.text = "WINNER: TIE!"        }
        //scissors - papper
        if cpuNumberChoice == 3 && playersChoice == 2 {
            cpu_points = cpu_points + 1
            WINNER.text = "WINNER: CPU!"        }
        //rock - papper
        if cpuNumberChoice == 1 && playersChoice == 2 {
            player_points = player_points + 1
            WINNER.text = "WINNER: YOU!"        }

        YOU_label.text = "YOU: \(player_points)"
        CPU_label.text = "CPU: \(cpu_points)"

    }
    */
    @IBAction func SCISSORS_Button(_ sender: Any) {
        playersChoice = 3
        let cpuNumberChoice = Int.random(in: 1...3)
        setCPUimage(imageView: CPU_Image, imageNumber: cpuNumberChoice)

        //rock 1, paper 2, scissors 3

        //scissors - scissors
        if cpuNumberChoice == 3 && playersChoice == 3 {
            WINNER.text = "WINNER: TIE!"        }
        //rock - scissors
        if cpuNumberChoice == 1 && playersChoice == 3 {
            cpu_points = cpu_points + 1
            WINNER.text = "WINNER: CPU!"        }
        //paper - scissors
        if cpuNumberChoice == 2 && playersChoice == 3 {
            player_points = player_points + 1
            WINNER.text = "WINNER: YOU!"        }

        YOU_label.text = "YOU: \(player_points)"
        CPU_label.text = "CPU: \(cpu_points)"

    }
    ///

        //
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    //@IBAction func

    func setCPUimage(imageView:UIImageView, imageNumber: Int){
        switch imageNumber {
        case 1://rock
            imageView.image = UIImage(named: "IMG_20210421_121204_edit_267680766477383")
        case 3://scissors
            imageView.image = UIImage(named: "IMG_20210421_121232_edit_267656474039366")
        case 2://paper
            imageView.image = UIImage(named: "IMG_20210421_121216_edit_267673424825822")

        default:
            print("error")
            //imageView.image = UIImage(named: "rock")
        }

    }

}

    libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<RPS.ViewController 0x7fdf76008840> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key PAPER_Button.'
terminating with uncaught exception of type NSException
CoreSimulator 732.18.6 - Device: iPhone 11 (BCA23623-0F8A-46DA-BE7F-F3B81149500E) - Runtime: iOS 14.4 (18D46) - DeviceType: iPhone 11
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<RPS.ViewController 0x7fdf76008840> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key PAPER_Button.'
terminating with uncaught exception of type NSException
CoreSimulator 732.18.6 - Device: iPhone 11 (BCA23623-0F8A-46DA-BE7F-F3B81149500E) - Runtime: iOS 14.4 (18D46) - DeviceType: iPhone 11
(lldb)

Comment: Go to Interface Builder and check if the IBAction is properly connected. By the way according to the naming convention function names are supposed to be *lowerCamelCase*.
Comment: You had a variable named `PAPER_Button`, which you created in code, in Storyboard and made the connection between the two. But you removed it later in code, but didn't remove the connection. That's why it's failing. For the rest, naming is important too, so `lowerCamelCase` is strongly suggested.
Answer: The error says PAPER_Button, which is referenced by .xib or .storyboard file, does not exist in your ViewController class.
I guess removing PAPER_Button from .xib or .storyboard file will fix the error.


why 3/8 is not a compound time signature?

Question: If compound time signatures are the result of the following operation
comp. ts = simple ts  x  3/2  (for ex.  6/8 = 2/4 x 3/2)
why 3/8 , that can be the result of  1/4 x 3/2 , is said to be simple rather than compound?
Comment: You seem to think time signatures are fractions. To an extent, they are, but they cannot be simply manipulated like a maths problem.
Answer: The bottom number in time signatures refers to the kind of notes involved - 4 is equivalent to crotchets, 8 to quavers.
The top number refers to how many of those are contained within one bar.
So 3/4 means there are three crotchets per bar, and 3/8 means there are there quavers to a bar. Simple - it's simple time.
Compound times are so called because they can be, and often are, counted in two distinct ways. 6/8, for example, is, from the numbers, 6 quavers, but they're not counted in the same way as 6 quavers in 3/4 time.
6/8 can be thought of as two counts worth 3 quavers each. So instead of counting 123 456, it is often counted 1--2--. This makes it countable in two ways - compound.
6/4, 9/8, 12/8 are other similarly compound time signatures.
Back to 3/8. How could that be counted in more than one way? Only by counting one bar as just 1--. It could work if the piece was very quick, but generally, 3/8 is considered as simple time.
Warning - there are websites that state 3/8 is compound - on the premise that there's an 8 at the bottom! I think they are confusing. 6/8, 9/8 and 12/8 are, but 3/8 just happens to have the same '8' on the bottom. Not a lot to do with compound!
Comment: To my mind, the difference between 3/4 and 3/8 is that the former is conducted in three and the latter is conducted in one.  If a piece isn't fast enough to justify conducting one dotted-quarter-note beat per measure, why would it be written in 3/8?
Comment: @supercat - who knows? Whims of the composer? B.p.m. may help solve this. 3/4 works for me!
Answer: Time signatures are not fractions nor can the be multiplied like fractions. They indicate two things: the number of beats per measure and what size note gets a single beat. Thus 3/8 indicates that measures are three beats long with an eighth note getting one beat. Historically, time signatures also carried some tempo and style information but that convention is not used nowdays.
A top number of 6 or 12 or 9 (or 16 or 24) and a few others indicates a compound signature. For example, a signature of 6/8  represents a measure with 6 eighth notes conventionally grouped in threes. It's almost like two measures of 3/8; in 6/8, there is a secondary accent on the 4th eighth note; in 3/8, the beginnings are accented equally (except for the tendency to group measures in to chunks but that's another story.)
Musical notation has developed historically (rather than being recreated every few years like programming languages). There are conventions. A waltz is commonly written in 3/4 time but could be written in 3/8 (or 3/2). Rags and tangos were often written in 2/4 but with a eighth note pulse (though some composers preferred to write in 4/4 which I find easier to read.)
Answer: The term "compound time signature" typically refers to a time signature which has some number of dotted quarter notes per measure; the duration of each dotted quarter beat three eighth-note beats.  So a 6/8 time signature would be two dotted quarter beats, each consisting of three eighth-note beats.
In 3/8 time, the act of multiplying the three eighth notes per beat by one beat per measure might not be seen as a real "multiplication", and thus some would argue that 3/8 isn't a compound time signature.  I would argue the opposite: the notion of a time signature where the dotted quarter is a beat is more useful than the notion of a time signature which has two arbitrary nested subdivisions.  If a piece of music that's in 6/8 has an occasional 3/8 measure or run thereof, the 3/8 measure should be only be conducted as three discrete beats if the 6/8 measures were conducted as six discrete beats.  If the 6/8 bars were conducted in two (as is more common) the 3/8 bars should be conducted in one.
Note that there is nothing "weird" about the notion of conducting a 3/8 piece in one.  The conductor simply flicks the baton once per measure.  The pieces where that wouldn't make sense would typically be those which are slow enough that they may as well be written in 3/4, or those where a 3/8 measure serves to fill in an odd-length gap (e.g. if a piece of music is in 2/4, but one measure is an eighth-note shorter than usual, it may make more sense to regard that measure as having a full-length quarter note beat and a half-length eighth-note beat than to conduct in in three or one).  In that situation, though, I wouldn't really say that the piece is ever really "in" 3/8 time.  Instead, it's in 2/4 time but has an oddball-length measure.


Lite version of iOS app with changes in scene (storyboard)

Question: I want to create a lite version of my app. When I searched on google, almost all the solutions mentioned to create a duplicate target and set necessary flags (to differentiate between full and lite version).
Now I did the necessary things but in my lite app I want some controls in one scene to be disabled. So how do I do it in the design mode?
With the flag sets I can differentiate between full and lite app while Runtime. But can I make the changes to a scene only for lite app in Design Time?
Or for every scene load, I'll have to check the flag and then do the disable/enable code in runtime.
What are my options? Please help.
Answer: I think the most manageable way is in your code. One example:
- (void)viewDidLoad {
    [super viewDidLoad];

    if (kIsLiteVersion) {
        [someObject setEnabled:NO];
    }
}

Or, perhaps you'd do this in init in some cases (maybe you want to not create certain objects in the lite version). Or, maybe use the condition to determine which storyboard view controller to push in some cases, and have some for the lite version.
Comment: Yes I guess this is what I'll have to do. Thanks Anton for your help.


how to retrieve the request body parameters in magento 2.0

Question: Client request url with some POST data. How can I retrieve that variable using CURL?
I have to retrieve that in JSON format variable and do the operation using those variables.
Answer: we insert our JSON DATA in REQUEST BODY in this form
{ "firstname":"vijay", "secondname":"bokka", "email":"email@example.com" }
as part of api implementation one method will be invoked when api url is trigged.
to that method interface write
apiinvokedmethod($firstname,$secondname,$email)
{
}
you can access value of '$firstname' automatically in the class where you implemented this interface class
NOTE:: The value of KEY in json and name of the METHOD PARAMETERE should be equal


P5.JS Animated GIF shows all frames when it renders

Question: This is my first submitted question. So please go easy!

I have made a very simple run/jump game using p5.js.

Game: https://simongowing1.github.io/the-art-collector-game/
Code: https://github.com/simongowing1/the-art-collector-game

Originally the 'player' was static, but I just added an animated gif (made up of two images) so that it appears to be walking.

When I check in the browser both layers of the gif show at once, so the effect does not work.

I think this is something to do with the rendering of the image. Having checked out some other solutions on stack, I tried 'createImage()' and 'createImg()' instead of simply 'loadimage()' but both of these resulted in other elements from the site disappearing.

Anyone have any ideas? Thanks in advance.

I've pasted my code from the 'game.js' file below for reference
<code>class Game {
constructor() {
    this.backgroundImage;
    this.tokenImage;

}
setup() {
    this.background = new Background();
    this.player = new Player();
    this.tokens = [];
    this.obstacles = [];
}

preload() {
    this.backgroundImage = [
        { src:loadImage('assets/empty_gallery_long.jpg'), x: 0, speed: 1.5}
    ]
    this.playerImage = loadImage('assets/Player1-walking-front.gif');
    this.playerImageBk = loadImage('assets/Player1-walking-back.gif');
    this.tokenImage1 = loadImage('assets/token1.png');
    this.tokenImage2 = loadImage('assets/token2.png');
    this.tokenImage3 = loadImage('assets/token3.png');
    this.obstacleImage = loadImage('assets/Obstacle1.png');
    this.backgroundMusic = createAudio('assets/01 Windowlicker.mp3');
    this.jumpSound = createAudio('assets/jump.mp3');
    this.saleSound = createAudio('assets/Sale.m4a');
    this.breakingSound = createAudio('assets/breaking.m4a')
}

gamelogic() {
    if (counter === remainingTime) {}
}

draw() {
    clear();
    this.background.draw();
    //console.log('hello')
    if (frameCount === 10 || frameCount % 500 === 0) {
        this.tokens.push(new Token(this.tokenImage1))
        //console.log('now');
    }

    this.tokens.forEach(function (token) {
        token.draw();
    })

    this.tokens = this.tokens.filter(
        (token) => {
            if (token.collision(this.player))
            {
                console.log('got it!');
                return false
            } else if (token.x < 0 - token.width) {
                return false
            } else {
                return true
            }
        })

        this.player.draw();

        if (frameCount === 300 || frameCount % 1200 === 0) {
            this.obstacles.push(new Obstacle(this.obstacleImage))
            //console.log('now');
        }

        this.obstacles.forEach(function (obstacle) {
            obstacle.draw();
        })

        this.obstacles = this.obstacles.filter(
            (obstacle) => {
                if (obstacle.collision(this.player))
                {
                   // console.log('CRASH');
                    return false

                } else {
                    return true
                }
            })
</code>
Answer: Split that gif into frames using free online editors like ezgif
Then name all frames in order player1, player2 and so on
and write code like this :-
this.playerImage = loadAnimation('player1', 'player2', 'player3');


Group by 2 columns and sum 2 other columns in MySQL

Question: SQL noob here with a noob question. I have a table like this:
ID   word num_pos num_neg
34   car  1       0
34   car  1       0
100  bus  0       1
123  car  0       1
34   car  0       1
100  bus  1       0
123  bus  0       1
123  car  1       0

What I want is a table that groups all the unique IDs AND words  and sums the num_pos and num_neg columns to get the following output:
ID   word num_pos num_neg
34   car  2       1
100  bus  1       1
123  car  1       1
123  bus  0       1

Also, i would like to filter by word, for example for the word 'car', I would need the following table returned:
ID   word num_pos num_neg
34   car  2       1
123  car  1       1

I think it would probably be quicker to query the word first, then group by and sum, but I dont know.
Thank you all in advance!
Comment: And what was that you tried to do to achieve this?
Comment: What is your PRIMARY KEY?
Answer: You just need to use GROUP BY clause on ID and word, and two SUM aggregate functions:
SELECT ID, word, SUM(num_pos) sum_npos, SUM(num_neg) sum_nneg
FROM yourtable
GROUP BY ID, word

Please see fiddle here.
Answer: Touo must read about GROUP BY (Aggregate) Functions
SELECT ID, word, SUM(num_pos) num_pos, SUM(num_neg) num_neg
FROM tbl
GROUP BY ID, word

Answer: SELECT ID, word, SUM(num_pos), SUM(num_neg)
FROM Sometable
GROUP BY ID, word


Find eigenvalues and eigenvectors of infinite symmetric matrix of powers of two

Question: Let $a_n=2^{-n}$. What are the eigenvalues and eigenvectors of the $\ell^2$ operator represented by the infinite matrix below?
$$A=\begin{pmatrix}
a_1 & a_2 & a_3 & \dots \\
a_2 & a_3 & \dots \\
a_3 & \dots \\
\dots
\end{pmatrix}$$
The relation is $(Av)_i=\sum_j\frac{\alpha_j}{2^{i+j-1}}=\lambda \alpha_i$ where $\alpha_i= \left\langle v,e_i \right\rangle $ and $e_i$ are the standard basis, but it looks to be a horrible mess. Maybe some nice decomposition of $A$ resolves everything? Perhaps the fact each row is half the row above it?
Attempt. Since each row is half the row above it, $(Av)_j=\frac 1{2^{j-1}}(Av)_1=\frac \lambda{2^{j-1}}v_1$, so $Av\propto(1,2^{-1},2^{-2},\dots)$. If $\lambda$ is to be an eigenvector we must have $\sum_n \frac\lambda{2^n}<\infty$, which always holds... What...
Answer: Suppose $Av=\lambda v$. Then as you noted we have $(Av)_j=\frac 1{2^{j-1}}(Av)_1=\frac \lambda{2^{j-1}}v_1$ but also $(Av)_j=\lambda v_j$. Thus we have that $\lambda v_j=\frac \lambda{2^{j-1}}v_1$ so that $v_j=\frac{v_1}{2^{j-1}}$. For $v_1$, we have that $\lambda v_1=(Av)_1=\sum_{n=1}^\infty\frac{v_1}{2^{n-1}2^n}$ which implies that $\lambda=2\sum_{n=1}^\infty\frac{1}{4^n}=\frac{2}{3}$.


jack 3.5mm condenser microphone (SubZero intrument) requiring phantom power, but working better without?

Question: This question has been posted here with no answer, except that "you should probably not use phantom on a mini jack microphone" : Providing phantom power to 3.5mm mic
...However, I've got the Subzero clip on condenser intrument microphone, and the description says it does require phantom !
https://www.gear4music.fr/en/PA-DJ-and-Lighting/SubZero-Instrument-Condenser-Microphone/1OGY
By the way, I can't find any documentation/specification for this mic except this commercial website...
I tried the VXLR adaptor to power it with my MG16XU console. But when I enable the phantom power, I have a highly noisy input while with no phantom, the sound level seems okay... any tips ?
Comment: I have one of those microphones, and it works well with Gear4Music's own SubZero XLR adaptor.
Comment: Which I think is also a DC-DC converter (like the VXLR +) that itself requires phantom, but not the mic. Could you measure the tension between the contacts ?
Answer: Not all VXLR adaptors support phantom power.
For example, here is a 3.5mm mini jack to XLR VXLR adaptor that warns, "It is not compatible with microphones that require plug-in power, such as the VideoMicro". In this case, that's because it's a mono adaptor. You only need a mono mic signal, but you need the phantom power to be passed through on the third connector.
Using a VXLR adaptor that doesn't support phantom power would either just not work, or could possibly cause the symptoms you describe by partially shorting the connectors.
Try to get hold of a VXLR adaptor that definitively does support phantom power.
Comment: it's said that it does not support "plug in power" which is ~2.5V (the one that is mentioned in the thread linked in the question). The Rode VXLR is a simple adapter with the 3 XLR contacts forwarded to the jack TRS. This mention is to differentiate it from the VXLR+, which also acts as a Phantom-Plugin DC-DC converter.
Comment: However, on the mic's description from the vendor website, it's is said it needs "Phantom (48V)" power supply, which is the true phantom...
Comment: The "not compatible" message may be referring to the fact that TRS will short across the wrong contacts as the cable in inserted.
Comment: @hl037_ I'm still not clear which VXLR you're actually using? Anyway, sounds like you're on the case with following that possibility through. Let us know if you do get to the bottom of it.
Comment: I would have added "Pro" or "+" if it was the DC-DC converter version. The one I used was the simple one with just the contacts forwarded, since the vendor pretended it required phantom (on the microphone sold alone page, without adapter). As I said as answer, with a DC-DC conversion, it work.
Answer: The Vendor description is wrong. The microphone does actually require plugin power supply which is not phantom.
I hope they will correct it soon, because it is really misleading.
The microphone works very well with the VXLR pro or +


Does Vm7 in minor key function as dominant?

Question: I heard Vm7 in minor key could be used insted of V7 but In Cm key doesn't it have to have the natural B note to function as dominant ? But how does it work ? If it does not function as one what's its function ?
Comment: Sometimes it may have dominant function, but due to the chord is a m7 chord, it could not have it as "strong".  It would normally have tonic function.  Also, a Vm7 is **extremely** rare.
Answer: In common practice music (that is, music by composers like Bach, Mozart, Beethoven, etc.), the use of minor v7 as a harmony—as opposed to V7—is quite uncommon. When it does occur, it doesn't usually have dominant function at all.
Probably the most common use of this uncommon harmony is in first inversion as a passing chord between a i and a VI: i – min v6 or v6/5 – VI. The reason for the unraised leading tone in this progression is that it has a smoother bass line without an augmented second. If we were in c minor, the bass line would be C – Bb – Ab instead of C – B – Ab. The vast majority of uses of minor v and v7 arise our of similar circumstances; a melodic need to use the natural version of the seventh scale degree exists, so the minor form of v is needed to harmonize it without a huge clash.
Situations like that account for all of the uses of minor v as a harmony that I'm aware of. It should be noted, however, that minor v as a key area is quite common in minor-key pieces. For example, in minor key sonata form works, the most common key for the second half of the exposition is III, but minor v is definitely the next-most common.
It also should be noted that minor v and v7 are perfectly normal and can still have dominant function outside of the major/minor common practice universe. For example, v7 (and bVII) are standard dominant function chords in Mixolydian, Aeolian and Dorian. As a result, there are definitely times you will hear even common practice composers use it as a dominant function chord during modal parts of their music. This is especially common, for example, in Russian Romantic composers like Mussorgsky and Tchaikovsky.
Answer: 'Function' is a concept that belongs to the sort of harmony that is built on the dominant - tonic relationship.  G7 has a dominant relationship to C.  We can extend that to stringing 'secondary dominants' together - Em7, Am7, Dm7, C. We can colour it with tritone substitutions and the like.  But it's still all basically about dominant - tonic progressions. The 'cycle of 5ths thing.
But there's another world of harmony that, apart from perhaps retaining the idea of a tonic, doesn't really deal with function.   There's no function in Cmaj7, Dm7, Em7...  except a vague (and easily diverted) sense of C as 'home'.   Likewise the progression Ab, Bb, C.  Which could easily continue D, E...
If your ear is attuned to functional harmony, you may be able to hear Gm as the dominant of C.  (It can certainly be a secondary dominant in a 'cycle of 5ths' Gm, C, F progression.)   Or we may have entered a less structured type of harmony where a chord is sufficiently justified by being adjacent to the one before.  Or by sharing some notes with it. Or...   And this isn't 'modern, way-out' stuff.  It happens all the time in popular music.


Preencher select multiple com dados armazenados no banco

Question: Boa tarde a todos.
Preciso de uma orientação de vocês com relação a select multiple.
Eu tenho o select abaixo:
<select class="form-control" id="dias_semana" multiple name="diasDaSemana[]" required>
<option value="">Selecione...</option>
<option value="Domingo">Domingo</option>
<option value="Segunda">Segunda-Feira</option>
<option value="Terca">Terça-Feira</option>
<option value="Quarta">Quarta-Feira</option>
<option value="Quinta">Quinta-Feira</option>
<option value="Sexta">Sexta-Feira</option>
<option value="Sabado">Sábado</option>
</select>

Através do select acima estou conseguindo selecionar mais de uma opção e envia para o banco.
Minha dificuldade é apresentar os dados que estão no banco.
Estava tentando fazer assim:
$("#dias_semana").val(diasDaSemana[]);

Mas não funcionou.Como posso fazer isso?
Comment: Você poderia esclarecer o que é o `diasDaSemana[]`? Em javascript isso não significa nada a não ser que seja uma variávei e o `[]` no final irá causar um erro. Eu poderia pensar que o seu objetivo seria selecionar o último item da array `diasDaSemana`, ou até mesmo pegar o elemento com o name=diasDaSemana. Poderia esclarecer, assim eu posso te ajudar melhor.
Comment: @FilipeTeixeira é uma variavel sim.... também não sei explicar, pois peguei isso da net e funcionou para salvar no banco... o problema está em pegar do banco e mostrar pro usuário oque foi salvo... por exemplo.... seleciono Domingo... ai na minha tela de edição... esse select option Domingo, teria que estar marcado. Aqui que estou camelando
Answer: Veja este código:
var diasDaSemana = ["Segunda", "Quarta", "Quinta"];//Deverá ser carregada do banco de dados

$.each(diasDaSemana, function(idx, val) {
  $('#dias_semana option[value=' + val + ']').attr('selected', true);
});

A váriavel diasDaSemana deverá ser carregada do banco de dados, posteriormente o each irá selecionar cada opção.
Comment: segui seu exemplo e não funcionou: https://jsfiddle.net/4yydLL5L/
Comment: resolvido. http://jsfiddle.net/McddQ/1/   obrigada pela explicação.
Comment: Fico feliz. Obrigado por escolher minha resposta. :D
Answer: Um simples plugin para jQuery:
(function($, window) {
  $.fn.replaceOptions = function(options) {
    var self, $option;

    this.empty();
    self = this;

    $.each(options, function(index, option) {
      $option = $("<option></option>")
        .attr("value", option.value)
        .text(option.text);
      self.append($option);
    });
  };
})(jQuery, window);

Usa-se desta forma:
$("#foo").replaceOptions(options);

Fonte: https://stackoverflow.com/a/16654226/5660495
Comment: Pelo que entendi, o usuário não perguntou como substituir as opções pelos valores de uma Array, mas sim selecionar no select os valores que vieram do banco de dados


Downshifting in high positions on violin

Question: I'm having trouble going down to fifth position from a higher position. I often land a little offkey (usually flat by a quarter-step unless I overcompensate), I think because that's where the base of the neck changes shape. It doesn't matter how big or small the shift is, and it happens regardless of whether I'm practicing scales and arpeggios or trying to play a composition. What's really frustrating is that I don't know how to fix it in practice. Can someone suggest a way of practicing this out that won't leave me with a slow glissando every time I need to shift down to fifth?
Comment: Not sure if this helps, but I curve my thumb as I shift down the neck of the violin.
Answer: I haven't played violin for a long time, but as a beginner I used to have a narrow piece of electrical tape on the neck, marking (I think) the third. It came off once I had gained a feel for the position.
Perhaps you could try something similar. Mark the 5th -- it needn't be dead on, just a reference point. Practice pieces and exercises in which you're having this problem. Concentrate on how it feels, physically, to move to the 5th correctly.
When you can do it correctly every time, using the tape for reference, make a point of looking away when downshifting. When you can find the 5th without looking all of the time, the tape can come off for good.
Comment: Thanks for the answer. I might even try something like that. The thing is, coming *up* to fifth I can always hit it dead on. I can even pick up the violin and drop my first finger right on F# on the A-string. I just can't reliably shift *down* to it from higher positions. :/
Comment: Possibly the action of moving your hand down the fingerboard pulls the instrument away from your body some small distance, so the position you feel is right, is different from the position you're used to when moving up to it.
Answer: I practice shifting exercises as part of my warm up routine. This helps with pitch accuracy. They go something like this on my double bass:
A - long tone glissando to A one octave up. Gliss back down to A. Then Bb to Bb, B to B, C to C, etc.
variation:
A to A, Bb to A, B to A, C to A, C# to A, D to A, etc.
On violin, a better note to start with might be F# on the E string, or a B on the A string.
Increase the speed of your glissandos over time, until the gissando is imperceptible to simply playing one note from another. This should be gradual - always strive for slow and accurate improvement over jumping the gun and sacrificing accuracy just to gain some short-term speed improvements.
Next, I'll target specific difficult passages. Like the one you mention above. I will isolate just the shift, in the context of my scales, or more importantly in the context of the piece of music I'm trying to learn. I will practice just the shift, over and over, dozens of times. I will practice it slowly, as slow as it takes to get it perfect, then increase tempo with my metronome very gradually. Never compromise a perfect shift and intonation for a faster tempo, or else you're just practicing making mistakes. I will gradually expand the scope of the excerpt to include more notes before and after, so I can practice 'getting into the shift.'
Sometimes I'll record the target pitches and play it back while I practice to it. Or I'll set a drone pitch to tune to.
Technique-wise, make sure you maintain contact with the string and the neck. Don't your fingers off the string when shifting. The shift is a very tactile, very sense-of-touch oriented movement.
Answer: Your thumb should always be your point of reference in whatever position you're in (yes, even if your thumb is on the right side of the fingerboard). Play a C on your E with your 1, ensure your thumb is placed properly and make note of it. Then try drilling the following while focusing on getting your thumb to the right spot, and then your other fingers:

 Shift from first to fifth position repeatedly playing [ F# C# C# #F ] (first finger). You can mix up the bowing.
Then try fifth to seventh [ C# F# F# C# ]
Now try an octave going from first to fifth to seventh to fifth back to first.
Then try alternating from something higher than seventh down to fifth using just your first finger
Repeat all, keeping the first finger for fifth position, but adding fingers for the others
Now repeat adding fingers to fifth position, but when shifting keep your focus on your thumb and index finger
Drill on other strings
As you drill these, you should start developing a natural frame of reference based on your thumb and index finger, and the rest of your fingers should fall in place :)
Note: it's okay to gliss a bit at first, but by the end of your drilling it should be completely clean.


MySQL slow, but speed up after drop disk caches

Question: I have very busy Linux MySQL server with huge database.
Server usually work on load average 2 or less.
The server have software raid (mdadm) that is currently rebuilding.
Several times today, MySQL get slower and load average reach 200-300-500.
In same time iostat is not big - 20-30% maximum.
Swap is currently turned off, because I thought it causes the problem.
Restart MySQL do not help. If we reboot the server, everything get back to normal for couple of hours.
Last time, instead of reboot I decided to stop MySQL and drop caches. I did in this way:
sync; echo 1 > /proc/sys/vm/drop_caches
sync; echo 2 > /proc/sys/vm/drop_caches
sync; echo 3 > /proc/sys/vm/drop_caches

(Yes I did three in a row)
For my surprise, when I started MySQL, everything get back to normal.
What could be the problem and can I automate the "drop caches" somehow to prevent the server of slow down at least for next couple of days.
Comment: Once you get to this point the problem is resource exhaustion. Shot in the dark: if dropping disk caches makes it *faster* then you're probably low on RAM. If you're not monitoring your server with something like Nagios, you should be. You need to look at historical Memory usage and Disk IO stats in order to properly diagnose something like this instead of subjective break/fix judgements like you've done.
Comment: seems like it was from raid rebuilding. rebuild finished and for the moment server works OK. if next 2-3 days all OK, will post answer.
Answer: Once RAID was rebuilt, we restarted the server once more and then things were back to normal.
We believe, during RAID rebuild, Linux used lots of memory and the server was actually running out of memory.
Answer: Answer could be provided with posting to your original question the following:
RAM   available on the HOST
SHOW GLOBAL STATUS;
SHOW GLOBAL VARIABLES;
SHOW ENGINE INNODB STATUS;


Como validar formato e comparar duas datas para habilitar botões

Question: Estou utilizando um script* para habilitar um botão quando duas validações forem feitas. A primeira verifica o formato, e a segunda se a data inicial é menor que a final, mas estou com alguns problemas pra incluir mais campos com as mesmas funcionalidades, e corrigir algumas inconsistências.
Criei um FIDDLE pra demonstrar o funcionamento na prática, e segue abaixo o código com exemplo verificável. O script já faz a validação (tanto a formatação quanto a comparação) antes de abrir o botão, mas:

Só funciona quando perde o foco, queria que fosse como com onkeyup (quando soltar a tecla), mas
se não tiver jeito pode ser só quando perde o foco mesmo;
Se o usuário, após o botão ter sido aberto, mudar a data para um formato inválido (ou que fique menor que
outro que deveria ser maior), o botão não é desabilitado (e preciso que seja). Preciso que não seja possível o usuário "passar de tela" (trocar de div, veja no fiddle) sem o formato estar correto, e observar a condição de data inicial < data final;
A última data, que faz a comparação com a segunda, chega a abrir a div com a mensagem de erro (quando a data é menor ou está no formato errado), mas mesmo assim envia o formulário (o que não era pra ocorrer);
O campo aceita letras, e só depois que
perde o foco ele dá a mensagem que o formato está errado. Queria que o campo não aceitasse letras, apenas números (é possível fazer com RegExp não?) nem mesmo  a / o que causa problemas porque o usuário às vezes tenta digitá-la.

Estou aberto a outras soluções, inclusive com plugins diferentes do que estou usando pra verificar a formatação, mas já adianto que percorri um longo caminho procurando outra solução e não achei. Ou bem o plugin/script valida a formatação, ou bem valida a comparação das datas, e preciso das duas coisas.
Segue o código:

    // VALIDAÇÃO DO FORMATO PELO FORM.VALIDATOR

// Chama o form.validator

    $.validate({
        modules: 'date'
    });

    // Cria uma classe que verifica se o form.validator foi true, e abre o botão.

    $('.checar')

            .on('validation', function (evt, valid) {
                var validou =  document.getElementById('validou').value = valid ? "true" : "false";

                /* Verifica SE a data está OK */

                if (validou === "true") {
                    verificar(); // chama o script abaixo antes de abrir o botão se o formato está correto
                }
            });

    //VALIDA DATAS EM COMPARAÇÕES

    var primeiradata = document.getElementById('Cinsem');
    var segundadata = document.getElementById('Cdesl22');
    var terceiradata = document.getElementById('Cinsem2');
    var quartadata = document.getElementById ('Cdesl223');
    var quintadata = document.getElementById('Cdatapgtos');

    function gerarData(str) {
        var partes = str.split("/");
        return new Date(partes[2], partes[1] - 1, partes[0]);
    }

    function verificar() {
        var primeira = primeiradata.value;
        var segunda = segundadata.value;
        var terceira = terceiradata.value;
        var quarta = quartadata.value;
        var quinta = quintadata.value;

        // PRIMEIRA DATA X SEGUNDA DATA

        if (primeira.length != 10 || segunda.length != 10) {
            return;
        }
        if (gerarData(segunda) >= gerarData(primeira)) {
            $('#startBtnseg').removeAttr('disabled', 'disabled');
            $('#message1').hide();
        }
        else {
            $('#startBtnseg').attr('disabled', 'disabled');
            $('#message1').fadeIn('slow');
        }
        // TERCEIRA DATA X QUARTA DATA

        if (terceira.length != 10 || quarta.length != 10) {
            return;
        }
        if (gerarData(quarta) >= gerarData(terceira)) {
            $('#startBtnseg2').removeAttr('disabled', 'disabled');
            $('#message2').hide();
        }
        else {
            $('#startBtnseg2').attr('disabled', 'disabled');
            $('#message2').fadeIn('slow');
        }

        //QUINTA DATA X SEGUNDA DATA

        if (quinta.length != 10 || segunda.length != 10){
            return;
        }
        if (gerarData(quinta) < gerarData(segunda)){
            $('#startBtnseg3').attr('disabled', 'disabled');
            $('#message3').fadeIn('slow');
        }
        else {
            $('#startBtnseg3').removeAttr('disabled', 'disabled');
            $('#message3').hide();
        }
    }

<form>

    Primeira data
    <input class="form-control checar" type="text" maxlength="10" placeholder="dd/mm/aaaa"
           onkeyup="formatar('##/##/####', this, event)" name="Tinsem3" id="Cinsem"
           data-validation="birthdate" data-validation-error-msg="Insira uma data válida"
           data-validation-format="dd/mm/yyyy">

    Segunda data
    <input type="text" class="form-control checar" name="Tdesl"  maxlength="10" data-validation="date"
           data-validation-format="dd/mm/yyyy" data-validation-error-msg="Insira uma data válida" placeholder="dd/mm/aaaa"
           onkeyup="formatar('##/##/####', this, event)" id="Cdesl22">

<input type="date" id="Cdesl222" name="Cdesl22" class="checar" hidden="hidden" />

<input type="text" id="validou" name="validou" hidden="hidden" class ="checar" value="false" />

A segunda data deve ser igual ou posterior à primeira data.

<button type="button" class="btn btn-primary btn-sm link" id="startBtnseg"  name="TstartBtnseg"
        data-link="dois" onkeyup="verificar()" disabled="disabled">
     Ir para próximas datas</button>

        A segunda data deve ser igual ou maior que a primeira, e ambas devem estar
        no formato correto (ou seja, não pode aceitar letras, nem mês acima de 13 etc) para abrir o botão.
        Caso o usuário, antes de submeter o formulário (ou depois, se ele voltar) faça qualquer alteração
        que torne o formato inválido, ou torne a data final menor que a inicial, o botão deve ser desabilitado.
        O ideal é que a habilitação/desabilitação do botão seja feita com onkeyup (assim que o usuário
        tirar a pressão da tecla), mas se não tiver jeito pode ser só quando perder o foco mesmo (e eu criaria uma botão
        "falso" para "Checar data", onde o usuário clicaria apenas para o campo perder o foco e realziar a validação).

            Terceira data
            <input class="form-control checar" type="text" maxlength="10" placeholder="dd/mm/aaaa"
                   onkeyup="formatar('##/##/####', this, event)" name="Tinsem3" id="Cinsem2"
                   data-validation="birthdate" data-validation-error-msg="Insira uma data válida"
                   data-validation-format="dd/mm/yyyy">

            Quarta data
            <input type="text" class="form-control checar" name="Tdesl"  maxlength="10" data-validation="date"
                   data-validation-format="dd/mm/yyyy" data-validation-error-msg="Insira uma data válida" placeholder="dd/mm/aaaa"
                   onkeyup="formatar('##/##/####', this, event)" id="Cdesl223">

        <input type="date" id="Cdesl2223" name="Cdesl223" class="checar" hidden="hidden" />

        <input type="text" id="validou3" name="validou" hidden="hidden" class ="checar" value="false" />

A data quarta data deve ser posterior à terceira data.

        <button type="button" class="btn btn-primary btn-sm link" id="startBtnseg2"
                data-link="tres" onkeyup="verificar()" disabled="disabled">
             Próximas!</button>

        Igual a primeira tela, considerando entre a terceira e a quarta datas.

     Quinta data
    <input type="text"  id="Cdatapgtos" name="Tdatapagtos" class="form-control checar" maxlength="10"
           placeholder="dd/mm/aaaa" onkeyup="formatar('##/##/####', this, event)">

A quinta data deve ser igual ou posterior à segunda data.

<button type="submit" id="startBtnseg3" class="btn btn-primary btn-sm" onkeyup="verificar()">
    Submeter formulário</button>

        A quinta data deve ser IGUAL OU POSTERIOR à SEGUNDA DATA, e ambas devem
        estar no formato correto para que o formulário seja submetido. O botão de submeter
        o formulário precisa estar habilitado, e será desabilitado caso as validações não ocorram (formato de data e comparação
        com segunda data). Da mesma forma seria interessante com onkeyup, mas pode ser quando clicar no botão.
        O campo não é obrigatório, mas caso seja preenchido é feita a validação, e habilitado/desabilitado.

</form>

Vários usuários aqui do SOpt me ajudaram a implementar esse script. Veja a série de perguntas:

Habilitar/Desabilitar botão de acordo com a validação de campos
Como comparar duas datas em Javascript ou jQuery
Como converter função .on do jQuery para JavaScript puro
Incompatibilidade entre onkeyup e máscara de data?
Answer: Eu acabei removendo algumas partes do seu código que não achei necessário e adicionei alguns
 para ficar melhor apresentado, além de remover a validação de HTML5.

.message1 {
    font-size: 10pt;
    color: red;
}

<form onsubmit="return verifica('data2', 'data5', false, 3);">

                Primeira data
                <input class="form-control checar" id="data1" type="text" maxlength="10"
           data-funcao="verifica('data1', 'data2', true, 1);">

                Segunda data
                <input class="form-control checar" id="data2" type="text" maxlength="10"
           data-funcao="verifica('data1', 'data2', false, 1);">

        <button type="button" class="btn btn-primary btn-sm link" id="botao1"
          data-link="dois" disabled="disabled">
             OK, vamos continuar!
        </button>

            A segunda data deve ser igual ou maior que a primeira, e ambas devem estar
            no formato correto (ou seja, não pode aceitar letras, nem mês acima de 13 etc) para abrir o botão.
            Caso o usuário, antes de submeter o formulário (ou depois, se ele voltar) faça qualquer alteração
            que torne o formato inválido, ou torne a data final menor que a inicial, o botão deve ser desabilitado.
            O ideal é que a habilitação/desabilitação do botão seja feita com onkeyup (assim que o usuário
            tirar a pressão da tecla), mas se não tiver jeito pode ser só quando perder o foco mesmo (e eu criaria uma botão
            "falso" para "Checar data", onde o usuário clicaria apenas para o campo perder o foco e realziar a validação).

                Terceira data
                <input class="form-control checar" id="data3" type="text" maxlength="10"
           data-funcao="verifica('data3', 'data4', true, 2);">

                Quarta data
                <input class="form-control checar" id="data4" type="text" maxlength="10"
           data-funcao="verifica('data3', 'data4', false, 2);">

        <button type="button" class="btn btn-primary btn-sm link" id="botao2"
          data-link="tres" disabled="disabled">
             OK, vamos continuar!
        </button>

            Igual a primeira tela, considerando entre a terceira e a quarta datas.

                Quinta data
                <input class="form-control checar" id="data5" type="text" maxlength="10"
           data-funcao="verifica('data2', 'data5', false, 3);">

        <button type="submit" id="botao3" class="btn btn-primary btn-sm"
          onclick="return verifica('data2', 'data5', false, 3);">
            Submeter formulário
        </button>

            A quinta data deve ser IGUAL OU POSTERIOR à SEGUNDA DATA, e ambas devem
            estar no formato correto para que o formulário seja submetido. O botão de submeter
            o formulário precisa estar habilitado, e será desabilitado caso as validações não ocorram (formato de data e comparação
            com segunda data). Da mesma forma seria interessante com onkeyup, mas pode ser quando clicar no botão.
            O campo não é obrigatório, mas caso seja preenchido é feita a validação, e habilitado/desabilitado.

</form>

Utilizei aquele mesmo plugin da pergunta sobre horas, mas pra validar a data obrigando a ser uma data válida e faço a verificação do botão no oncomplete dela.
Utilizei o pastebin por causa do problema na hora de puxar o source, então esses são os originais:

Explicação do function verifica(idMenor, idMaior, primeiro, botao)

idMenor vai ser o campo que você vai comparar sendo a data inferior
idMaior vai ser o campo que você vai comparar sendo uma data igual ou posterior
primeiro é uma flag pra saber se meu aviso de data inválida vai ser no primeiro ou segundo id.
botao é pra eu saber qual botão eu preciso travar ou destravar

O segredo pra funcionar
$(document).ready(function(){
    $('.checar').inputmask("dd/mm/yyyy",
                            {
                                "oncomplete": function () {
                                    eval($(this).data("funcao"));
                                }
                            });
});

eval aceita uma string como parâmetro e ele irá executar ela como se fosse código normal, exemplo eval("1 + 3") vai retornar 4.
atribuo uma data-funcao nos input pra saber exatamente quais campos preciso validar e qual a ordem
sobre o submit eu atribui uma função lá também pra retornar false quando a data for inválida, dessa forma ele não é submetido.
oncomplete só é chamado quando ele termina de preencher toda a máscara, se você quiser melhorar esse aviso existe outros eventos que podem ser vistos aqui: https://github.com/RobinHerbots/jquery.inputmask (procure por oncomplete, onincomplete...)

Qualquer problema ou bug, me avise que arrumo.
Comment: @MaiconCarraro Digo isto no caso de usar o plugin na versão que disse estar com problema: *...uma pena ainda não funcionar direito na última versão, fiz um teste de colocar apenas `0` e ele também trava...*
Comment: Aparentemente está perfeito! Vou checar com mais calma daqui a pouco, mas testei aqui as regras e parece que tá perfeito! Valeu!
Comment: Eu adicionei uma informação sobre o `oncomplete` no final da resposta se interessar também.
Comment: @gustavox qualquer dúvida sobre alguma linha, pode falar :)
Comment: sim esse plugin é excelente, uma pena ainda não funcionar direito na última versão, fiz um teste de colocar apenas `0` e ele também trava! :)
Comment: Uma pena mesmo, mas tá funcionando certinho, e uso a jQuery mais atual e não deu problema em nenhum outro script... tá perfeito! :-)
Comment: Sim, eu vou estudar certinho pra aprender, e qualquer coisa pergunto sim. :) Mas acabei de testar aqui no projeto e parece que ficou melhor do que tava em vários aspectos (além do que eu pensava até). Agora por exemplo não dá mais pra entrar com data inválida, porque o próprio script troca o local do número (digitar 4 no começo do mês transforma automático em mês 4, impedindo assim mês 44 por exemplo), ficando bem parecido com o campo `input type:date` com exceção da janelinha com o calendário (o que só atrapalha quando a data não está nos primeiros dias do calendário...). Valeu mesmo!
Comment: Deve ter como tratar as datas inválidas (mês `44` e data com apenas `0`s) dentro do `oncomplete`: caso não seja mínimamente válido, retorne `false`.
Comment: @falsarella o plugin já trata isso antes de chegar no oncomplete :)


integration with trigonometric substitution, is my result correct?

Question: $$\int\frac{\ln x}{x\sqrt{1-4\ln x-\ln^{2}x}}\ dx\left | u=\ln x,\ du=\frac{1}{x},\ x du=dx \right | \\ \int \frac{u}{x\sqrt{-u^{2}-4u+1}}\ xdu\ = \int \frac{u}{\sqrt{-u^{2}-4u+1}}\ du \\ \left | -u^{2}-4u+1=-(u^{2}+4u-1) \right | \\ \\ \left | -(u+2)^{2}+5=-u^{2}-4u+1 \right | \\ \\\int \frac{u}{\sqrt{-(u+2)^{2}+5}}\ du\left | \sqrt{-x^{2}+a^{2}}=\sqrt{a^{2}-x^{2}} \implies a\sin\theta \right | \\ u+2=x\implies\sqrt{5}\sin\theta,\\ dx=\sqrt{5}\cos\theta \ d\theta \\ \int \frac{u+2-2}{\sqrt{-(\sqrt{5}\sin\theta)^{2}+5}}\cdot\sqrt{5}\cos\theta \ d\theta \\ \int \frac{\sqrt{5}\sin\theta-2}{\sqrt{-5\sin^{2}\theta+5}}\cdot\sqrt{5}\cos\theta \ d\theta \\ \int \frac{\sqrt{5}\sin\theta-2}{\sqrt{5(1-\sin^{2}\theta)}}\cdot\sqrt{5}\cos\theta \ d\theta \\ \int \frac{\sqrt{5}\sin\theta-2}{\sqrt{5}\sqrt{\cos^{2}\theta}}\cdot\sqrt{5}\cos\theta \ d\theta \\ \int \frac{\sqrt{5}\sin\theta-2}{\sqrt{5}\cdot \cos\theta}\cdot\sqrt{5}\cos\theta \ d\theta \\ \int \sqrt{5}\sin\theta-2 \ d\theta =-\sqrt{5}\cos\theta-2\theta+c \\ \sqrt{5}\sin\theta=x, \ \sin\theta=\frac{x}{\sqrt{5}}, \ x=u+2 \implies u=\ln x, \ \theta =\sin^{-1}(\frac{\ln x+2}{\sqrt{5}})$$
Comment: Welcome to MSE. I suggest that you type `\sin`, `\cos` and `\ln` in order to get $\sin$, $\cos$, and $\ln$ respectively.
Answer: Yes it's correct. But avoid using $x$ twice for different meanings, as it may lead to confusion.
You have found $\theta$. Now, $\cos\theta = \sqrt{1-\sin^2\theta}$
$\sqrt 5\cos\theta = \sqrt{5(1-\sin^2\theta)}  = \sqrt{5\bigg(1 - (\frac{u+2}{\sqrt5}\bigg)^2}) = \sqrt{5-(u+2)^2} = \sqrt{-u^2-4u+1}$
$ \sqrt 5\cos\theta  = \sqrt{-\ln^2(x) - 4\ln(x) + 1}$
Thus the final solution becomes,
$$I = -\sqrt{-\ln^2(x) - 4\ln(x) + 1} - 2sin^{-1}\bigg(\frac{\ln(x)+2}{\sqrt5}\bigg)+c$$
Comment: $but\ if \ sin\theta =\frac{lnx+2}{\sqrt{5}}\ and\ if\ sin=\frac{a}{c}\\ c^{2}=a^{2}+b^{2} \\ \\ \sqrt{5}^{2}=(lnx+2)^{2}+b^{^{2}}\\ \\ b=\sqrt{5-(lnx+2)^{2}} \\ \\ cos=\frac{b}{c}=\frac{\sqrt{5-(lnx+2)^{2}} }{\sqrt(5)}\\ \\ -\sqrt{5}cos\theta -2\theta +c \\ \\ -\sqrt{5}\cdot \frac{\sqrt{5-(lnx+2)^{2}} }{\sqrt(5)}-2\cdot sin^{-1}(\frac{lnx+2}{\sqrt{5}})+c
$
Comment: Yes, after that $5 - (lnx+2)^2 =5 - ln^2(x) - 4ln(x) - 4 = -ln^2(x) - 4ln(x) +1 $ . Also cancel $\sqrt 5$ from Nr. and Dr.
Comment: yeah I didnt do the operations til the end it matches, ok thanks


Magento Seems Incomplete is it?

Question: I downloaded and installed magento on xampp by bitnami. Here is a screenshot of what i can see once i open localhost/magento :

I was watching a video on youtube about magento but he had a bit different view:

So what i wanted to know was, is my install incomplete? because it lacks the main content it just has the side bar content and the top bar. (Note: In the video the guy had also said that all that was pre-made and he did not add any of that himself) What is it? and if it comes automatically how do i add it? re-install?
Comment: This question better belongs on [MageOverflow](https://magento.stackexchange.com). It is not a programming question, but is specific to Magento.
Answer: Yes that guy did not enter all that himself but he uses the sample data provided by magento itself.
Magento has a sample data archive available that contains sample products and CMS pages to allow you to explore your new Magento installation without having to create everything from scratch.
Note: You cannot install that sample data now. You need to re-install with some more steps.
Here is the magento page about all this.

Magento Seems Incomplete is it?


Reload Windows environnement variables on a Commande Prompt without closing it

Question: How do I reload Windows environment variables on a Command line (CMD) without closing it?
Answer: Yes.
setlocal
... do part  of the script
endlocal
setlocal
... do part 2 of the script
endlocal
setlocal
... do part 3 of the script
endlocal

for as many parts as you want.
The downside is that any changes to the environment that you want to save will be lost at the endlocal command.
There are two ways around this
setlocal
... do part n of the script
endlocal&set keepme=%keepme%&set keepme2=%keepme2%...

or
setlocal
... do part n of the script
set keepme>>keepmefile.txt
endlocal
for /f "delims=" %%a in (keepmefile.txt) do set %%a

which saves the values starting keepme in a file and then reloads them after the endlocal is executed. (I tend to reserve a prefix of $ on variablenames I want to preserve for such purposes)


Are there recent Microsoft changes affecting the behavior of AppInitDLLs registry entry?

Question: I support a product that detects unique key combinations when pressed to launch a notification alert.
This monitoring is done by a dll that is injected.  Originally this was done specifically to winlogon.exe, but due to some changes in Vista we added the reference to our dll in AppInitDLLs to have it injected into every running process.
This is not working on my newest development machine, and some behavior on client machines mimicks the behavior.  Another dll listed, C:\Windows\system32\nvinitx.dll, is still correctly being loaded, but mine is not.
Are there any known recent security patches that may affect this?
Comment: I know you said it's for Vista, but I wonder whether you have come across this article: http://msdn.microsoft.com/en-us/library/dd744762%28VS.85%29.aspx, which requires code-signing.
Comment: Probably to prevent tampered code like the Case of the Malicious Autostart http://blogs.technet.com/b/markrussinovich/archive/2011/02/27/3390475.aspx to run.
Comment: Thanks for the comments.  I've code-signed the dll with no effect, and that link only says it's good practice, not required by default in 7.
Answer: there are no new security changes as far as I know, you can inject any dll (but it must be compatible with the process you are injecting into) like if the process is 32bit your dll must be 32 and if the process is 64bit u need to inject 64bit or odd behavior will appear. another things that there is a new bool value must be set in windows 7 (not sure in vista) that is
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\LoadAppInit_DLLs" must be set to one
Comment: As it turns out, my replacement at that company got on a call with Microsoft support to resolve this one several months ago, but you are absolutely correct, 32 vs 64 bit was the issue.  Also, my apologies for not returning to this earlier to list the answer, anyone who may have read this.