A More Efficient Embedding Method for YouTube Videos

Question: I have created a video gallery comprised of embedded YouTube videos using the Media: YouTube Module. Everything works as expected, but the page load is slow. This is a common issue when embedding many YouTube videos on a page.
Amit Agarwal proposed this solution on his blog which drastically reduces load time. Is there a way to do this with the current Module or custom scripting?
Answer: Yeah, you can essentially follow that approach in Drupal.  I have used a variant on it.
In a MYTHEME_preprocess_html(), do a drupal_add_js() to load in the YouTube Javascript API.
Field out the video media type to add an image if you don't want to use the default YouTube thumbnail.
Create and edit media-youtube-video.tpl.php for your theme; the default is in the media_youtube module folder.  Make the markup match what you want.
Write a MYTHEME_preprocess_media_youtube_video() function to add in any addtional $variables that you may need in your template, like the image if you added one.
Then add a Javascript behavior to .media-video-wrapper so that when the user clicks on the thumbnail, the YouTube video is dynamically created.  You probably also want to add some logic to destroy other videos on the page.
This is actually way easier than it sounds if you are comfortable with PHP for themes.


Cron to run every 2nd wednesday?

Question: I need to find a way to cron a job so that it runs every second wednesday of the month.  Is this possible?
Comment: This [question](http://stackoverflow.com/questions/350047/how-to-instruct-cron-to-execute-a-job-every-second-week) looks to provide an appropriate answer.
Comment: Yeah, but that question's about Tue, not Wed ;) The accepted answer is clever, though.
Comment: >> Yeah, but that question's about Tue, not Wed ;) The accepted answer is clever, though ... what is so hard to change Tue to Wed ?
Comment: 0 * * * 3 test $(date \+%u) -eq 3 && echo "start run me" try this. didn't paste to the answer because one liner question is pretty vague.
Answer: My manpage for crontab (which I sadly can't seem to find online) gives the following example:
# Run on every second Saturday of the month
0 4 8-14 * *    test $(date +\%u) -eq 6 && echo "2nd Saturday"

Adapting this to your purposes...
0 4 8-14 * *    test $(date +\%u) -eq 3 && job.sh

Comment: To anyone looking to edit this answer, the reason you don't just use the day of week field is that if both day of month and day of week are restricted (ie, aren't `*`), the command will run when _either one_ matches.
Comment: I found that I had to escape the %u, so: `date +\%u`
Comment: crontab manpage: http://manpages.debian.org/cgi-bin/man.cgi?query=crontab&sektion=5
Answer: For CentOS 7 servers, this seems to be the syntax that works for me. Please note the spaces around the [ and ]. That took a while for me to figure out.
This runs the test.sh file at 13:07 / 1:07PM on the second Wednesday of the month.
(0=Sunday, 1=Monday, 2=Tuesday, 3=Wednesday, etc.)
07 13 8-14 * * [ `date +\%u` = 3 ] &&  /root/scripts/test.sh

Comment: Working for me on CentOS 8 Stream too, thanks.
Answer: Based on this answer, you could do:
00 12 * * Wed expr `date +\%d` \> 7 \& `date +\%d` \< 15 >/dev/null && runJob.sh

Answer: It's not possible using cron on its own, but you could call a script once a week that does the test:
In crontab, run second_wed.sh at 12.00 every Wednesday:
0 12 * * 3 /home/you/bin/second_wed.sh

In second_wed.sh:
#!/usr/bin/env bash

#get day of month
day_of_month=`date +%d`

#if this day is between 7th and 15th day of the month = 2nd week
if [ $day_of_month -gt 7 -a $day_of_month -lt 15 ]; then
  # Call your program here instead of 'ls'…
  ls
fi

Answer: Fire at 10:15 AM on the third Friday of every month: 0 15 10 ? * 6#3
Source: https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm
Comment: That's so cool. Too bad it isn't supported on most common Linux distros :/
Answer: 7 13 8-14 * 3 /home/you/bin/second_wed.sh

Answer: I would try:
37 2 * * 3 [[ $(($(date +%-V -d '20220208') % 2)) -eq 0 ]] && /path/to/script

This will run the script on Wednesday of every even week of the year. Unfortunately you may hit one week delay when the year has 53 weeks.
Answer: You can avoid running an external script by using a combination of the day of week trick plus the weekday:
# Run on every second Wednesday of the month
0 4 8-14 * Wed job.sh

This also avoids running another external program.  The 8-14 selects all days that match the second week of the month.  Then it filters out just that Wednesday.
Comment: according to this: [crontab.guru](https://crontab.guru/#0_4_8-14_*_Wed) , `cron` will execute the task every day: 8,9,10,11,...,14 at 4AM. So, it is 7 invocations instead of one. I don't want to test it in production))
Comment: @GabrielA.Zorrilla friend, please check the "next invocations" section. Or run something with this settings on your host.
Comment: @maxkoryukov it says ""At 04:00 on every day-of-month from 8 through 14 and on Wednesday." will execute only once, when its Wed and the day in the range 8-14.
Comment: Or better yet, just read the man page:  Note: The day of a command's execution can be specified by two fields — day of  month,  and  day  of week.  If both fields are restricted (i.e., don't start with *), the command will be run when either field matches the current time.  For example,``30 4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.
Comment: In CentOS 8 Stream this certainly didn't work for me - as others have said it tries to run every date specified in the third column.

Cron to run every 2nd wednesday?


Calculate an integral in polar coordinates

Question: I have to calculate the next integral in polar coordinates but it confuses me to calculate the extremes of integration. The condition $x> 1$ confuses me.
$\iint_D 6x dx dy$
$D=\{(x,y)\in \mathbb{R}^2:y\geq 0,x\geq 1, x^2+y^2 \leq 4\}$
Thanks!
Answer: The domain is the region bounded by a circle centered at the origin with radius $2$, the line $y=0$ and the line $x=1$ with the condition $x\ge 1$ that is

therefore

$0\le \theta \le \frac{\pi}3$
$r_{min}(\theta)=\frac 1 {\cos \theta}\le r \le 2$

therefore the set up becomes
$$\iint_D 6x \,dx dy=\int_0^{\frac{\pi}3}\, d\theta\int_{\frac 1 {\cos \theta}}^{2}6r^2\cos \theta \,dr$$
Comment: "The domain is given by an half of a quarter of circle" - not sure what this means, but it's either misleading or flat-out wrong - or maybe a typo and needs editing?
Comment: @NickD Yes it is not much clear in that way. I'm going to add a sketch! Thanks
Answer: Hint:
The equation of a vertical line $x=k$ in polar coordinates is simply $r\cos \theta=k$, so the bounds for $r$ in the integral in polar coordinates are
$$\int_{\tfrac1{\cos\theta}}^2 ...\,\mathrm dr$$
Answer: in polar coordinates $x=r\cos(\theta)$ and $y=r\sin(\theta)$
also $x^2+y^2\le 4$
put $x=r\cos(\theta)$ and $y=r\sin(\theta)$ in $x^2+y^2\le 4$
gives $r\le2$
given $y\ge 0$ and $x \ge 1$ thus   $y^2\le 3$
means  $r\sin(\theta)\le \sqrt3$
$2\sin(\theta)\le \sqrt3$
$\sin(\theta)\le \sqrt3/2$
thus $\theta \le \pi/3$
$$\iint_D 6x \,dx dy=\int_0^{\frac{\pi}3}\, \cos \theta  d\theta\int_{\frac 1 {\cos \theta}}^{2}6r^2\,dr$$


A regression decomposition for dummy variables

Question: Suppose that I have a regression model
\begin{align}
Y = X\beta_X + Z_1 \beta_{Z_1} + Z_2 \beta_{Z_2} + \varepsilon
\end{align}
where $X$ are some controls, and $Z_1$ and $Z_2$ are two sets of dummy ($\{0,1\}$-valued) variables. I assume that $Z_2$ does not depend upon $Z_1$, but $Z_1$ might depend upon $Z_2$ in the sense that the probability that an element of $Z_1$ might be affected by the value of $Z_2$. I would like to decompose the information (variation) in $Z_2$ into a component that affects $Y$ only through $Z_1$, and a residual that affects $Y$ directly.
If $Z_1$ were continuous, I could do something like regress (each coordinate of) $Z_1$ onto $Z_2$, then regress $Y$ on the fitted values. The natural analogue of this, say fitting a logistic (or similar) regression model for $Z_1$ gives up linearity, losing interpretability, and takes much longer to compute.
I would appreciate any insight on literature addressing this or similar problems.
Answer: In the approach you write for the case where the r.v.'s were continuous, you would regress $Z_1$ on $Z_2$ and use the fitted values $\hat Z_1$ in the $Y$-regression. But $\hat Z_1 = \hat E(Z_1\mid Z_2)$. So what you need is the conditional expectation function of $Z_1$ given $Z_2$.
This paper has a nice exposition for the bivariate Bernoulli distribution (as an introduction to the multivariate case).
Denoting  the joint probability $P(Z_1 = 0, Z_2=0)=p(0,0) $ and analogously for the other three possible combinations, the conditional density of $Z_1\mid Z_2$ is (eq. 2.11 of paper)
$$P(Z_1=z_1\mid Z_2=z_2) = \left(\frac {p(1,z_2)}{p(1,z_2)+p(0,z_2)}\right)^{z_1}\left(\frac {p(0,z_2)}{p(1,z_2)+p(0,z_2)}\right)^{1-z_1} $$
Then the conditional expectation function we are looking for is
$$E(Z_1\mid Z_2=z_2) = \frac {p(1,z_2)}{p(1,z_2)+p(0,z_2)} \equiv Z_1^* $$
You will then have to approximate the joint probabilities, creating a standard $2 \times 2$ contingency table of relative empirical frequencies -from which actually you can also test your dependence suspicion: theoretically, $Z_1$ and $Z_2$ will be independent if and only if $p(0,0)\cdot p(1,1) = p(0,1)\cdot p(1,0)$ and you can test this by a Fisher exact test.
Assuming that independence is rejected, then the contigency table will give you the estimated probabilities that you need and you will obtain the regressor
$$\hat Z_1^* = \frac {\hat p(1,z_2)}{\hat p(1,z_2)+\hat p(0,z_2)}$$
..which will produce a series of numbers, as for each observation $j$ of the sample we will use the ratio that corresponds to the value $z_{2j}$ of $Z_2$, i.e. if $z_{2j}=1$ we will have
$$\hat z_{1j}^* = \frac {\hat p(1,1)}{\hat p(1,1)+\hat p(0,1)}$$
etc. $\hat Z_1^*$ is still a binary variable, but not taking the $\{0,1\}$ values any more.
Comment: I agree, this is the way to go if $Z_1$ and $Z_2$ are one-dimensional. This approach suffers some rather severe curse of dimensionality, however. Since I care only about modeling the mean of $Y$, it seems that there should be better approaches? It seems that the paper you reference gives a way of parameterizing the correlation structure. Would you mind making it clearer how I could estimate the conditional means of $Z_1$ without estimating exponentially many parameters in the dimension of $Z_2$?
Comment: Multidimensionality needs some clarifications: you mean that $Z_1$ is a vector of r,v,'s, $\beta_{Z_1}$ is a vector of coefficients and $Z_1\beta_{Z_1}$ is their inner product? (the same question applies to $Z_2$). Also, in such a case, all elements of the random vector $Z_2$ have a dependence relationship with all elements of the random vector $Z_1$?
Comment: Yes, sorry. I said "...$Z_1$ and $Z_2$ are two _sets_ of...", but I could have been clearer. All elements of $Z_2$ _could_ depend upon $Z_1$ (and hopefully whatever procedure I use would give me some information on this).


The complete orthonormal basis on $L^2(-\infty,+\infty)$ about Hermite polynomials.

Question: Prove that $\{\varphi_n(t)=(2^n n! \sqrt{\pi})^{-\frac{1}{2}}e^{-\frac{t^2}{2}}H_n(t)\}_{n=0}^{\infty}$ are the complete orthonormal basis on $L^2(-\infty,+\infty)$ where $H_n(t)$ are the Hermite polynomials.
I have aleady proved $\{\varphi_n(t)\}$ are orthonormal by the trick "Integration by parts". But I have difficulties on proving the completeness. I want to use the denseness of the continuous functions with a compact supported set in $L^2(-\infty,+\infty)$ and use polynomials to approximate those continuous functions, and the use the properties of integral $\int_{-\infty}^{+\infty} e^{-\frac{t^2}{2}}p(t)dt$ where $p(t)$ is a polynomial. But I faied.
I want to know if I am on the right track. And if it isn't correct, what's the right way to do it?
Any kind of help is appreciated and thank you very much in advance!
Comment: Hint: The linear span of Hermite polynomials is the span of all polynomials.
Comment: @TheOscillator So we have to prove that $e^{-t^2/2}\Bbb{R}[t]$ is dense in $L^2$
Comment: @TheOscillator I realize the conclusion and try to use that. As  reuns said, I try  to prove that $e^−{\frac{t^2}{2}}\mathbb{R}[t]$ is dense in $L^2$, but it seems not easy.
Answer: There is a nice machinery for proving that polynomials are dense on certain weighted $L^2$-spaces, which involves some beautiful complex analysis tools. In this particular case, the proof is rather simple and follows from standard Hilbert space theory on $L^2(\mathbb{R})$.
Let $\mathcal{P}$ denote set of polynomials with complex coefficients. According to the comments, we came to agreement that it suffices to prove that
$$ S = \left\{e^{-t^2 /2}p(t): p \in \mathcal{P} \right\}.
$$
forms a dense subspace in $L^{2}(\mathbb{R})$. This is equivalent to proving that the orthogonal complement of $S$ in $L^2(\mathbb{R})$, denoted by $S^\perp$ only consists of the zero function, that is $S^\perp = \{0\}$. Let $f\in S^\perp$, that is
$$ \int_\mathbb{R} f(t)\,t^n \, e^{-t^2 /2}dt = 0 \qquad ,\forall n\geq 0.
$$
Consider the Fourier transform of $f(t)e^{-t^2 /2}$, defined by
$$
F(\xi) := \int_{\mathbb{R}}f(t) e^{-t^2 /2 } \, e^{-it\xi} dt \qquad, \, \xi \in \mathbb{R}.
$$
A simple series expansion (easily justified by the dominated convergence theorem, for instance) shows that
$$
F(\xi) = \sum_{n=0}^{\infty} \frac{(-i\xi)^n}{n!} \underbrace{\int_{\mathbb{R}}f(t)\,t^n\, e^{-t^2 /2} dt}_{=0} = 0 \qquad, \, \forall \xi \in \mathbb{R}.
$$
Since $\varphi(t)=f(t)e^{-t^2 /2} \in L^2$, it follows that by Parseval's theorem that
$$
\int_{\mathbb{R}} \left| f(t)e^{-t^2/2} \right|^2 dt = \int_{\mathbb{R}} \left|F(\xi) \right|^2 d\xi = 0.
$$
This implies that $f(t) \equiv 0$, thus we conclude that $S$ is dense in $L^2(\mathbb{R})$.
Comment: It seems that $Q_{\delta}(t) \notin L^2(\mathbb{R})$


selectize js está atrás do input

Question: Estou usando o selectize e estou com um problema o imput está por trás da minha tabela e os estados só o primeiro está no fundo branco os demais estão transparentes alguém sabe como posso resolver isso?

Segue meu código no Js
$(".js-combo-uf")
.on(
        "change",
        function() {
            var id_estado = $(this).val();
            $
            .ajax({
                type: "GET",
                url: "/listacidades",
                data: ({
                    parametroBusca: id_estado,
                    tipoBusca: 'uf'
                }),
                dataType: 'json',
                success: function(data) {
                    var text = "<select class='form-control' name='cidade' id='selecionar-estados' ><option value=''>Cidade</option>";
                    for (i = 0; i < data.length; i++) {
                        text += '<option value="' +
                        data[i] + '">' +
                        data[i] + '</option>';
                    }
                    text += '</select>';
                    $(".js-combo-cidade").html(text);
                    $('.js-combo-roteiro').prop('selectedIndex', 0);
                    $('#selecionar-estados').selectize();

                }
            });
        });

as bibliotecas que instalei foi:

Comment: Coloque também o HTML e o CSS. Pode ser problema de estilos.
Answer: faltou adicionar os css
<link rel="stylesheet" th:href="@{/css/selectize.css}" />

<link rel="stylesheet" th:href="@{/css/selectize.bootstrap3.css}" />

após adiciona-los, funcionou.
obs: a documentação deles não são bem explicáveis.

selectize js está atrás do input


How to set date display format for jQuery datepicker?

Question: I am using the standard jQuery datepicker in Drupal 7 and I would like to change how it saves and displays dates. Instead of displaying 10/11/2013, I would like it to display as November 10, 2013 for clarity. Is it possible to accomplish this?
Answer: To change how the datepicker displays in your content entry form, go to Structure > Content types > YourType > Manage fields > YourField. Expand the section labeled, "MORE SETTINGS AND VALUES", then select the desired date format from the "Date entry options" select list.
Answer: Check out this
<code> $(function(){
        $("#to").datepicker({ dateFormat: 'yy-mm-dd' });
        $("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){
            var minValue = $(this).val();
            minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
            minValue.setDate(minValue.getDate()+1);
            $("#to").datepicker( "option", "minDate", minValue );
        })
    });
</code>
Answer: For Drupal 9 you can create the new custom library and attach it to some elements. Example of library code :
<code>(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.FAJqueryUiDatepickerLocale = {
    attach: function attach(context, settings) {
      // console.log(drupalSettings);
      $.datepicker.regional['drupal-locale'] = $.extend({
        dateFormat: Drupal.t('dd/mm/yy'),
      }, drupalSettings.jquery.ui.datepicker);
      $.datepicker.setDefaults($.datepicker.regional['drupal-locale']);
    }
  };
})(jQuery, Drupal, drupalSettings);
</code>
Works fine for me.


Theme_hook_suggestions not working

Question: I'm using hook_preprocess_node in a module. In that, I check whether the node type, and on satisfying the condition I'm doing a theme_hook_suggestions. My tpl.php files are inside my modules template folder, It is not taking the tpl file I have suggested. I have searched a lot, but didn't find any solutions
Any solution would be apprecaited
Here is my code
<code>/**
 * Implements hook_preprocess_node().
 */
function mymodule_preprocess_node(&$varaiables) {
  if (isset($varaiables['node'])) {
    $node = $varaiables['node'];
    $field_template_list = $node->field_template_list[$node->language][0]['value'];
      if ($node->type == 'event') {
        $varaiables['theme_hook_suggestions'][] = 'module_name_' . $field_template_list;
      }
   }
}
</code>
Comment: Can you be sure $node->field_template_list[$node->language][0]['value'] always has a value? Also, what is in that field? You'll want to make sure to handle any punctuation etc. that users might be able to enter.
Comment: What is the file name of the template file you are trying to use that isn't working as you expect?
Comment: @rooby. 1. I have dpm the value. It have value. 2. File name I'm using is module-name-$field_template_list.tpl.php. Sorry there is a mistake in the code I have included. I'll update.
Answer: Drupal will not look for template overrides in custom modules, only themes.
If you really want to put a template override in a custom module see the answer to this question.
Extra notes are:

Make sure to handle punctuation and any other undesirable characters in your field value.
field_get_items() is a better way to get the value of a field from a node.
It is generally best to keep your template suggestions in line with what is already there. For example starting this suggestion with 'node__' followed by your custom stuff, like maybe <code>'node__event__' . $field_template_list</code> or something like that. It makes it easier in future to know what kind of template it is.

Theme_hook_suggestions not working


Spline df selection in a general additive Poisson model problem

Question: I've been fitting some time series data using a Poisson general additive model using SAS's PROC GAM. Generally speaking, I've been having it's built-in generalized cross-validation procedure generate at least a decent "starting point" for my single spline, which is a non-linear function of time along with a single parametric term (the one I'm actually interested in).
So far, it's worked rather swimmingly, with the exception of one of my data sets. There are 132 observations in that data set, and GCV suggests a spline of 128 degrees of freedom. That seems...wrong. Very wrong. More importantly, it's also not at all stable. I tried a second approach, using something like a "Change in Estimate" criteria to stop adding degrees of freedom when the estimate of the parametric term stops changing because why continue to add control if nothing's different?
The problem is that the estimate isn't at all stable. I tried the following degrees of freedom, and as you can see, the parametric term bounces around wildly:
DF: Parametric Estimate:
1   -0.76903
2   -0.56308
3   -0.47103
4   -0.43631
5   -0.33108
6   -0.1495
7    0.0743
8    0.33459
9    0.62413
10   0.92161
15   1.88763
20   1.98869
30   2.5223
40-60 had convergence issues
70   7.5497
80   7.22267
90   6.71618
100  5.83808
110  4.61436
128  1.32347

I've no intuition at all about what I should be using in terms of df for this particular bit of data. Any other ideas for how to choose a df? Should I be looking at the significance of the spline?
Doing some more looking between df = 10 and df = 15, it looks like df = 12 is the closest you can come to the estimate generated by 128 and still be in the "reasonable degrees of freedom" range. Along with the linear term, the intercept and the single parametric term, that feels like a pretty heavily saturated model. Is it justifiable to just go with 12?
As a second update, changing the smoothing from spline(t) to loess(t) is resulting in much more well-behaved df estimates - should I just switch to loess smoothing?
Comment: In your dataset with 132 observations, is there an associated count and offset term, implying it is actually a weighted dataset with many more than 132 observations? Because of the mean variance relationship in Poisson RVs, large counts can lead to "model selection" properties which are unfavorable due to the "large sample size".
Comment: The dataset is 132 weeks of data, modeled as counts = model terms + log(person-time) as an offset. The counts never go particularly high - but there are a fair number of zeroes.
Answer: As @M.Berk mentions, GCV is known to undersmooth, primarily because this criterion weakly penalizes overfitting, which tends to result in a very shallow minimum in the GCV criterion as a function of $\lambda$, the smoothness parameter. As the minimum is very shallow, the optimal GCV can occur over a wide range of $\lambda$ estimates. Furthermore, the GCV criterion, as a function of $\lambda$ tends to have multiple minima, which can lead to the instability that you describe. Simon Wood (2011) has a nice illustration of this in his Figure 1.
Wood (2011) also illustrates that AICc doesn't provide much additional benefit over GCV for low to intermediate rank bases used for the smooth functions.
In contrast, REML (and also ML) smoothness selection more strongly penalizes overfit than GCV, and consequently has a much more clearly defined optimum. This leads to more stable estimates of $\lambda$ and much reduced risk of undersmoothing.
Wood (2011) describes REML and ML estimation procedures that are both fast and stable, which he shows improves over existing REML (ML) approaches in terms of convergence. These ideas are available in Simon's mgcv package for R.
As Wood (2011) is behind a paywall, I include a copy of a similar image (the AICc results are not shown here) taken from a set of Simon's slides, available on his website, on smoothness selection methods {PDF}. The figure, from slide 10, is shown below

The two rows reflect simulated data where there is a strong (upper) or no (lower) signal respectively. The left-most panels show a realisation from each model. The remaining panels show how the GCV (middle column) and REML criteria vary as a function of $\lambda$ for 10 data sets each simulated from the real model. In the case of the upper row, notice how flat GCV is to the left of the optimum. The rug plots in these panels shows the optimal $\lambda$ for each of the 10 realisations. The REML criterion has a much more pronounced optimum and less variance in the chosen values of $\lambda$.
Hence I would suggest the approach advocated by Simon Wood for his mgcv package, namely to chose as the basis dimension something that is sufficiently large as to include the flexibility anticipated in the relationship between $y = f(x) + \varepsilon$, but not so large. Then fit the model using REML smoothness selection. If the chosen model degrees of freedom is close to the dimension specified initially, increase the basis dimension and refit.
As both @M.Berk and @BrendenDufault mention, a degree of subjectivity may be required when setting up the spline basis, in terms of selecting an appropriate basis dimension from which to fit the GAM. But REML smoothness selection has proven reasonably robust in my experience in a range of GAM applications using Wood's methods.
Wood, S.N. (2011) Fast stable restricted maximum likelihood and marginal likelihood estimation of semiparametric generalize linear models. J. Royal Statistical Society B 73(Part 1), 3--6.
Comment: @EpiGrad Welcome. Sorry I missed the question at the time; over the past year or two I've been struggling with situations similar to yours and have read Simon Wood's papers on this and feature selection on a number of occasions. Glad I was able to recall some details to help.
Answer: I think your best bet lies outside the smoothing algorithms; consider model parsimony.
You allude to this, but I believe it must become your chief selection criteria. Ask yourself how many "bends" seem reasonable based on the etiology/causality of the processes being modeled. Graph the fitted splines with the plots=components(clm) statement and visually assess the fit. Perhaps the high DF splines are telling a similar story as the low DF splines, except more noisily. In that case, choose a low DF fit.
After all, GAM models are intended to be exploratory.
Having used the gcv option myself, I wonder about its performance under Poisson conditions, sparse data, etc. Maybe a simulation study is due here.
Answer: I typed up the following answer and then realized I have no idea if it's applicable to Poisson regression which I have no experience with. Perhaps people can answer that with some comments.

Personally, I like the advice of B. W. Silverman (1985) "Some aspects of the spline smoothing approach to non-parametric regression curve fitting (with discussion)." (Available without subscription here): try a range of smoothing parameters and pick the one which is most visually appealing.
As he also rightly points out in the same paper, while a subjective approach may be preferred, there is still the need for automatic methods. However, GCV is generally a poor choice as it has a tendency to undersmooth. See, for example Hurvich et al (1998) "Smoothing Parameter Selection in Nonparametric Regression Using an Improved Akaike Information Criterion" (Available without subscription here). In the same paper they propose a new criteria that may alleviate your problem, the corrected AIC which includes a small sample size correction. You may find the Wikipedia description of AICc easier to follow than the paper. The Wikipedia article also includes some good advice from Burnham & Anderson (i.e. use AICc rather than AIC regardless of sample size).
In summary, my suggestions would be, in order of preference:

Pick the smoothing parameter manually via visual assessment
Use the corrected AIC (AICc) rather than GCV
Use the standard AIC


Accumulate all JS warnings and errors during test runs in TestCafe

Question: I would like to be able to access all JS warnings and errors from the Browser Console during test runs. With the "-e" (skip JS errors) flag disabled, the test stops at the first error, so clearly it is looking for them. With this flag enabled, I would like to be able to see which errors (and ideally warnings) fired during test runs.
I've tried using the ClientFunction and window.onerror methods. I've also tried the -r 'reports' flag -- I only see TestCafe errors, not JS errors from the page under test. I've tried "Accessing Console Messages" from https://devexpress.github.io/testcafe/documentation/test-api/accessing-console-messages.html but this only gives messaging thrown by console.log, etc ("Note that this method returns only messages posted via the console.error, console.warn, console.log and  console.info methods. Messages output by the browser (like when an unhandled exception occurs on the page) will not be returned.")

    const installErrorHandler = ClientFunction(() => {
      window.onerror = error => {
          console.log("ERROR::::::");
          console.log(error);
      };
    });

Over in the Clojure space, when using the Etaoin webdriver implementation (on Chrome or Phantom.js), at any point simply performing a

    (get-logs driver)

returns

    {:level :warning,
     :message "1,2,3,4  anonymous (:1)",
     :timestamp 1511449388366,
     :source nil,
     :datetime #inst "2017-11-23T15:03:08.366-00:00"}
 ....
 ....

Including any 'unhandled exceptions'.
Can I not do this in TestCafe?
Answer: Probably your example with window.onerror does not work because it executes later that error occurs. I suggest you extract the error handler into a separate *.js file and inject it using the new testcafe feature: Inject Scripts into Tested Pages.
Look at the following example:
script to inject (log-errors.js):
window.unhandledErrors = [];
window.onerror = (message, source, lineno, colno, error) => {
    window.unhandledErrors.push({ message, source, lineno, colno, error });
}

test:
import { Selector } from 'testcafe';

fixture('Log errors')
    .page('http://example.com')
    .afterEach(async t => {
        const errors = await t.eval(() => window.unhandledErrors);
        console.log(errors);
    });

test('test', async t => {
    //...
});

Run tests by the following command:
testcafe chrome test.js -e --cs=./scripts/log-errors.js

Note that Script Injection feature is available since 1.4.0 version.
Comment: Thanks! -- indeed I was on an older version without the Script Injection feature :) -- I think this will suffice for my Error checking, but i'm assuming a comparable solution to collect Warnings is not possible...


In $\triangle ABC$ AB=13,BC=14,CA=15 . D,E,F lie on BC ,CA,DE respectively . AD ,DE,AF perpendicular to BC,AC,BF. segment DF =M/N(coprime) .M+N?

Question:
In $\triangle ABC$, $AB=13,BC=14,CA=15$. Points $D,E,F$ lie on $BC ,CA,DE$ respectively such that $AD ,DE,AF$ perpendicular to $BC,AC,BF$. Segment $DF$ =$M/N$(coprime). $M+N$ is equal to what ?

What I did -
used herons formula to find area then found $AD$ using it. Using Pythagoras, I found $DC$ as $9$ so $BD$ becomes $5$. Then since  $\triangle DBF\sim\triangle ABC$. Then using similarity got $\frac{AB}{DB}=\frac{BC}{FB}=\frac{AC}{DF}$.
So $13/5=15/DF$. So $DF=75/13$. So $M+N=88$.
Where am I going wrong?
Answer shows $21$
Comment: Is ⩑ supposed to be $\triangle$? Use `$\triangle ABC$` notation. Look up Mathjax
Comment: @ACB thanks a lot
Comment: $\triangle DBF$ is not similar to $\triangle ABC$
Answer:
You already obtained $AD = 12, CD = 9, BD = 5$
In $\triangle ACD, CD:AD:AC = 3:4:5$
As $\angle ADE = \angle ACB$, $\triangle ADE \sim \triangle ACD$. So we obtain,
$DE = \dfrac{36}{5}, AE = \dfrac{48}{5}$
Also as $ABDF$ is cyclic, $\angle ABF = \angle ADE = \angle ACB \implies \triangle ABF \sim \triangle ACD$
So, $AF = \dfrac{52}{5}, EF^2 = AF^2 - AE^2 = 16$
Then $DF = \dfrac{36}{5} - 4 = \dfrac{16}{5} = \dfrac{m}{n}$
$ \therefore m + n = 21$


How to split multi-voice lilypond scores to multiple midi outputs (e.g. for choir practice)

Question: After spending long enough learning lilypond and writing scores for multiple voices, I've often run into the problem of generating individual voice midi/mp3 files from the score. I was surprised to find this was not already a feature or that no one had an easy way to do this since individual voice mp3s are a precious resource for learning a multi-voice piece !
While it is possible to just remove other voices from the score temporarily, compile, rename the midi, change to another voice, compile, rename, etc.. This becomes very tedious very fast.
Plus, I find it helpful to still have the other voices at low volume in the background to have a sense of the harmony.
So I need a way to generate these separate voices from a standard multi-voice score.
Here is a standard lilypond script for a 4-voice example to use as a test file :
\version "2.18.2"

global = {
  \key c \major
  \time 4/4
  \tempo "Allegro" 2 = 60
}

% Lyrics
verseBass = \lyricmode {Ho Ho Hoo, Ho Ho Hoo !
}
verseTenor = \lyricmode {Ha Ha Haa, Ha Ha Haa !
}
verseAlto = \lyricmode {Huu Hu Hu, Hu Hu Huu !
}
verseSoprano = \lyricmode {Hi Hi Hii, Hi Hi Hii !
}

% Music
voiceBass = \relative c {\global c4 b f'2 d4 g, c2 \bar "|."}
voiceTenor = \relative c' {\global g4 b c2 b4 f g2}
voiceAlto = \relative c' {\global e2 d4 g g b, e2}
voiceSoprano = \relative c'' {\global c8e d4 a2 d4 b c2}

% Score stucture
voicePartBass = \new Staff \with {
  instrumentName = "Bass"
  shortInstrumentName = "B"
  midiInstrument = "violin"
} {

  \clef bass \voiceBass
} \addlyrics { \verseBass }

voicePartTenor = \new Staff \with {
  instrumentName = "Tenor"
  shortInstrumentName = "T"
  midiInstrument =  "violin"
} {

  \clef "G_8" \voiceTenor
} \addlyrics {\verseTenor}

voicePartAlto = \new Staff \with {
  instrumentName = "Alto"
  shortInstrumentName = "A"
  midiInstrument = "violin"
} {

  \voiceAlto
} \addlyrics { \verseAlto }

voicePartSoprano = \new Staff \with {
  instrumentName = "Soprano"
  shortInstrumentName = "S"
  midiInstrument =  "violin"
} {

  \voiceSoprano
} \addlyrics {\verseSoprano}

\score {
    <<
      \new ChoirStaff << % choirstaff adds the fancy join on voice staves
        \voicePartSoprano
        \voicePartAlto
        \voicePartTenor
        \voicePartBass
      >>
    >>
    \layout {}
    \midi {}
}

Which outputs

And a midi file with everything.
Answer: TL;DR : You add some tags and there's a bash script at the end which automates the separate midi part generation (for Unix users only, sorry :P)
The midiMaximumVolume option
In my quest for a multi-voice split, I found out about an option called
midiMaximumVolume which can be set within a Staff environment.
By setting this variable to a value between 0 and 1, it's possible to tone down (or entirely suppress) the volume of the staff it's placed within.
This needs to be set for each voice, so it's about as tedious as removing the music variables of other parts and then you still have to do the compiling/renaming shenanigans.
However it's already a great step towards automation of split-voices since it is a single parameter that can be targeted (instead of any custom \myvoice variables one may use...)
Plus, this makes it possible to have the other voices at a low volume in the background by setting them to a lower volume (eg. main voice at 1, others at 0.3).
Introducing a tag system
So the idea is to tag each part in its staff with a name & tag so we can easily detect where to introduce the volume parameter as well as a name for each part (mainly for file-naming). I went with something like this :
%#%part:<part_name>

Which fits in a lilypond comment. It must be placed at the location where the volume option would be set. Using the example above, it would be like so :
% Score stucture
voicePartBass = \new Staff \with {
  instrumentName = "Bass"
  shortInstrumentName = "B"
  midiInstrument = "violin"
} {
  %#%part:Bass
  \clef bass \voiceBass
} \addlyrics { \verseBass }

voicePartTenor = \new Staff \with {
  instrumentName = "Tenor"
  shortInstrumentName = "T"
  midiInstrument =  "violin"
} {
  %#%part:Tenor
  \clef "G_8" \voiceTenor
} \addlyrics {\verseTenor}

Bash magic
Now we have to target each tag and change it into the appropriate commands to use its voice as the main voice with the others in background, and repeat for all tags.
I made this into a bash function ly2partmidi (at the end of the post).
You can now source the function and run
$ ly2partmidi test.ly

which generates test_<part_name1>.midi, test_<part_name2>.midi, etc. in one go !
To modulate the volume (or silence) voices :
$ ly2partmidi <file.ly> <mainvolume> <othervolume>

eg. to remove other voices completely ly2partmidi <file.ly> 1 0 or to have all but the main voice 0 1, default is 1 0.3.
If we set up the test.ly file above properly, and run the function, it generates test_Soprano.midi, test_Alto.midi, test_Tenor.midi and test_Bass.midi files, as expected.
You can also add a midi2mp3 step in there, if you want.
The bash function :

ly2partmidi () {
    lyfile=${1}
    volumeMain=${2:-1} # level of the 'main' voice of a file
    volumeOther=${3:-0.3} # level of the other voices (set to 0 if completely silent)
    tagregex="^\s*%#%part:([a-zA-Z0-9_\-]+)"
    setvolcmd="\\\set midiMaximumVolume = #"

    # find the tags in the .ly file
    mapfile -t fulltags < <(  grep -Po ${tagregex} ${lyfile} )
    tagnames=()

    for t in ${fulltags[@]} ; do
        t1=$(echo $t | sed -E "s/${tagregex}/\1/")
        tagnames+=("$t1")
    done

    # get unique of each tag
    fulltags=($(echo "${fulltags[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
    tagnames=($(echo "${tagnames[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))

    # for each tag...
    for i in ${!fulltags[@]}; do
        ft=${fulltags[$i]}
        t=${tagnames[$i]}

        echo -e "\n--- Generating part [$t] ..."
        echo -e "\tCopying lilypond script"
        # make temp copy of .ly
        t_lyfile=${lyfile/.ly/_$t.ly}
        cp -f $lyfile $t_lyfile

        echo -e "\tReplacing tags with midiVolume cmd"
        # replace tags with the midiVolume cmds
        sed -i -E "s/${ft}/${setvolcmd}${volumeMain}/g" $t_lyfile
        sed -i -E "s/${tagregex}/${setvolcmd}${volumeOther}/g" $t_lyfile

        echo -e "\tRunning lilypond engraving to generate midi"
        # generate midi
        lily_o=${t_lyfile/.ly/}
        lilypond -s -dno-print-pages -o $lily_o $t_lyfile

        rm $t_lyfile

    done
}

Answer: Your solution obviously works, but you don't need any compile/rename/rinse/repeat shenanigans.
You can put multiple \score blocks in one file. Each of those blocks will typeset the music into some file if it has the \layout block inside of it, and it will put MIDI into some file if it has the \midi block inside of it. So you can add another score block that would look along these lines:
\score {
    \new Staff \with {
        midiInstrument = "saxophone"
        midiMinimumVolume = #1
        midiMaximumVolume = #1
    } \new Voice \soprano
    \new Staff \with {
        midiInstrument = "acoustic grand"
        midiMinimumVolume = #0.4
        midiMaximumVolume = #0.4
    } \new Voice \alto
    % etc for \tenor and \bass
    % NO \layout block!!
    \midi {}
}

This will make a file your-filename-0.midi with your soprano played by a loud saxophone and the other parts by a quiet piano. You didn't put a \layout block in it, so it will typeset no music, just make the MIDI. Rinse & repeat for the other three voices.
Of course you can further automate this. I use this function (which I pilfered somewhere years ago, I don't remember where):
rehearsalMidi = #
(define-music-function
 (parser location name midiInstrument lyrics) (string? string? ly:music?)
 #{
     \unfoldRepeats <<
         \new Staff = "sopran" \new Voice = "sopran" { s1*0\f \sopran }
         \new Staff = "alt" \new Voice = "alt" { s1*0\f \alt }
         \new Staff = "tenor" \new Voice = "tenor" { s1*0\f \tenor }
         \new Staff = "bas" \new Voice = "bas" { s1*0\f \bas }
         \context Staff = $name {
             \set Score.midiMinimumVolume = #0.5
             \set Score.midiMaximumVolume = #0.5
             \set Score.tempoWholesPerMinute = #(ly:make-moment 100 4)
             \set Staff.midiMinimumVolume = #1.0
             \set Staff.midiMaximumVolume = #1.0
             \set Staff.midiInstrument = $midiInstrument
         }
         \new Lyrics \with {
             alignBelowContext = $name
         } \lyricsto $name $lyrics
     >>
 #})

Now I just add blocks like this,
\book {
    \bookOutputSuffix "sopran"
    \score {
        \rehearsalMidi "sopran" "soprano sax" \slovaI
        \midi { }
    }
}

one for each voice. The three arguments to \rehearsalMidi are: the voice whose part it is, the instrument that part should be played on, and the lyrics to go with that. Since we call the four voices soprán, alt, tenor and bas in Czech, I use these names for my voices, but you will surely be able to tinker with the function to make it meet your needs. The book and bookOutputSuffix just make the file names nicer, e. g. my-filename-sopran.midi, my-filename-alt.midi etc. instead of my-filename-0.midi etc.
By the way, when you write this one time, you can copy&paste it into all of the choral music you typeset (which is what I'm doing several years already :)).
Comment: Wow, that's a very good approach as well ! I'm not experienced enough in lilypond's language to make functions like yours, so I went with an 'outside' approach to automation and keep lilypond only for the music.
Comment: I have a question on your function, though : If it does not typeset any music, what's the point of having the lyrics added ?
Comment: @RoB, the function is just a "source code generator", it just writes a larger block of source code. Nothing complicated. // The lyrics get embedded into the MIDI somehow. I guess that some programs can then make advantage of it (esp. programs that "convert" MIDI back to score).
Answer: Nancho Alvarez, LilyPond typesetter of Tomás Luis de Victoria's scores (Partituras de Tomás Luis de Victoria), wrote a C program that splits MIDI tracks into separate MIDI files: splitmidi.c.
Answer: As interesting as these answers are, there's a good case for a low-code solution that doesn't require external Bash scripts, C programs, or defining new functions. It uses two basic functions built into LilyPond: output file names (https://lilypond.org/doc/v2.22/Documentation/notation/output-file-names) and includes (https://lilypond.org/doc/v2.22/Documentation/notation/including-lilypond-files).
Consider the following directory hierarchy:
┌─ base
├─┬─ music
│ └─── example.ily
│
├─┬─ score
│ └─┬─ audio.ily
│   ├─ example.ily
│   └─ printed.ily
│
├─┬─ words
│ └─── example.ily
│
└─── compile.ly

The contents of your base folder are just three directories (music, words, score) and one compile file (compile.ly).
Inside your music and words folders are simply the .ily files containing, respectively, your music and words variables.
Inside your score folder is one .ily file that uses two \include statements to reference two other .ily files:

a \book and \score block that only results in printed music (printed.ily)
several \book and \score blocks that only result in audio files (audio.ily)

How does it look?
compile.ly
\version "2.22.0"
\include "./music/example.ily"
\include "./words/example.ily"
\include "./score/example.ily"

music/example.ily
sop = \relative c' {
  c4 d e f
  e d e2
}
alt = \relative c' {
  e4 f g a
  g fis g2
}
ten = \relative c' {
  c2 b
  a g
}
bas = \relative c {
  a2 e'
  a, a
}

words/example.ily
sop_words = \lyricmode {
  so -- pra -- no
  words they are here
}
alt_words = \lyricmode {
  al -- to words be
  here yo ho
}
ten_words = \lyricmode {
  ten -- or
  words -- ies
}
bas_words = \lyricmode {
  gol -- lum
  gol -- lum
}

score/example.ily
\include "./printed.ily"
\include "./audio.ily"

score/printed.ily
\book {
  \bookOutputName "my_printed_score"
  \score {
    <<
      \new ChoirStaff <<
        \new Voice = "sop" \sop
        \new Lyrics \lyricsto sop \sop_words
        \new Voice = "alt" \alt
        \new Lyrics \lyricsto alt \alt_words
        \new Voice = "ten" { \clef "treble_8" \ten }
        \new Lyrics \lyricsto ten \ten_words
        \new Voice = "bas" { \clef bass \bas }
        \new Lyrics \lyricsto bas \bas_words
      >>
    >>
    \layout {}
  }
}

score/audio.ily
\book {
  \bookOutputName "midi_sop"
  \score {
    \new Staff \sop
    \midi {}
  }
}
\book {
  \bookOutputName "midi_alt"
  \score {
    \new Staff \alt
    \midi {}
  }
}
\book {
  \bookOutputName "midi_ten"
  \score {
    \new Staff \ten
    \midi {}
  }
}
\book {
  \bookOutputName "midi_bas"
  \score {
    \new Staff \bas
    \midi {}
  }
}

As I said above, the two functions that make the difference here are bookOutputName and include.
Using bookOutputName, you're able to produce multiple files—in this case, one that will only have the soprano music, another with only the alto music, etc. Of course, if you desire, you can add other instruments and control how loud they are and their stereo positions (left ear / right ear), among other options:
\book {
  \bookOutputName "midi_sop_bas"
  \score {
   <<
    \new Staff \with {
      midiMinimumVolume = #0.8
      midiPanPosition = #-1
    } \sop
    \new Staff \with {
      midiMaximumVolume = #0.5
      midiPanPosition = #1
    } \bas
   >>
    \midi {}
  }
}

(The reason for bringing up \include is to comment out % the \include "./printed.ily" file when you are fine with how the music looks and only want to tweak the way it sounds. Compiling MIDI alone with no layout block is often orders of magnitude faster.)
In this case, all you would need to do now is put a few more \book and \score blocks in, order and structure them the way you want to hear your MIDI files, and then, if you're so inclined, use them in \include statements (or don't) to control which ones are getting compiled.


$\mathbb{Q}(\sqrt{6},\sqrt{10},\sqrt{15})=\mathbb{Q}(\alpha, \beta),$ for some $ \alpha $ and $\beta$?

Question: Let $\mathbb{Q}\subseteq\mathbb{Q}(\sqrt{6},\sqrt{10},\sqrt{15})$ be a extension of $\mathbb{Q}$, i need to show the elements of  $Gal(\mathbb{Q}(\sqrt{6},\sqrt{10},\sqrt{15})\mid\mathbb{Q})$ the Galois group asociate to this extension, i know that is enogth knowing were the root of the minimal polynimials of $\sqrt{6},\sqrt{10}$ and $\sqrt{15}$ are asigned, to create the automorphisms, but i had notice that $\sqrt{6}=\sqrt{3}\sqrt{2},\sqrt{10}=\sqrt{5}\sqrt{2}$ and $\sqrt{15}=\sqrt{3}\sqrt{5}$, my question is, there is a way to show that the field $\mathbb{Q}(\sqrt{6},\sqrt{10},\sqrt{15})$ is of the form $\mathbb{Q}(\alpha,\beta)$ for some $\alpha,\beta$ depending of $\sqrt{2}, \sqrt{3}$ and $\sqrt{5}$, any clue?
Comment: One way you could show this is via the proof of the primitive element theorem.
Comment: And indeed, geometric considerations show that for any "random" element $\beta$ of your field $K$, $K=\Bbb Q(\beta)$.
Answer: To answer the question in the title,
$\mathbb{Q}(\sqrt{6},\sqrt{10},\sqrt{15})=\mathbb{Q}(\sqrt{6},\sqrt{10})$ because $\sqrt{6}\sqrt{10}=2\sqrt{15}$ implies $\sqrt{15} \in \mathbb{Q}(\sqrt{6},\sqrt{10})$.


Como eu elimino a primeira variável para fazer testes com a variável t-1?

Question: Importo os arquivos do Excel mas não consigo defasar a varíavel no R. A função lag ela elimina a primeira observação e não consigo usar a nrow ou algo parecido. Como eu faria? Queria usar para fazer o teste de Berenblutt-Webb
Comment: Bota o código que você utilizou para ler a planilha?
Answer: Tente a função lag do pacote dplyr. Ela possui um argumento default que pode ser usado para completar os valores anteriores. No caso usei NA.
library(dplyr)

df <- data.frame(
  dia = seq(from = as.Date("2017-01-01"), length.out = 100, by = 1),
  x = 1:100
)

df <- df %>%
  mutate(
    x_lag = lag(x, n = 1, default = NA)
  )

head(df)

         dia x x_lag
1 2017-01-01 1    NA
2 2017-01-02 2     1
3 2017-01-03 3     2
4 2017-01-04 4     3
5 2017-01-05 5     4
6 2017-01-06 6     5


Search for product displays based on info from products in Commerce

Question: I have a website with various articles of clothing for sale. Here's how I have it set up:
Product Display content items:
Mens V-Neck Tshirt
Mens Tank Top Tshirt
Womens Tshirt
Childrens Tshirt

Product content items (in Commerce):
Mens V-Neck Tshirt - Red - Large
Mens V-Neck Tshirt - Blue - Large
Mens Tank Top Tshirt - Green - Small

etc...
Colors (Red, Blue, Green) and sizes (Large, Small, etc) are set up as Select-List fields with the Enable this field to function as an attribute field on Add to Cart forms option enabled.
I need to allow my shoppers to search for shirts that have Red as an available color, or that have Small as an available size. So if they searched for shirts that are Red and Small, they would receive no results based on the product list above, but if they search for Green and Small, they would see the Mens Tank Top Tshirt product display item in their search results.
How can I set this up? With Views/exposed filters, perhaps? Or...?
Thanks!
Answer: Use Commerce Search API module. Basically you are gonna have to set up Facets to achieve what you want.
This screen cast here walks you through on which modules you have to enable and how to tweak your configurations.


Textblock error with inline text

Question: I'm presently learning WPF and C# programing with Visual Studio 2015.
I actually get an error using TextBlock in XAML which I don't understand.
Using this code:
    <TextBlock>
        Text example
    </TextBlock>

VS shows me the following error:
A value of type 'String' cannot be added to a collection or dictionary of type 'InlineCollection'.
This error doesn't prevent compilation and the application still work but it makes programming harder as my error list box is full of messages as for every inline text there is an error message.
The only way I found to prevent the situation is to put texts with the Text="" property but this method makes formatting text way much harder.
Anybody have a solution for this issue?
Thanks.
Edit:
I should have wrote a real example of code from the book I'm reading to clarify the question:
<TextBlock FontSize="14"
    TextWrapping="Wrap">
        <Bold><Italic>Instructions:</Italic></Bold>
        <LineBreak />
        Select a <Underline>font</Underline> to view from the list <Italic>below</Italic>.

        You can change the text by typing in the region at the bottom.

</TextBlock>

That represent the kind of formatting I want to do.
Comment: @Jim: You're right! I did the same and found out that if I target .Net 4.6 instead of 3.5 the errors clears out. Thanks to have made me think of testing this!
Comment: Whenever you put a string as a `TextBlock` content it actually is converted to a `Run` inline and added to the `Inlines` collection (note that `TextBlock` is decorated with `[ContentProperty("Inlines")]` attribute. I think the error stems from the fact that the designer sometimes fails with the conversion (I don't know why though). So as cumbersome as it is, you can put all the strings in between `` tags and that should make the errors go away (since `Run` has `[ContentProperty("Text")]`, which is a string, so no conversion is required.
Comment: Your TextBlock code.... works perfectly fine
Comment: @Grx70: You're right, it's cumbersome! But as it clear my error list it will make studying and practicing easier.  So I will use it for the time of my learning.
Comment: @Jim, I know the code works but not without showing errors.
Comment: @sevynos I made an empty project, tested the code you provided, and worked without any error. Must be something else ... you forgot to mention.
Answer: We can use Run for inline style like
       <TextBlock>
      <Run Text="Hello World"></Run>
      <Underline>
          <Run Text="Hello World"></Run>
      </Underline>
        <Bold>
             <Run Text="Hello World"></Run>
        </Bold>
       </TextBlock>

Comment: Thanks for the demo code, tried it and it works flawlessly.
Answer: What you should do is this:
 <TextBlock Text="Text example">

What kind of formatting are you trying to do?  You can do things like:
 <TextBlock Text="Text example" FontSize="45" FontWeight="Bold">

There are many more options.  VS2015's Intellisense can help you discover what attributes are available.
Comment: You can look back at my question, I did an edit with some code from the book I'm using as a course.
Answer: The solution is the selection of .Net version as seen in the last comment to the question.

Textblock error with inline text


Subquery returned more than 1 value, this is causing UPDATE statement to fail

Question: I would like to update a column(PullFilesReady) in a table with 1 value if any of the value for a given key (i.e. 'blackbox','camera') in @JSON(I am storing JSON in a column) recordset is > 0. update code works for values when there is only one key:value > 0  but update code fails where there are multiple key:value > 0.
Ask::
I would like to have column PullFilesReady updated to 1 when either of the given key:value in @json is greater than 0. and if none of the value is >0 the set PullFilesReady to 0.
sample data in JSON format and also in Tables
select @json
>>>>
 {
    "blackbox": 1,
    "camera": 1,
    "config": 0,
    "events": 0,
    "isi_printf": 0,
    "kinematic": 0,
    "tool_table": 0
}

select * FROM OPENJSON(@JSON, '$') AS x where x.[Value] > 0

>>>>
key         value   type
blackbox    1       2
camera      1       2

Implementation
        UPDATE [HB].[Heartbeats]
        SET [HB].[Heartbeats].[PullFilesReady] = (
            SELECT
            CASE
                WHEN
                    [ResultSet].[Value] >0
                    THEN
                        1
                ELSE
                    0
            END
            FROM OPENJSON(@JSON, '$') AS ResultSet where ResultSet.[Value] > 0
        )
        WHERE [HB].[Heartbeats].SystemName = @system

Error Message::

Msg 512, Level 16, State 1, Line 34 Subquery returned more than 1
  value. This is not permitted when the subquery  follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Comment: The error message is quite clear -- multiple values match in the subquery. You *can* eliminate the error using `select top (1)` or aggregation.  The right thing to do depends on your data and how you want to fix this problem, which you have not explained.
Comment: using `SELECT TOP(1) CASE ` helped in this regards. @GordonLinoff let me edit my post so that question is bit clear.
Comment: @GordonLinoff I have edited question, please can you take a look?
Answer: You may try with the following statement using EXISTS and OPENJSON() (for parsing the JSON in the RecordSet column):
UPDATE [HB].[Heartbeats]
SET [PullFilesReady] = CASE
   WHEN EXISTS (
      SELECT 1
      FROM OPENJSON([RecordSet], '$')
      WHERE ([key] IN ('blackbox', 'camera')) AND ([value] > 0)
   ) THEN 1
   ELSE 0
END
WHERE [SystemName] = @system


Erro ao ler arquivo de texto linha a linha

Question: Estou tentando ler um arquivo muito grande linha a linha e adicionando em uma lista, porém quando chega em um determinado ponto recebo um erro: System.OutOfMemoryException
Existe alguma forma de ler este arquivo todo em uma única só vez?
while ((line = trPlaces.ReadLine()) != null)
{
    var htmlLine = line.Split('\t');

    try
    {
        var newPlace = new Place
        {
            Id = htmlLine[0],
            Name = htmlLine[2],
            IsoCountry = htmlLine[8],
            Latitude = htmlLine[4],
            Longitude = htmlLine[5],
            Admin1 = htmlLine[10].Length == 1 ? "0" + htmlLine[10] : htmlLine[10],
            Admin2 = htmlLine[11],
            PlaceType = htmlLine[7],
            AlternativeNames = htmlLine[3].Split(',')
        };

        if(listPlaces1.Count< 4000000)
        {
            listPlaces1.Add(newPlace);
        } else
        {
            listPlaces2.Add(newPlace);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

Answer: Uma opção para ler o arquivo todo de uma vez e carregá-lo em um array é:
var arrLinhas = File.ReadAllLines(@"C:\Desenv\Texto.txt");

Uma sugestão para poupar memória seria não carregar todos os objetos na lista de uma vez. Você poderia criar uma classe para instanciar os objetos apenas quando eles forem utilizados.
Por exemplo:
public class PlaceFactory
{
    private string[] _places;

    public PlaceFactory(string filepath)
    {
        _places = File.ReadAllLines(filepath);
    }

    public Place ObterPlace(int index)
    {
        var htmlLine = _places[index].Split('\t');

        var place = new Place()
        {
            Id = htmlLine[0],
            Name = htmlLine[2],
            IsoCountry = htmlLine[8],
            Latitude = htmlLine[4],
            Longitude = htmlLine[5],
            Admin1 = htmlLine[10].Length == 1 ? "0" + htmlLine[10] : htmlLine[10],
            Admin2 = htmlLine[11],
            PlaceType = htmlLine[7],
            AlternativeNames = htmlLine[3].Split(',')
        };

        return place;
    }
}

class App
{
    static void Main()
    {
        var placeFactory = new PlaceFactory(@"C:\Desenv\Texto.txt");

        Place place;

        place = placeFactory.ObterPlace(2);
        place = placeFactory.ObterPlace(0);
    }
}


Determinant of a non-square matrix tell you if it is non-linear?

Question: Suppose a matrix $A = $\begin{pmatrix}
1 & 0 & 0\\
0 & 1 & 0\\
0 & 0 & 1\\
0 & 0 & 0
\end{pmatrix}
How can we argue that the vectors are independent if we can't take the determinant?
Comment: What is a non-linear vector?
Comment: Non linear or independent?
Comment: Sorry independent
Answer: Assuming that what you're asking is to determine whether or not the columns are linearly independent, the answer is, yes, they are. That's so because there is a maximal square submatrix whose determinant is not $0$: take the matrix which consists of the first $3$ lines. Here, I say that a square submatrix is maximal if there are no larger square submatrices.
Answer: Use the definition of linear independence: Consider an arbitrary linear combination $$a(1,0,0,0)+b(0,1,0,0)+c(0,0,1,0)=(a,b,c,0)$$ of the columns of this matrix. The only way for this to equal the zero vector is for $a=b=c=0$, therefore the columns are linearly independent.


Seeking help to Prove The Recursive Binomial Coefficient Formula

Question: A rich body of research exists on Binomial Coefficients, with the concept finding its roots in Pascal's Triangle. My current investigation focuses on a Recursive Approach for generating these coefficients, employing only fundamental mathematical operations, thereby avoiding mathematical complexity.

The formula is:
$$x^{th}\text{ term's coefficient} =\frac{(x-1)^{th}\text{term's coefficient} \times (n-(x-2))}{(x-1)} $$
Where,

"$n$" is the exponent of  the binomial ∶  ${(a+b)}^n$
"$x$" is the position of the specific term in the expansion whose coefficient needs to be determined
"$(x-1)^{th}$ term's coefficient" is the coefficient of the previous term

Clarifications:

The exponent of the binomial ${(a+b)}^n$ belongs to natural numbers. Or, $n\in \Bbb N$
The first coefficient in the expansion can't be found using this recursive formula, since it doesn't have any preceding coefficient. However, it is well established that this coefficient invariably holds a value of $1$. So, we'll implement that.

Example of Evaluation:
Coefficients of ${(a+b)}^6$, evaluated using this approach:
$1^{st}$ coefficient $(x=1)$:  $1$
$2^{nd}$ coefficient $(x=2)$:  $ \frac{(x-1)^{th}\text{term's coefficient} \times (n-(x-2))}{(x-1)}=\frac{1\ \times (6-(2-2))}{2-1}=6$
$3^{rd}$ coefficient $(x=3)$:  $ \frac{(x-1)^{th}\text{term's coefficient} \times (n-(x-2))}{(x-1)}=\frac{6\times(6-(3-2))}{3-1}=15$
$4^{th}$ coefficient $(x=4)$: $ \frac{(x-1)^{th}\text{term's coefficient} \times (n-(x-2))}{(x-1)}=\frac{15\times (6-(4-2))}{4-1}=20$
$5^{th}$ coefficient $(x=5)$: $ \frac{(x-1)^{th}\text{term's coefficient} \times (n-(x-2))}{(x-1)} =\frac{20 \times (6-(5-2))}{5-1}=15$
$6^{th}$ coefficient $(x=6)$: $ \frac{(x-1)^{th}\text{term's coefficient} \times (n-(x-2))}{(x-1)} =\frac{15\times (6-(6-2))}{6-1}=6$
$7^{th}$ coefficient $(x=7)$:$ \frac{(x-1)^{th}\text{term's coefficient} \times (n-(x-2))}{(x-1)} =\frac{6\ \times (6-(7-2))}{7-1}=1$
This recursive formula facilitates the efficient calculation of binomial coefficients, as exemplified by the evaluation of these coefficients: $1, 6, 15, 20, 15, 6, 1.$
In conclusion,

This research proposes a Recursive Formula for the Binomial Coefficients.
While initial testing suggests the formula's accuracy, further analysis is necessary to ensure its correctness across a wider range of inputs.
I welcome mathematicians for collaborations to solidify its theoretical foundation and provide formal proof of its validity or identify any potential counterexamples. Furthermore, the applicability of this approach to exponents that are irrational or fractional could also be a topic to discover.

Please let me know if you can help me with the proof.

Author:

Shaikh Sadi

$9$th Grade Student

Dhaka, Bangladesh
Comment: You need and extra pair of round brackets when evaluating the formula $$\frac{15\ \times\ {6-(4-2)}}{4-1} = \frac{15 \times 6 -2}{3}=\frac {88}3 \neq 20  $$
But...
$$\frac{15\ \times\ (6-(4-2))}{4-1} = \frac{15 \times (6 -2)}{3}=\frac {60}3 = 20  $$

I can see from your markup code that you have used curly brackets in thise places,  but these don't show up unless you type `\{` in place of `{`
So you could have...
 $$\frac{15\ \times\ \{6-(4-2)\}}{4-1} $$
Comment: Thanks a lot to notify me this
Comment: The recursion is correct, but I don't think this is a "novel" approach. It is easy to see that $\binom{n}{x} = \binom{n}{x-1} \cdot \frac{n-x+1}{x}$ for $x\ge 1$. Your approach just calls $\binom n x$ the $(x+1)$th coefficient.
Answer: Let me start by introducing a more conventional way of expressing your formula.
Conventionally, we can discuss the binomial coefficients $\binom nr$ as the coefficient of $x^r$ in the expansion of
$$(1+x)^n= \binom n0 x^0 + \binom n1 x^1 +... + \binom nn x^n$$
Which can be written more compactly using summation notation (and avoiding "...", which many math people object to)
$$(1+x)^n= \sum_{r=0}^n\binom nr x^r$$
A couple of things to point out here:

The symbol $x$ is never used to refer to a variable that is restricted to integers, in the formula above $r$ takes on $(n+1)$ integer values from $0$ to $n$, and $x$ can be any real number.
It is easy to convert from $(1+x)^n$ to $(a+b)^n$, I leave it as an excercize for you to prove...

$$(a+b)^n = a^n\left (1+\frac ba \right )^n= \sum_{r=0}^n \binom nr a^{n-r}b^r$$

$\binom nr$ is the $(r+1)^{th}$ coefficient, but typically it is just referred to as the coefficient of $x^r$ in the expansion of $(1+x)^n$

Using these conventions, your recursive formula can be written as ...
$$ \binom n r = \binom n {r-1} \frac {n-(r-1)}r ,  (r \ge 1)$$
Now to establish the connection between binomial coefficients and combinations, consider...
$$ (1+x)^3 = \color{green}{(1+x)} \color{red}{(1+x)} \color{blue}{(1+x)}
\\= \color{green}{1}\cdot \color{red}{1} \cdot \color{blue}{1}
+\color{green}{1}\cdot \color{red}{1} \cdot \color{blue}{x}
+\color{green}{1}\cdot \color{red}{x} \cdot \color{blue}{1}
+\color{green}{x}\cdot \color{red}{1} \cdot \color{blue}{1}
+\color{green}{1}\cdot \color{red}{x} \cdot \color{blue}{x}
+\color{green}{x}\cdot \color{red}{1} \cdot \color{blue}{x}
+\color{green}{x}\cdot \color{red}{x} \cdot \color{blue}{1}
+\color{green}{x}\cdot \color{red}{x} \cdot \color{blue}{x}
$$
so we have $2^3=8$ terms, each obtained by choosing either a $1$ or an $x$ from each of the three brackets. The coefficient of $x^2$ in this expansion is the number of combinations of two out of the three brackets from which an $x$ is chosen, it being understood that you choose the $1$ from the remaining bracket. So $\binom 32 = 3$ because there are three combinations of two brackets that can contribute a factor of $x$, namely $\{1, 2\}, \{1, 3\}, \{2, 3\} $.

The binomial coefficient $\binom nr$ is equal to the number of combinations of $r$ distinct objects that can be selected from a pool of $n$ distinct objects, it is often referred to as " n choose r ", in Desmos you can get it using the function nCr(n, r), check out that nCr(6, 3)=20

Now we can develop your formula using the example $n=6, r=5$, so calculate $\binom 65$ given that $\binom 64 = 15$.
For every combination of $(r-1)=4$ objects taken from 6, we can create $n-(r-1)=2$ combinations of $r=5$ objects merely by appending one of the 2 objects not included in the combination of 4 objects.
For example, one of the 4-combos is $\{2, 3, 5, 6\}$, we can create 2 5-combos using the remaining objects 1 and 4, namely...
$$ \{2, 3, 5, 6\}\cup \{1\} \text{ and }  \{2, 3, 5, 6\}\cup \{4\} $$
In this way you can generate every possible 5-combo, but each one will occur $r=5$ times , for instance, the single 5-combo $\{1, 2, 3, 5, 6\}$ will be generated in $r=5$ ways...
$$ \{2, 3, 5, 6\}\cup \{1\} \text{ and }  \{1, 3, 5, 6\}\cup \{2\}  \text{ and }  \{1, 2, 5, 6\}\cup \{3\}
\\ \text{ and }  \{1, 2, 3, 6\}\cup \{5\} \text{ and }  \{1,2,  3, 5\}\cup \{6\} $$
So for each of the $\binom n{r-1}=\binom 64=15$ 4-combos we can generate $n-(r-1)= 2$ 5-combos and each 5-combo will appear $r=5$ times
So...
$$ \binom 65 = \binom 64 \times \frac 25 = 15 \times \frac 25 = 6
$$
and in general...
$$ \binom nr = \binom n{r-1}\times \frac {n-(r-1)}r
$$


java DataInputStream read() stop and do not proceed

Question:
I want sends and receive an object and file the order is

client -> server   by ObjectOut(In)putStream
client -> server String(file name) by DataIn(Out)putStrean writeUTF
client -> server  by BufferedIn(Out)putStream
server -> client  by ObjectOut(In)putStream

but when the code reaches on 3 writing file takes forever (I think...it is waiting) the critical code is
byte[] data = new byte[BUFFER_SIZE];
while ((length = bis.read(data)) != -1) {
    bos.write(data, 0, length);
    System.out.println(length);
}

bis(BufferedInputStream).read() do not proceed when I print the length the output is
4096
4096
879

then just wait...
is there anyone who knows what is the problem or solution?
Server thread
public void run() {

    System.out.println("\n New FileUploadServer thread started");
    msg = (Message) objComm.recvObject(clientSocket);
    System.out.println("server get message");
    if (checkState(msg.getState()))
        System.out.println(clientAddr + " session over");

    System.out.println("");
}

private boolean checkState(int _state) {
    switch (_state) {
        case ST_EXCEL_FILE:
            return receiveExcel();
        default:
            return false;
    }
}

private boolean receiveExcel() {

    Message sendMsg = receiveStr();
    System.out.println("receiveStr() success");
    BufferedInputStream bis;
    DataOutputStream dos;
    DataInputStream dis;
    FileOutputStream fos;
    BufferedOutputStream bos;

    VoteInfo sendVoteInfo = (VoteInfo) msg.getObj();

    try {
        dis = new DataInputStream(clientSocket.getInputStream());
        dos = new DataOutputStream(clientSocket.getOutputStream());
        // check file name extension is "xls" or "xlsx"
        String fName = dis.readUTF();

        int idx = fName.lastIndexOf(".");
        String extension = fName.substring(idx + 1, fName.length());
        if (!excelFileCheck(extension))
            return false;

        dos.writeUTF("read_ok");
        dos.flush();
        System.out.println("File name: " + fName);
        File f = new File(EXCEL_FILE_DIR + fName);

        fos = new FileOutputStream(f);
        bos = new BufferedOutputStream(fos);
        bis = new BufferedInputStream(clientSocket.getInputStream());

        int length;
        byte[] data = new byte[BUFFER_SIZE];
        while ((length = bis.read(data)) != -1) {
            bos.write(data, 0, length);
            System.out.println(length);
        }
        bos.flush();
        // send success message to web server
        System.out.println("kangji2");

        objComm.sendObject(sendMsg, clientSocket);

        System.out.println("File receive success!");

        if (!dataToDB.excelToDB(EXCEL_FILE_DIR + fName, extension)) {
            //delete all db related to this excel file here
            return false;
        } else {

        }
        bos.close();
        fos.close();
        dis.close();

        clientSocket.close();

        // send candidates information to DB server
        return makeResult(sendVoteInfo);

    } catch (IOException e) {
        System.out.println("ReceiveExcel error");
        e.printStackTrace();
    }
    return false;
}

public class ObjectComm {

    private Message receiveMsg = null;
    private ObjectOutputStream out = null;
    private ObjectInputStream in = null;

    public Message commObject(Message _sendMsg, Socket _clntSocket) {

        if (!_clntSocket.isConnected()) {
            System.out.println("clnt Socket not connected");
            return null;
        }

        try {
            out = new ObjectOutputStream(_clntSocket.getOutputStream());
            out.writeObject(_sendMsg);
            out.flush();

            System.out.println("kangji1");
            in = new ObjectInputStream(_clntSocket.getInputStream());
            receiveMsg = (Message) in.readObject();
            System.out.println("kangji2");
            return receiveMsg;
        } catch (Exception e) {
            System.out.println("commObject err");
            e.printStackTrace();
            return null;
        }

    }

    public boolean sendObject(Message _msg, Socket _clntSocket) {
        if (!_clntSocket.isConnected()) {
            System.out.println("clnt Socket not connected");
            return false;
        }

        try {
            out = new ObjectOutputStream(_clntSocket.getOutputStream());
            out.writeObject(_msg);
            out.flush();

            return true;
        } catch (IOException e) {
            System.out.println("Object comm send err");
            e.printStackTrace();
            return false;
        }
    }

    public Message recvObject(Socket _clntSocket) {
        if (!_clntSocket.isConnected()) {
            System.out.println("clnt Socket not connected");
            return null;
        }

        try {
            in = new ObjectInputStream(_clntSocket.getInputStream());
            receiveMsg = (Message) in.readObject();
            return receiveMsg;

        } catch (Exception e) {
            System.out.println("Object comm recvObject err");
            e.printStackTrace();
            return null;
        }
    }

}

Answer: Did you close the connection in client side (sender side, or wherever opposite of your input stream) ? read(byte[], int, int ) in BufferedInputStream will return when end of the stream has been reached.
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html#read(byte[],%20int,%20int)
Comment: I thought if I close buffers then socket is closed also
isn't it?
Comment: Well, I don't see close() call for BufferedInputStream in your code.. and actually you shouldn't do that. Your code need to read input stream until read() return -1 and then you can close input stream at the end of your code, not during you read bytes from input stream.

Try to add socket close logic in opposite part where your code read bytes through input stream, and retry if my suggestion works.
Comment: As you said if I add close() the waiting is over but the problem is after close(), socket also closed. so I can't receive or get messsage from server after close()
Comment: Seems like your client side that you connect with clientSocket is finished sending data and there is nothing left. So every time your code try to read bytes through read(byte[], int, int), methods will return 0(zero) since there is nothing to read and reading is actually blocked. That's why you don't see any data after 4096 4096  879.

As you commented, if you want to keep using that connected clientSocket, then yes you shouldn't close the socket. Simply changing while conditions like while((length = bis.read(data)) > 0) ... you might able to avoid current problem,
Comment: Although there are possibility that your network or client side remote process is actually blocked for some reason and not sending anything temporary.. that case your reading process will be finished  even if there are still more bytes to read.
Comment: thanks for your comments but..while((length = bis.read(data)) > 0) doesn't work. same result.
Comment: if I delete the code after file communcation,
it works correctly. so..I think, it's not network problem..
Comment: Your read() call will be "blocked" and not getting any return value unless your close socket / inpustream OR client close the connection. ( that way your code get -1 ).
So yes, even > 0 check won't fix your problem since your code is still waiting to get some bytes from client side. You may need to redesign your protocol so once you get any kind of END-OF-SENDING notification, your stop reading it and start writing in another thread? ( use thread and/or nonblocking io for that )
Answer:

client -> server by ObjectOut(In)putStream
client -> server String(file name) by DataIn(Out)putStrean writeUTF
client -> server by BufferedIn(Out)putStream
server -> client by ObjectOut(In)putStream

Too much stuff here.
Playing with streams at different levels of your stream stack simply does not work.
If you want to send objects, use the ObjectInput/OutputStreams for everything. Construct them as follows:
new ObjectOutputStream(new BufferedOutputStream(...))

and
new ObjectInputStream(new BufferedInputStream(...))

Send the objects with writeObject(); send the strings with writeObject() or writeUTF(); send byte arrays via ObjectOutputStream.write(); and use the complementary methods of ObjectInputStream at the other end.
Comment: You tried what exactly? What code? Edit it into your question.


Rota não funciona no Vue.js - Vai para a ' / ' ao invés de ' /login '

Question: Boa noite, pessoal!
Estou começando a aprender e estou criando o meu primeiro projeto com Vue.js.
Acontece que criei uma rota '/login' mas o componente que carrega é o 'Content' que tá na raiz da aplicação. Estou olhando o código e não consigo encontrar o problema. Alguém poderia me ajudar?
Se eu coloco localhost:3001 ou localhost:3001/login aparece exatamente a mesma coisa no navegador.
Componente Login:
<template>

Página de Login!!!

Página de Login!!!

Página de Login!!!

</template>

Arquivo de rotas:
import Vue from 'vue'
import VueRouter from 'vue-router'

import Content from '@/components/template/Content'
import Login from '@/components/account/Login'

Vue.use(VueRouter)

const routes = [{
    name: 'content',
    path: '/',
    component: Content
}, {
    name: 'login',
    path: '/login',
    component: Login
}]

export default new VueRouter({
    mode: 'history',
    routes: routes
})

Arquivo App.vue:
<template>

    <Content />

</template>

Answer: Você precisa criar um router-view no na sua página principal, no caso o componente App, que irá direcionar para Content quando for / e para Login quando for /login.
Exemplo:

Hello App!

    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>

  <router-view></router-view>

Exemplo tirado de https://router.vuejs.org/guide/#html


Como colocar autocomplete no Sublime Text 3?

Question: Eu uso o Sublime Text 3 para programar só que o autocomplete não me está a funcionar. Já instalei o plugin Sublime Intelcode mas mesmo assim não funciona. Não aparece as sugestões quando vou a escrever o código. Como resolver?
Comment: Não encontrei isso
Comment: aparece os plugins que tenho instalados, mas antes de mais qual o melhor plugin para autocomplete ?
Comment: [Aqui](https://packagecontrol.io/browse/labels/auto-complete) há alguns, isso vai depender da sua necessidade, a versão que usas, a linguagem. Com *Ctrl* + *Space* não funciona?
Comment: funciona mas eu queria que aparece a lista conforme ia escrevendo
Comment: eu estou neste ficheiro aparece isto {
 "color_scheme": "Packages/User/SublimeLinter/Monokai (SL).tmTheme",
 "ignored_packages":
 [
  "Vintage"
 ]
}
Comment: coloquei isso mas mesmo assim não funciona eu agora removi todos os plugins e vou instalar só o de autocomplete qual e o na tua opinião o melhor para todas as linguas ou seja principalmente css php e jquery
Comment: Olhe para [PHP Completions](https://packagecontrol.io/packages/PHP%20Completions%20Kit).
Comment: eu acho isto estranho eu instalo o autocomplete para css se eu criar um css no arquivo php o autocomplete funciona bem num ficheiro .css nao funciona
Comment: Pode ser uma característica, talvez para *css* você tenha que ter outro *plugin*.
Comment: Bem já esta a funcionar como queria mesmo obrigado pela ajuda
Comment: Se for possível poste uma resposta de como você conseguiu e aceite ela.
Comment: Sim eu vou reformular uma resposta detalhada com as alterações que fiz com certeza irá ajudar outras pessoas
Answer: Bem vou publicar aqui como resposta a solução de como resolvi o meu problema, pelo que vi na internet existe muita gente a procurar por esse problema.
Primeiro verifiquei no menu Preferences/Settings-User se o "auto_complete": true, estava activado caso não esteja tem que colocar conforme "auto_complete": true,
Depois e instalar os plugins necessarios para fazer o efeito de autocomplete conforme as vossa necessidade vou deixar aqui os plugins que utilizei e que funcionam na perfeição.
CSS Extended Completions
https://packagecontrol.io/packages/CSS%20Extended%20Completions
Emmet
https://packagecontrol.io/packages/Emmet
SublimeLinter
https://packagecontrol.io/packages/SublimeLinter
O que vou colocar a seguir e Opcional e uma sugestão minha mas para quem passa muitas horas a programar penso que seja um bom tema para cansar menos a vista.
Spacegray theme
http://kkga.github.io/spacegray/


How to record to my laptop the sound of an acoustic guitar with a magnetic pickup?

Question: I have a magnetic pickup... How can I use it to record the sound of a guitar to a laptop?
I was told magnetic pickups should not be directly connected to a laptop (and that might be true, because I hear a lot of noise). What should the magnetic pickup be connected to, before I can input the sound to my computer?
Should I have used a simple microphone?
Comment: Is it important to you that the recording sound like a *guitar*, or is the sound produced by the pickup sufficient for your purposes?
Comment: "I was told magnetic pickups should not be directly connected to a laptop (and that might be true, because I hear a lot of noise)." Noise isn't a result of connecting to the laptop. Odds are good if you're hearing noise it's because the pickup is a single-coil, and, in the same room would be noisy going into a guitar amp. I've plugged my guitars into a 1/4" to mini-phone-plug adapter and into my laptop, and it sounds fine and doesn't hurt the computer or guitar.
Comment: What make and model pickup?
Comment: @ J Assyptoth: if you are responding to the other post about them not being suitable, what he said is not strictly correct. It is correct in the sense that it is a low quality solution, but it will work. The biggest issue with these setups is ground loops and unshielded cables. There are ways to deal with both of these situations.
Comment: [Recording is off-topic (for now)](http://meta.music.stackexchange.com/questions/6/adding-recording-to-the-topics). There is [an Audio Recording site](http://audio.stackexchange.com/) where you can ask this, however.
Comment: Re-opened since we changed our scope :)
Answer: Generally you do not use a magnetic pickup with an acoustic guitar but a pickup designed for acoustic's(such as a piezoelectric).
You can use a microphone or a clip on mic/pickup that clips onto the guitar(headstock or sits in the hole). I wouldn't use a magnetic pickup because it won't pickup a lot of the acoustical sound that makes an acoustic guitar sound the way it does(even piezo's are not the best for this).
Generally the way acoustic guitars are recorded in the studio is to use microphones. There are various ways to position the mic but this is generally the way to go if you want to "record".
As far as the laptop thing is concerned. The main issue you will have is impedance matching. What this means is, basically, your signal may be too quite and require too much amplification to recover it's sound which also amplifies the noise. This shouldn't really be a problem though and piezo's and mic's are not as susceptible to electromagnetic noise as magnetic pickups.
If I were you I'd look into getting a mic or a piezo rather than use a magnetic pickup.
Comment: Condenser mic is a good way to go.
Comment: When I was a teen back in the stone age with no money, I would place a pair of decent headphones on the guitar body (like a clip)
Comment: IME, well-designed (low-impedance!) magnetic pickups for western guitar tend to sound much better than a piëzo on the same guitar.
Answer: Is your magnetic pickup part of your guitar? Like it is on my Ibanez? If so, that's a fine way to get sound from your guitar to your computer. You're going to get a different sound than you would from a mic, and a different sound than you would from a regular electric guitar. Every setup has its own sound. Don't worry about that now.
What you need to worry about is getting instrument-level sound into your computer. What you want is an audio recording interface. There are several options.

There are interfaces built into cables.
There are interfaces built into pedals.
There are standalone interfaces.

I personally have and love one of the Line 6 interfaces. The amp / effect models are very good and it's worked with everything I've ever tried to use. I have the one with a single instrument and a single microphone input. The monitoring has zero latency and sounds great.
Comment: @John Assymptoth - Obviously I can't tell you anything about products I've never used. But $20 sounds like a really low bar. Here (http://www.bhphotovideo.com/c/product/800751967-USE/Alesis_GUITARLINK_GuitarLink_1_4_to.html) is the best price I can find on a product from a company and supplier that I've heard of. You'll still need some sort of software to deal with your sound once it's in your computer - that's a separate question. Hope this helps!
Comment: No, I bought the pickup separately. Do you know if I can get a reasonable interface (I'm assuming USB will be better than mic-in) for 20$?
Comment: Or is something like [this interface](http://cgi.ebay.co.uk/GUITAR-2-PC-USB-RECORDING-INTERFACE-VOCAL-AUDIO-TRAINER-/180626153728?pt=UK_Guitar_Accessories&hash=item2a0e286100) too bad
Answer: No matter whether you go for magnetic, acoustic or piezo pickups, the signals are at extremely low voltage, so you want to use some form of pre-amp. This will bring the levels up well above the noise floor. It will also sort out impedance issues (impedance matching is an entirely separate area but also of importance in ensuring output quality).
Some preamps also allow you to simulate an amplifier sound (see the Line-6 range) but this may or may not be what you want.
I tend to use either a DI box, or a Line-6 amp simulator, depending on the sound I want.


Get list of channels subscribed by user using userid, without authorization

Question: Previously we are using GData V2 api to get list of channels subscribed by user using userid as follows,
https://gdata.youtube.com/feeds/api/users/userid/subscriptions?v=2&alt=json&max-results=50
But in V3 api, to get list of channels subscribed by user, authorization is compulsory, anyone know any other approach for this. Thanks.
Answer: In V3 Api you can get list of subscriptions by using channel id of that user.
<code>GET https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&channelId=*channelid*&maxResults=20&key={YOUR_API_KEY}
</code>
Comment: For this to work you need to have to have the channel having the list of subscriptions set to public.
Answer: In V3 API, if you have the access token, and the channel id. Make a GET request like

https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&channelId=**channel_id**&access_token=**access_token**&maxResults=**max_results_between_0_to_50_default_5**

I'm not an expert or anything, but I'm getting the result correctly now for what I'm working on.

Edit:

@prasad's answer is correct though, but the request will not work with api_key.  Just replaced his api_key with access_token.
Comment: Hey, Thanks, it's helped me a lot.


Topological Group Structure on Endomorphism Group of a Quiver Representation and Relations with Dimensions of Varieties

Question: I have been reading chapter 8 of Ralf Schiffler's 'Quiver Representations'. There he has defined, for a finite quiver $Q=(Q_0,Q_1)$ without oriented cycles and for a (fixed) dimension vector $\textbf{d}:= (d_i)_{i \in Q_0} \in \mathbb{Z}_{\geq 0}^n$, the space $E_\textbf{d}$ of representations $M$ of $Q$ having dimension vector equal to $\textbf{d}$, and the group $G_\textbf{d} := \prod_{i \in Q_0} GL_{d_i} (k)$, which acts on $E_\textbf{d}$ by conjugation: that is, for $g:=(g_i)_{i \in Q_0} \in G_\textbf{d}$ and $M := (M_i, \phi_\alpha)_{i \in Q_0, \alpha \in Q_1} \in E_\textbf{d}$,
$$g \cdot M := (M_i, \hspace{1mm} g_{t(\alpha)} \hspace{0.5mm} \phi_\alpha \hspace{0.5mm} g_{s(\alpha)}^{-1})_{i \in Q_0, \alpha \in Q_1} \in E_\textbf{d}$$
where the source and target of arrow $\alpha \in Q_1$ are given by $s(\alpha)$ and $t(\alpha)$ respectively.
For a representation $M \in E_\textbf{d}$, we denote the orbit of $M$ under the above action by $\mathcal{O}_M$. Then $G_\textbf{d}$, $Aut(M)$ and $\mathcal{O}_M$ have the structure of an algebraic variety, and as such their dimension (as algebraic varieties) is defined.
Now in Proposition 8.10, in order to prove that the codimension of $\mathcal{O}_M$ is equal to the dimension of $Ext^1(M,M)$, he says that the "group of automorphisms of $M$ is an open subgroup of the group of endomorphisms thus $dim \hspace{0.51mm} Aut(M) = dim \hspace{0.51mm} End(M)$". The proof also uses Proposition 8.4 which is a relation between the vector space dimensions of $End(M)$ and $Ext^1(M,M)$.
Unfortunately all I know about algebraic varieties and topological groups is the definitions of the dimension of an algebraic variety $V$ (as one less than the length of the longest chain of distinct non-empty irreducible subvarieties of $V$) and of irreducible varieties, hence it is not obvious to me why the following are true:
$1.$ How can we topologize $End(M)$ to make it a topological group such that $Aut(M)$ turns out to be an open subset of $End(M)$?
$2.$ Does a general vector space become an algebraic variety? (If so, how?) If not, why do $End(M)$ and $Ext^1(M,M)$ in particular have structures of algebraic varieties? (For $End(M)$, I can still see that we could make it an algebraic variety by noting that the diagram commutativity conditions for morphisms between quiver representations gives some polynomial relations between the $\phi_{\alpha}$'s, and I wanted to confirm if this is right. And what about $Ext^1(M,M)$?) And why is the dimension of these vector spaces equal to their dimension as algebraic varieties (because that is what is being subtly used when Proposition 8.4 is employed to establish 8.10)?
$3.$ What does $Aut(M)$ being open in $End(M)$ have to do with the equality of the (algebraic variety) dimensions of $Aut(M)$ and $End(M)$ or with the vector space dimension of $End(M)$?
I would really appreciate some help in this regard.
Answer:
The general idea here is that automorphisms are just endomorphisms of nonzero determinant, so any topology so that the determinant polynomial is continuous and $\{0\}\subset k$ is closed will do. In practice, the Zariski topology on $k^n$ suffices: this is the topology where the closed sets are $\{x\in k^n\mid p(x)=0\}$ for $p$ a polynomial $k[x_1,\cdots,x_n]$, and if you're working over a field that comes with a natural topology (like $\Bbb R$, $\Bbb C$, or $\Bbb Q_p$) those will all work as well, because they're finer (that is, more open sets) than the Zariski topology.
This depends on your definition of an algebraic variety. If you take the "classical" definition from the linked post, it's obvious: set the topology to be the Zariski topology, then boom, variety. For other notions there, you'll have to do a little more, but it's not usually too bad.
Open subsets of irreducible varieties in the Zariski topology have the same dimension as the whole space - see here for example. As the dimension of a vector space as a vector space and a vector space as a variety are equal (see here), we have the requested result.


Java class Thread Safe methods, for exam certification 1Z0-851

Question: I am studing for 1Z0-851 Oracla Java SE 1.6 Certification and I saw this question:

Can anybody explain me this answer?
And say whether I am correct when I think this way:
if doThings() is static only one access can be made by time despite of when a method is not static once each TestSeven object would access doThings at the same time modifying the x value inconsistently.
Am I correct on thinking this way?
Thanks.
Answer: Yes that's it. At the moment, if you create two instances of TestSeven and call their doThings method from 2 different threads, you have no guarantee that x will be incremented twice. For example, the following execution is legal (T1 and T2 are the two threads):
T1: current = x //0
T2: current = x //0
T1: current++; // 1
T2: current++; // 1
T1: x = current; // 1
T2: x = current; // 1

So you have called the method twice but x has been incremented only once.
If you make the method static, only one thread will be able to execute it at a given moment, even if you create many instances.
Comment: @thiagoh yes it would achieve the same: you could use any static object as a lock (TestSeven.class is one possibility).
Comment: good! thats what I thought.. I could do a `synchronized(TestSeven.class) {}` instead of making this method static also??
Comment: Correct, you could use a synchronized block where the lock is the class (or another arbitrary static field).
Answer: It's not thread-safe because x scope is "static", ie all classes instance can access it, and the doThings methods isn't. So it's synchronized only on the class instance.
Therefore, there can be two classes instance accessing x in the same time despite the synchronized keyword.
Making the method static would ensure it to be called only once at a time.
Answer: The doThings() method is an instance method and is reading and writing to a static variable x. By making doThings() static, it will be synchronized across all instances (intrinsic lock on the class, rather than on the instance). In other words, as it currently stands, the method can be invoked simultaneously by multiple threads, whereas making it static would prevent that.
Answer: If x is not marked static then will the class be thread-safe?


Free-throw lines length

Question: Art. 2.4.3 of the FIBA official rules (approved 4th July 2017) says that

The free-throw line shall be drawn parallel to each endline. It shall
  have its furthest edge 5.80 m from the inner edge of the endline and
  shall be 3.60 m long

But in Diagram 2 of the same rules, the free-throw line is 4.9 m long (and not 3.6)
Am I missing something?
Answer: That 4.9 m line in Diagram 2 is the extended free-throw line, used for defining the restricted area. The centre 3.6 m of that line, where it joins the free-throw semi-circle, is the free-throw line itself. When taking a free throw, a player must

Take a position behind the free-throw line and inside the semi-circle.

(Art 43.2.3). If they took a position behind either of the 0.65 m extensions of the free-throw line, they would be in an incorrect position.

Free-throw lines length


Give permissions to user of the same role

Question: I'm working in a site and I've to set node permissions (edit) so that a user can edit a node that is owned by a user of the same role.
If I have the role "redactor" I can edit any node that is owned by a user that as the role "redactor".
Is there a module that do this?
Or I've to write a custom module?
Answer: You can used module content access, he does that easily.

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type

Or you have node access which add a tab on each node to control permission for this node (you can configure role or user) I never really used it because there's no very stable version for d7.
Comment: Actually, i did that with `references` module by auto-assign  a user that was linked to the content with : `$form['field_reference']["und"][0]['uid'] = array( "#type" => 'value',"#value" => $user, );` SO i think i possible to do that for users of the same role.
Comment: I know content access but are you sure that is it useful for me? I don't have to set permissions generally to content types & roles. I need that if I have a role (redacator, for example), I could edit nodes that are owned by other users with the "redactor" role.
Comment: Sorry, i misunderstood the subtility of your question. In fact, it was possible to do that programmatically with `node access` but it seems that in drupal 7 it doesn't work anymore (i tried to reinstall it and i have a fatal error when i save the form) You could with this module give an alias for all your role, after i think it was easy to set it for the node.  But you're right you can do that with `nodeaccess_userreference`.
Comment: Ok, I'll write a simple custom module that use hook_node_presave. In this hook I call a view that tells me all users with the same role of the author and I add a user_reference to the node for every users
Answer: A simple solution could be the use of http://drupal.org/project/nodeaccess_userreference or http://drupal.org/project/nodeaccess_userreference
With this modules I can set programmatically, when I save the node, a user-references field to all users of a role.


delegating into private parts

Question: Sometimes, C++'s notion of privacy just baffles me :-)
class Foo
{
    struct Bar;
    Bar* p;

public:

    Bar* operator->() const
    {
        return p;
    }
};

struct Foo::Bar
{
    void baz()
    {
        std::cout << "inside baz\n";
    }
};

int main()
{
    Foo::Bar b;   // error: 'struct Foo::Bar' is private within this context

    Foo f;
    f->baz();     // fine
}

Since Foo::Bar is private, I cannot declare b in main. Yet I can call methods from Foo::Bar just fine. Why the hell is this allowed? Was that an accident or by design?

Oh wait, it gets better:
Foo f;
auto x = f.operator->();   // :-)
x->baz();

Even though I am not allowed to name the type Foo::Bar, it works just fine with auto...

Noah wrote:

type names defined within a class definition cannot be used outside their class without qualification.

Just for fun, here is how you can get at the type from outside:
#include <type_traits>

const Foo some_foo();

typedef typename std::remove_pointer<decltype( some_foo().operator->() )>::type Foo_Bar;

Comment: To abbreviate your code example, you're basically asking whether it is legal by design to return a private type (`Foo::Bar*`) from a public member function (`Foo::operator ->()`)?
Comment: You still haven't gotten access to the typename Bar that is defined within Foo.  You've invented a new typename that refers to the same type.  You're assuming the type's name and the type are the same thing and in C++ they're apparently not...though I've not yet found anything in the standard that explicitly says that.
Comment: @stakx Hmmm, I guess so :) +1
Comment: Concerning your `auto` code example, I thought that was an abbreviation for `auto int`. Does this actually compile and run correctly?
Answer: Trying to find anything in the standard that would spell it out in detail but I can't.  The only thing I can find is 9.9:
Type names obey exactly the same scope rules as other names.  In particular, type names defined within a class definition cannot be used outside their class without qualification.
Essentially, the name of Foo::Bar is private to Foo, not the definition.  Thus you can use Bars outside of Foo, you just can't refer to them by type since that name is private.
The name lookup rules for members would also seem to have some effect on this.  I don't see anything that specifically references "nested class" and thus they wouldn't be allowed to (if my lack of finding anything in fact is because it's not there).
Answer: I can't provide a full answer, but maybe a starting point. The C++ 1998 specification includes the following code example under paragraph 11.3 [class.access] (p. 175):
class A
{
    class B { };
public:
    typedef B BB;
};

void f()
{
    A::BB x;   // OK, typedef name A::BB is public
    A::B y;    // access error, A::B is private
}

In this example, a private type is "published" through a public typedef. Although it's not the same thing as publishing a type through a member function signature, it's similar.
Comment: The same text is in clause 11, paragraph 4 of the C++0x FCD; I think paragraph 5 explains why you can do it: "It should be noted that it is access to members and base classes that is controlled, not their visibility.Names
of members are still visible, and implicit conversions to base classes are still considered, when those members
and base classes are inaccessible. The interpretation of a given construct is established without regard to access control. If the interpretation established makes use of inaccessible member names or base classes, the
construct is ill-formed."
Comment: *@Niall C.:* I'm not sure that the distinction between accessibility and visibility provides the answer. Visibility doesn't seem an issue, here. And the above code example still makes a private type accessible (in a limited fashion, though).
Comment: Even though `Foo::Bar` is inaccessible outside of `Foo`, its members are visible and accessible through the `Bar *` being returned by the `operator->()` overload..
Answer: I think this is by design. You cannot explicitly create instance of Foo::Bar but it could be returned from member functions and then you could pass it to other member functions. This lets you to hide implementation details of your class.

delegating into private parts