MySQL search for a number in VARCHAR field

Question: I have a field in my database that contain comma separated values these values are numbers, and I am trying to do a search and count the number of times that a number appears in that column throughout the column,
$sql = "SELECT sector_id_csv, COUNT(sector_id_csv) as count FROM cv WHERE sector_id_csv LIKE '$sectorId'";

This seems slow and does not return any results, and I know the sector_id it is search exists in the table.
Comment: What value does `$sectorID` have?
Answer: Basically, this should work fine if you use % wildcards:
WHERE sector_id_csv LIKE '%$sectorId%'";

what tends to cause problems in this scenario, though, is the fact that a search for 50 will also find 501 502 503 and so on.
If you can rely on your comma separated list to have a trailing comma behind every entry, it would be more reliable to search for
50,
to catch that value only.
Comment: @FractalizeR yup. I think this approach will be slow no matter what, normalizing the table would definitely speed things up. But maybe it's fast enough - for smaller projects, data is easier to handle this way.
Comment: This will cause FULL TABLE SCAN to be performed. On large tables this will be really slow.
Comment: Thanks for the answer gave enough of basis to get it working, the table will never be massive.
Answer: WHERE CONCAT(',', sector_id_csv, ',') LIKE '%,$sectorId,%'

or
WHERE FIND_IN_SET('$sectorId', sector_id_csv);

This will ensure that your query returns only rows with sector id in given field. Provided that sector id-s in this field are comma separated.
Any query using LIKE or FIND_IN_SET will be slow as it cannot take advantage of indexes. Please consider putting all sector id-s in separate table.
Also for security reasons please remember to ensure that $sectorId is a number by casting it to int like that:
$sectorId = (int)$sectorId;

before using it in a query.
Answer: Don't you need to pad the value with the % wildcard for LIKE to work?
$sql = "SELECT sector_id_csv, COUNT(sector_id_csv) as count FROM cv WHERE sector_id_csv LIKE '%".$sectorId."%'";

At least that's my understanding from reading this article, your use of wildcards will depend on your desired condition.
Answer: ...but if your scema was normalized you wouldn't need to jump through these hoops - and it would run a lot faster.
C.
Answer: Actually the number could be at he beginning or the end too. So you need to do
WHERE sector_id_csv='$sectorId' OR sector_id_csv LIKE '%,$sectorId' OR sector_id_csv LIKE '$sectorId,%' OR sector_id_csv LIKE '%,$sectorId,%'

Answer: SELECT count(*) from TABLENAME where FIND_IN_SET('VALUE',FILDNAME)>0;

Others u can use  instr, regexp....
It's advisable to have FILDNAME indexed.


Population Variance and Sample Variance

Question: How is it that lowering the number of frequence,$n$ by $1$ in the for formula for Population and Sample Variance account for the discrepency of using sample rather than population.
I mean how is dividing the whole expression by $n-1$ in sample variance better than dividing by $n$?
I am referring to the formula $$s^2=\frac{\sum_{i=1}^{n}({x_i-x_{avg}})^2}{n-1}$$ more accurate than $$s^2=\frac{\sum_{i=1}^{n}({x_i-x_{avg}})^2}{n}$$
Thank You.
Comment: Closely related: http://stats.stackexchange.com/questions/54/why-do-us-and-uk-schools-teach-different-methods-of-calculating-the-standard-dev.
Answer: If you use
$$
s^2 = \frac{\sum_i^n (x_i - \bar{x})^2}{n}
$$
as an estimate, based on a sample of size $n$, of the population variance then your estimate results to be biased. The formula for the bias however shows that
$$
\tilde{s}^2 := \frac{n}{n-1} s^2
$$
is unbiased.
I just came across this pdf where the formula for the bias is derived.
With a sample of size $n$, the usual practice is then to use
$$
\tilde{s}^2 = \frac{\sum_i^n (x_i - \bar{x})^2}{n-1}
$$
as an estimate of the population variance.
If, on the other hand, the $x_i$'s form the whole population, then there is no discussion about bias or anything, and we just apply the definition of the variance.
Comment: Well, of course,if the entire population is sampled, then there is no bias.
Comment: @Russell I think what ocram is alluding to is that when the entire population is sampled, then $\tilde{s}^2$ *is* biased.  This shows that a key issue has not yet been discussed: this variance estimate is unbiased only for certain forms of sampling.
Comment: @whuber: Ah, yes, of course.
Answer: As a supplement to the math stat derivation of Bessel's correction, how about a simulation to help show what is going on?
<code>#Draw 6 values from a N(0,1) distribution and calculate
#the variance using the true population mean and the
#mean calculated from the sample - repeat 1E6 times
n <- 6
m <- 1E+6
mu <- 0
sigma <- 1
v.pop <- numeric(m)
v.sam <- numeric(m)
for (i in 1:m) {
  x <- rnorm(n,mu,sigma)
  x.bar <- mean(x)
  v.sam[i] <- sum((x-x.bar)^2) / n
  v.pop[i] <- sum((x-mu)^2) / n
}

#if you use the true population mean to calculate the estimate of
#the population variance, on the average you will get a good estimate
mean(v.pop)

#if you use the sample mean in place of the population mean, on
#the average your estimate of the population variance will be too
#small because the individuals in a sample tend to be more closely
#clustered around their own mean than they are around the population mean
mean(v.sam)

#the ratio of the estimate of population variance made with the
#population mean to the estimate of population variance made with
#the sample mean is
mean(v.pop) / mean(v.sam)

#which happens to look a lot like
n / (n-1)

#which we use to adjust upward the estimate of the population
#variance made with the sample mean
n / (n-1) * mean(v.sam)
</code>

Population Variance and Sample Variance


Is it possible to not generate package-lock.json with npm 5?

Question: I've updated npm to it's latest version recently to get the performance upgrade. But since my company hasn't updated globally, I don't want the usage of package-lock.json.
I could simply ignore it in git workflow by adding package-lock.json to my .git/info/exclude. But it would still be used by npm when installing or updating dependencies.
So how can I tell npm not to use it?
Answer: To disable package-lock.json in a project you can add
.npmrc file and content of this file will be
package-lock=false

if you try to install with npm the file will not generate.
Comment: When you do this, if you explicitly generate a package-lock.json ie - `npm i --package-lock-only` will subsequent npm installs respect that package-lock.json or skip it entirely?
Answer: Deactivate package-lock.json usage globally
To disable it globally, you'll have to set your package-lock to false in your ~/.npmrc. You can do it by using:
npm config set package-lock false

This will allow you to use npm@5 performance without bothering with package-lock.json. Though package-lock.json has many benefits according to npm doc, and you may consider using it.
Deactivate package-lock.json usage per command
According to npm-cli doc, you can use --no-package-lock options for the install command:
npm install --no-package-lock any-lib

And according to this question, existing package-lock.json will not be taken care of.


Logistic Regression with empty cells

Question: I have a data set from which I need to train a model and use it for prediction.
Let's say I want to predict what people say about food items produced by a cake shop.  Let's assume people have stated the taste of the food items as good, average and bad in different years, by different methods. So the columns will be:

Food item
No. of people saying Good
Year it was said Good
Method of stating Good (By tasting or by rumours)
No. of people saying Bad
Year it was said Bad
Method of stating Bad (By tasting or by rumours)
No. of people saying OK
Year it was said OK
Method of stating OK (By tasting or by rumours)

In this case, there will be food items which people have stated as Good but no mention whether it is Bad or Ok. In such cases, the respective columns will have to be kept empty. For "the no. of people ...." columns, zero can be added but not for "year ..." column and "method...." column.
If I use Logistic Regression to train this data set, will it be valid since there will be no.of empty cells in the training data set? Or else, if Logistic Regression is not good in this scenario, what supervised machine learning method can be used?
Comment: You should definitely be considering ordinal/ordered logistic regression with the response levels Good > Average > Bad. You will also probably want to recenter your year column for ease of interpretation. Zero cells aren't the end of the world for logistic regression. Edit: just to be clear, you need to change columns to: Reponse (good/average/bad), Number giving response, other factors (year, method, ...).
Comment: If the column Response is used, how will I enter data in a scenario where one food item was stated as Good in 2014, but it was also stated as Bad in year 2013?
Comment: Use separate rows. Do the same even if it's the same year.
Comment: I'm not taking the 'Food item' column to train the model. If so, is it possible to add several columns for the same food item? The example I have given regarding food items is not my scenario. But my scenario is very similar to what I have given in the example. (Same kind of columns). If I'm not taking the 'food item' column to train the model, is it still possible to go for separate  columns? I f not, what is the best thing to do?
Comment: I'm having some difficulty understanding your problem... What is your dependent variable in this case, I.e. What are you trying to predict?
Comment: Dependent variable will be "Sales" which will have values either "Profitable sales" or "No profitable sales". Independent variables will be all the columns I have listed in the post except "Food item" column.
Answer: If I understand correctly what you are aiming for, you might want to rearrange your data a little. You have for each year set of explaining variables in your example:

Number of people who said it was good based on rumours
Number of people who said it was ok based on rumours
Number of people who said it was bad based on rumours

And the same for those where it was based on tasting. Which makes six columns for each year and if there were none saying something the value is zero. So you would have six times the years as input in this case and what you are predicting is 1,0 for profit/no-profit.
What it means is that "year" as such is not a predictor, but "number of people who did A in year X" is.
Comment: This looks right to me. Obviously make sure the regression makes sense, so don't include ratings which come after the sales period. Also, make sure it makes sense to group by year - is this how reviews are presented? And one would expect more recent reviews to have a stronger effect on sales.

Logistic Regression with empty cells


"The website encountered an unexpected error" right after login in

Question: So I recently bought a very cheap host just to run a not-important website on it. but when I login to admin, it shows

The website encountered an unexpected error, Please try again later.

message, since its a shared host I checked into my cpanel for error logs, there were just two errors regarding my .htaccess files (in root and also sites/default/files) regarding FollowSymLinks not being available here, so I commented out those lines and all error logs now are gone. but still I get the error message after I try to login.
I contacted the webmaster regarding FollowSymLinks and he said we are using SymLinksIfOwnerMatch .
however with or withought FollowSymLinks I still get the error message while my error logs in cpanel is empty.
Any Ideas or hints?
Comment: can you check the last error logged in your watchdog db table
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10854/discussion-between-arpitr-and-sohail)
Comment: Thanks for the affort guys, the issue was db damage, I reupload the dump and it works fine again, arpitr please leave an answer so i can select it as the right one
Comment: well I get this error for like 2 days
Comment: is your .htaccess file readable by webserver?
Comment: yea I assume it is because of permission and also because of errors I was getting from my .htaccess before
Comment: www.yourdomain.com/user works?
Comment: yes it looks ok
Comment: yea give me a minute
Comment: believe it or not there is no watchdog table in my db structure
Comment: did you have imported database properly?
Comment: I guess, there was no error, I imported as a tar.gz
Comment: I am glad it helped you, I have added an answer keeping it generic :)
Answer: If you are not able to login then you can try checking the logged error directly looking into your database watchdog table.
In your case:As per our chat you were missing watchdog table so importing the database back helped you.


How to test the influence of external factors on time series

Question: I need an advice/ best method on how to rigorously test the influence of categorical predictors (states),
or their duration (duration of war/peace in this case) on time series.
How to prove that the increase in prices of oil is caused by war?
I would like to get some p-value.
<code># Example - influence of war on prices of oil
# (completely speculative of course ;D)
price <- c(13,13.5,13,13.5,13,15,15.5,15.5,15,12.5,12,12,12,12.5,14,15,
           14,13.5,12.5,13,13,14,15,13.5,12,12,12,12.5,12,12)
year <- seq(from = 1960, length = 30)
era <- rep(c("peace","war","peace","war","peace","war","peace"),
             times = c(5,4,5,2,3,4,7))
my.data <- data.frame(price = price, year = year, era = era)

# plot
plot(my.data$year, my.data$price, xlab = "year", ylab = "price of oil",
     pch = 20, ylim = c(11,17), cex = 2.2)
lines(my.data$year, my.data$price, col = "blue", lty = 2, lwd = 2)
</code>
Can anybody help me? Thank you for any guidance in advance!
At least the name of appropriate technique will be helpful.
Comment: Isn't it actually the case that sudden jumps in prices of essential commodities *cause* wars? :-)  In fact, I believe you will find that the price of oil increases *before* the onset of many wars.
Comment: Let me start by stating I consider the question a very interesting one, and I would love to see it answered even in its more general form(http://stats.stackexchange.com/questions/99582/find-correlated-regions-from-time-series).

I think there are two ways of looking at it. The first is that prices during war are higher, the second is that the onset of a war leads to a price jump. If the second option is what you would like to prove (which I find more interesting but more complicated), should one consider some kind of saturation mechanism associated to the price increment?
Comment: Thank you for your attention @pedrofigueira. You are right, I am not looking for some simple ANOVA solution (comparison of prices between war and peace time), but rather some time series analysis technique.
Answer: The data suggests a possibly useful model . TH Actaul and Fitted values are graphed here. Th residual plot does not indicate non-randomness  . The equation incorporates memory an an identified level shift at period 10 while suggesting a significant effect of the ear variable to be +1.4392 . The full reporting of the statistical model is  and  . The P value for the war indicator is close to 0.0 . The method used here was to form a regression model between y and x and then identify the need for the level shift indicator reflecting an unspecified event. Additionally the error structure suggested non-randomness necessitating augmenting the model with an arima process of order (2,0,0)(0,0,0) . In this way the resultant error process is rendered Gaussian and the tests of significance become meaningful.
Comment: @Ladislav The method is called Transfer Function or Dynamic Regression. It incorporates Intervention Detection http://www.unc.edu/~jbhill/tsay.pdf procedures which have been extended to cover cases where there are known possible predictors (x=war).
Comment: remarkably comprehensive answer. If I understood it correctly, it is based on the existance of a regression model on variables $X_1$ and $X_2$. How did you construct that model?
Comment: The data are fake.  Oil prices did not behave as shown.  Therefore it is important to focus one's answer on *assumptions, principles, and methods* rather than results.
Comment: Whether data is real or simulated is not important. What is important is the approach that is taken and understanding the assumptions that are in place AND if and when these assumptions are validated as was the case in my analysis.
Comment: It is true that my data are FAKE. @whuber could you provide a name for this procedure? How would you call it? (possibly name or package in R)
Comment: Thank you @IrishStat for your answer, could you provide a method used for constructing that model? (first plot in your answer - green line and points)
Answer: strucchange package in R (Zeileis et al. 2003) - with this you can identify changes or significant breaks in your time series and study and possibly relate significant break points to war events. Denisiar
Comment: You might want to look at my response to http://stats.stackexchange.com/questions/16953/how-to-detect-structural-change-in-a-timeseries . It is VERY important to consider time trend changes.


Group by on table, list all of one attribute for each of another attribute

Question: I'm attempting to group this data by name so that instead of current query output giving me:
Name                       Number
Nice guy                   1
Nice guy                   2
Nice guy                   4
Nice guy                   5
Nice guy                   6
Nice guy                   7
Nice guy                   8
Nice guy                   9
Nice guy                   10
Nice guy                   11
Nice guy                   12
Frank                      3
Frank                      4

I would get this:
Name       Number
Nice guy   1,2,4,...
Frank      3,4

Here is my current query:
select distinct name, number
from patterns,numbers,people
where patterns.index=numbers.index
AND patterns.id=people.id
order by name, charge;

What I have tried is this, but it fails:
select distinct name, number
from patterns,numbers,people
where patterns.index=numbers.index
AND patterns.id=people.id
group by name
order by name, number;

Any help would be greatly appreciated!
Answer: UPDATED: Try it this way
SELECT name, WM_CONCAT(number) number
  FROM
(
  SELECT DISTINCT name, number
    FROM patterns t JOIN numbers n
      ON t.index = n.index JOIN people p
      ON t.id = p.id
) q
 GROUP BY name
 ORDER BY name

Comment: This works! However, I now get duplicate values with the concatenation. Meaning for Nice guy I get 1,1,2,... instead of what I was getting before with 1,2,... Is there any way to remove the duplicate values from this?
Comment: thanks, I just got this on my own but I appreciate it nonetheless! hadn't seen that function before. Much appreciated!


Add FILTER CRITERIA in Views Programmatically

Question: I want to add/modify a filter criteria programmatically.
For example, for a view, I added an "Email Address" filter whose value is needed to change dynamically, it is needed to set to the current logged in user's email id.
How to achieve that? Please see attached image for more details. Please help.
Answer: Use the Devel module and dpm($view) and dpm($query) after you put like "email@example.com" into the "value" field found in your pic. See the object/array structure of the view and query from the devel output.
Then use the function hook_views_query_alter(&$view, &$query) in your module to target the WHERE condition filter condition and set it to the value you want.
Something like:
function MYMODULE_views_query_alter(&$view, &$query) {
  global $user;
  dpm($view, __FUNCTION__);
  dpm($query, __FUNCTION__);
  if ($view->name === 'your_view_machine_name') {
    // This will only work as-is if you always have something in the filter by
    // default, I guess. This hook runs always so you could just put
    // 'firstname.lastname@example.com' as the email to filter by in views and this
    // will always override it. I'm sure there is a cleaner way to put
    // the filter dynamically at runtime. But i think thats more complex
    // php that customizes a view.
    //
    // The index 2 below is the index of the condition for the email filter.
    // Your $query structure may be different in your dpm() of the View $query.
    $query->where[1]['conditions'][2]['field']['value'] = $user->email;
  }
}

Comment: Many thanks! Can you please tell me where do I first, write `dpm($view);`?
Comment: you make a custom module and place the above function it in. the hook will fire if views are enabled and you will see the $view and $query at the top of the page once you've enabled the custom module and the Devel module. Then just change my code to have your view's machine name it in ... and making the $query values work with your exact query ...
Comment: That's a great answer. In Drupal 7 you actually do:
$query->where[1]['conditions'][2]['value'] = $user->email
Comment: Personally I think the answer using the hooks below is much better https://drupal.stackexchange.com/a/200870/9634
Answer: Here's an alternative:
$view = views_get_view('view_machine_name');
$view->init_display('default');
$view->display_handler->display->display_options['filters']['your_filter_name']['default_value'] = 'your_value';
$view->is_cacheable = FALSE;
$view->execute();
print $view->render();

I know you should probably set this using some esoteric, convoluted method, but if you just want quick and dirty access without messing around this will get you there.
Answer: It would be preferable to alter these in hooks rather than at render time so that you are not undermining site performance and caching. Took me age to figure out that hook_views_pre_build() fires too late, you need hook_views_pre_view().
I found reference to using $view->add_item() but struggled for examples, below was my solution for filtering a set of taxonomy terms to only include certain vocabs:
function MODULENAME_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name == 'VIEWNAME' && $display_id == 'DISPLAYID') {
    // Add all the terms of a vocabulary to the terms listing widget select field
    $vids = array();
    $vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
    $vids[ $vocab->vid ] = $vocab->vid;

    // Get the existing filters
    $filters = $view->display_handler->get_option('filters');

    if (empty($filters['vid'])) {
      // There is no vid filter so we have to add it
      $view->add_item(
        $view->current_display,
        'filter',
        'taxonomy_term_data',
        'vid',
        array(
          'operator' => 'in',
          'value' => $vids,
          'group' => 1
        )
      );
    }
    else {
      // Add to pre-existing filter
      foreach($vids as $vid) {
        $filters['vid']['value'][ $vid ] = $vid;
      }
      $view->display_handler->override_option('filters', $filters);
    }
  }
}

Edit note: This comment on d.o group helped me figure out how to get the views filters using $view->display_handler->get_option('filters') and to then override them using $view->display_handler->override_option('filters', $filters);.
Answer: I've had a similar issue but where trying to pass in multiple arguments to a filter.  I have used the "views_get_view" method, but passing in arguments to the view.  I hope it helps someone.  You can substitute any argument type or value for your needs:
I have added contextual filters to the view itself (from the advance view settings fieldset).  The first one is a "content: has taxonomy term ID".  The 2nd one is "content: nid" with "allow multiple" checked and "exclude" checkbox checked (from the 'more' fieldset in the contextual filter pop-up).

args[] = '1'; // Term ID
args[] = '1+2+3'; // Node IDs to exclude/include

$view = views_get_view($view_name);
$view->init();
$view->set_display($display);
$view->set_arguments($args);
$view->execute();
$view->result

Update:  I forgot to mention, within the contextual filter values, you may need to select php code and return the view arguments passed in.  Eg:

return $view->args[1];
Answer: In Drupal 8 you can use ViewExecutable::setHandler($display_id, $type, $id, $item) to set a filter programmatically.
Comment: This answer could be a bit more verbose about why this works. Often I like to link and quote the documentation pages. This would help the asker learn more about the Drupal API and help find information for themselves in the future.
Answer: Here's an example on how filter criteria can be added programmatically in Drupal 8:
/**
 * @param ViewExecutable $view
 * @param QueryPluginBase $query
 *
 * Sets a custom custom filter criteria (takes current language into account)
 */
function MODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->storage->id() === 'my_view_id') {
    $query->addWhere(0, 'node__field_custom_criteria.field_custom_criteria_value', \Drupal::languageManager()->getCurrentLanguage()->getId(), '=');
  }
}

The above query will add a criteria that filters nodes where the field_custom_criteria field equals the currently selected language.
More info can be found in the docs: hook_views_query_alter
Answer: Based on @Duncanmoo's answer above that I felt was best, I added the following filters to my view - thought these would be useful examples in case you weren't trying to filter based on a referenced taxonomy but instead on a referenced entity or a NID:
function [MYMODULE]_views_pre_view(&$view, &$display_id, &$args) {
  if (($view->name == '[your view name]') && ($display_id == '[your display id]')) {
    // Get referenced service - example for entity reference.
    $node = menu_get_object();
    $node_wrapper = entity_metadata_wrapper('node', $node->nid);
    $referenced_service = $node_wrapper->field_service_ref->value();
    // Add service id as a filter to view.
    $filters = $view->display_handler->get_option('filters');
    if (empty($filters['field_service_ref_target_id'])) {
      // Only display operations nodes that reference the same service.
      $view->add_item(
        $display_id,
        'filter',
        'field_data_field_service_ref',
        'field_service_ref_target_id',
        array(
          'operator' => '=',
          'value' => ['value' => $referenced_service->id],
          'group' => 1
        )
      );
    }
    // Add nid as a filter to view - example for NID filter
    if (empty($filters['nid'])) {
      // Don't include current operation in list of related operations.
      $view->add_item(
        $display_id,
        'filter',
        'node',
        'nid',
        array(
          'operator' => '!=',
          'value' => ['value' => $node->nid],
          'group' => 1
        )
      );
    }
  }
}


Show data like tool tip when hovered over portion or regions on a custom map

Question: I have a map and i want to create some regions in the map. When hovered on that region i need to show some content from database may be preloaded also. so which module should i use to create this task. when i hover should be able to show some click-able links to the user.
Answer: What kind of map is it? An HTML imagemap (using  and  tags)? If so, you can use the EasyToolTip and MapHilight JavaScript libraries. They aren't connected to any Drupal modules, as far as I know.
EasyToolTip allows you to format the tooltips almost any way you want, and MapHilight allows you to highlight the section of a map that the mouse is hovering over.
Comment: yes its an image map. When i hover on the # attribute i should be able to show some links and i should be able to go and click on those links
Comment: Then the two libraries should do what you want, quite easily, too. I ran into problems because I wanted several optional layers on top of my imagemap, and EasyToolTip wasn't being called (haven't figured out the solution yet).
Answer: I found these 3 links useful.
http://www.red-team-design.com/image-map-with-css3-jquery-tooltips
http://www.workwithchoicecuts.com/methodology/revisiting-the-html-image-map/
http://www.workwithchoicecuts.com/demo/html-image-map-revisted/index.htm


[Como verificar se a minha lista possui letras ou palavras em Pyton]

Question: Possuo uma lista em Python e preciso saber se possui alguma palavra ou letra, pois preciso que ela só tenha números
    def sum_of_products(lista):
if type(lista) != int:
    print("Possui letras")
else:
    print("Somente Numeros")

Pensei em algo mais ou menos assim, mas não encontro a solução.
Comment: E se possuir a *string* `'42'`, que é uma *string* numérica, o que deve acontecer?
Comment: Ele teria que recusar e entender como se fosse uma palavra
Answer: Supondo que você tem uma lista:
lista = [1,232,723,221,'numero',3455]

De forma simples, você precisa checar pelos ITEMS da lista, não pela lista:
for item in lista:
    if type(item) != int:
        pass

Agora verificando se existe de forma mais compacta:
possui_letras = any(type(item) != int for item in lista)
if possui_letras:
    print("Possui letras")
else:
    print("Somente Numeros")

Comment: Extamente isso que eu precisava, funcionou perfeitamente. Muito obrigado!


$f:(0,1)\cup (1,2)\to \Bbb R$ and $f(x)=0$ if $x\in (0,1)$ otherwise $1$.

Question: Till today, I always thought that if the derivative of a function is $0$ at every point in the  domain, then the only functions possible for which this is true are constant functions. But, my teacher gave me the example $$f:(0,1)\cup (1,2)\to \Bbb R$$ with
$$f(x) = \begin{cases}0&\mathrm{\ if\ } 0<x<1 \\ 1 &\mathrm{\ if\ }1<x<2\end{cases}$$
This function is not constant but has derivative $0$ everywhere in domain.I know it is pretty much possible because of the domain he chose, but what is special there in this domain which makes this happen.
Can anybody give some other examples not of this form (which I gave above) having derivative $0$ without function being constant.
Comment: http://math.stackexchange.com/questions/71972/if-derivative-of-a-function-is-the-zero-function-in-mathbb-rn-then-the-func
Answer: A differentiable function with zero derivative is constant on the connected components of its domain.
The function $\displaystyle f : \mathbb{R}-\mathbb{Z} \to \mathbb{R}$ given by $f(x) = \lfloor x \rfloor$ has derivative $0$ everywhere and it takes, not just 'more than one value', but in fact it takes infinitely many values $-$ you can't even bound it! But it is constant on all of the connected components of its domain; explicitly, $f|_{(n,n+1)}(x) = n$ for all $x \in (n,n+1)$.
In fact, any step-function will do, provided you remove the points at which it is not continuous from its domain.
Comment: @Avatar: Yes $-$ if it's constant on the connected components of the domain, and the domain only has one connected component, then it must be constant on the whole domain! More generally, if the domain has $n$ connected components then $f$ can take $\le n$ distinct values.
Comment: so, if my domain is connected, then the only class of functions possible with given conditions is constant function, right??
Comment: thanks for the help; i got the idea now.
Answer: Have you considered the function $f: \mathbb R\setminus\{0\} \to \mathbb R$ defined by $f(x):=\arctan(x)+\arctan(1/x)$?
Anyway this is not a real answer to your question. Indeed, the following theorem holds true:

If $f\colon A\subset \mathbb R \to \mathbb R$ is differentiable at every point of $A$ with $f'(x) \equiv 0$ then $f$ is constant on every connected component of $A$.

So the "key" to understand the examples lays in the topological properties of the domain. If the set $A$ is connected then every differentiable function $f :A\to \mathbb R$ with zero derivative (everywhere) is constant.
Hope this helps.


Prove that if $x$ is odd, then $x^2$ is odd

Question:
Prove that if $x$ is odd, then $x^2$ is odd

Suppose $x$ is odd. Dividing $x^2$ by 2, we get:
$$\frac{x^2}{2} = x \cdot \frac{x}{2}$$
$\frac{x}{2}$ can be rewritten as $\frac{x}{2} = a + 0.5$ where $a \in \mathbb Z$. Now, $x\cdot\frac{x}{2}$ can be rewritten as:
$$x\cdot\frac{x}{2} = x(a+0.5) = xa + \frac{x}{2}$$
$xa \in \mathbb Z$ and $\frac{x}{2} \notin \mathbb Z$, hence $xa + \frac{x}{2}$ is not a integer. And since $xa + \frac{x}{2} = \frac{x^2}{2}$, it follows that $x^2$ is not divisible by two, and thus $x^2$ is odd.
Is it correct?
Comment: If you are saying $x=2a+1$ for some integer $a$ then an easier approach may be to say $x^2= 2(2a^2+2a)+1$ which is $1$ more than an even number and so odd.
Comment: odd times odd is odd
Comment: proof by contrapositive:  if $x^2$ is even, then $2|x^2,$ so $2|x$ (by Euclid's lemma), so $x$ is even
Comment: Yes, your proof is correct. Good job!
Answer: Let $x = 2k + 1 \in \mathbb{Z}$ be odd. So, $$ x^{2} = (2k + 1)^2 = 4k^{2} + 4k + 1 = 2(2k^{2} + 2k) + 1$$ Let $t = 2k^{2} + 2k  \in \mathbb{Z}$, thus: $ x^{2} = 2t + 1$.
Comment: This is not an answer to the question.
Comment: @let'shaveabreakdown This is an answer to "Prove that if $x$ is odd then $x^2$ is odd" which is not the question. The OP has given this the proof-verification tag, and asked "is [the proof in the question] correct?" This answer does not address that question.
Comment: @SantanaAfton The only thing missing is "and $2t+1$ must be odd" which is understood if you followed the proof from the beginning since it starts with understanding $2k+1$ is odd.
Answer: Your written proof is correct. FYI, here is another proof technique which, although it's far more than you need in your case as Bill's comment indicates, is somewhat shorter and, perhaps, of some use to you, such as for other more complicated related problems.
Since $x$ is odd, this means it has no factors of $2$. By the Fundamental theorem of arithmetic, $x^2$ has the same prime factors as $x$, just twice as many of each of them and, thus, also no factor of $2$. As such, it is also odd.
Comment: @OP while that's worth knowing, one should be aware that using FTA here is like using a sledgehammer to crack open a nut. Much less powerful methods suffice (e.g. parity arguments).
Answer: Your proof is correct.
You could also prove by contrapositive:
if $x^2$ is even, then $2|x^2=x\cdot x,$ so by Euclid's lemma $2|x,$ so $x$ is even.
If you don't like that, you could say $x$ is odd, and the product of two odd numbers is odd,
so $x^2=x\cdot x$ is odd.
If you don't like that, you could argue as follows:
if $x$ is odd, then $x-1=2k$ and $x+1=2k+2$ with $k \in\Bbb Z$,
so $x^2=(x-1)(x+1)+1=(2k)(2k+2)+1=2(k(2k+2))+1$ is odd.
Answer: Yes, $ $ your proof is correct. $ $ You have $\ a = \color{#c00}{(x\!-\!1)/2}\in\Bbb Z\ $ so eliminating $\,a\,$ the proof becomes
$$\begin{align} &\dfrac{x^2}2 - \dfrac{x}2\, =\, \dfrac{x(\color{#c00}{x\!-\!1})}{\color{#c00}2}\in \Bbb Z\\[.2em]
\Rightarrow\ \ \ &\dfrac{x^2}2\in\Bbb Z\iff \dfrac{x}2\in\Bbb Z\\[.2em]
\Rightarrow\ \ \ & \ \ \ \ 2\nmid {x^2}\iff\ \  2\nmid x\\[.2em]
{\rm i.e.}\  \ \ & \ x^2\  {\rm odd}\ \iff x\ \  {\rm odd}
\end{align}\qquad\qquad\qquad\qquad$$


How to avoid evaluation of TFunc> when passing as method argument?

Question: I have the following method:
InstanceOfMyType(const Name: String; const Modifiers: array of TFunc<TProc<TMyType>>);

The idea is to allow fluent setup code in unit tests.
The problem occurs when I try to call that method:
// in test helper methods
function TTest.WithSomeProperty: TProc<TMyType>
begin
Result :=
  procedure (MyType: TMyType)
  begin
  // modify MyType instance
  end;
end;

// in the test
Given;
  InstanceOfMyType('Name', WithSomeProperty);

Is there any way to force the compiler not to evaluate the passed TFunc and produce a compile time error?
[DCC Error] IndexerTests.pas(257): E2010 Incompatible types: 'array of System.SysUtils.TFunc<System.SysUtils.TProc<TMyType>>' and 'System.SysUtils.TProc<TMyType>'

WithSomeProperty is obviously a TFunc<TProc<TMyType>> but the compiler always evaluates it and try to passes the resulting TProc<TMyType> to the method which naturally does not pass compile-time checking.
Comment: Just write `InstanceOfMyType('Name', [WithSomeProperty]);` and it compiles.
Comment: How about adding square brackets since you are passing one value to an argument that requires an array? The compiler error is pretty clear about that.
Comment: @StefanGlienke note that this is an open array parameter.
Comment: @StefanGlienke Thanks! It just surprises me, can you explain why? I guess I could live with the square brackets although they do add additional noise.
Comment: @StefanGlienke It's worth noting that compilation is not enough. Some versions of Delphi compile the original code, but the code that the compiler emits is bogus.
Answer: This program compiles and outputs 12 on XE2:
{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function GetProc: TProc<Integer>;
begin
  Result :=
    procedure(Value: Integer)
    begin
      Writeln(Value);
    end;
end;

procedure CallProc(const GetProcArr: array of TFunc<TProc<Integer>>);
begin
  GetProcArr[0]()(666);
end;

begin
  CallProc([GetProc]);
  Readln;
end.

Normally you are allowed to omit the square brackets when preparing an argument for an open array parameter, and the compiler transforms that into a single element array. But that seems to confuse the compiler with this parameter type.
In XE2,
CallProc(GetProc);

results in the E2010 compile error that you reported.
In XE7
CallProc(GetProc);

compiles but then results in a runtime error. So clearly there are still compiler bugs relating to this undocumented feature to turn single values into single element open array arguments.
Unfortunately this mess is a direct result of the decision by the language designers to allow you to omit the parens on a function call. Whilst that does result in arguably more readable code, it does sometimes leave the compiler in situations where an expression is simply ambiguous. That's the case here and you have to explicitly resolve the ambiguity. Is the benefit of omitting the parens when calling functions worth the downside of this ambiguity? In my view it is not.
Comment: +1 Do you understand what makes the difference here in terms of why the compiler evaluates in one case and not in the other?
Comment: I think there are compiler bugs


Restrict access to folder inside public_html

Question: I am currently making a WordPress user system, that is supposed to feature private files, that can be uploaded to each user. In order to achieve this, I am using a filter that places the files in question in a subfolder to uploads named secretfiles. The filter won't allow me to place the files outside the public_html, so I have to do it this way.
Now I am planning to exclude all access to the this 'secretfiles' folder using .htacces, and write a downloadscript that checks whether a user is allowed to download requested files, before sending them to him.
Would this be a safe way to make the files truly private, even though they are placed inside the public_html folder. And what would my .htaccess code be?
Thanks!
Comment: What have you tried? Where's the code you're using that demonstrates the problem? Why wouldn't the filter allow you to place the files outside public_html? What is this filter? What does it do? Did you [read the Apache httpd manual](https://httpd.apache.org/docs/2.4/howto/access.html) to learn how to restrict access? Did you read [how to ask a question](http://stackoverflow.com/help/how-to-ask) in the StackOverflow help center to get some guidelines about how to ask before asking?
Comment: This certainly is possible. It is not great, but maybe all you can do according to your own words. Whether it is "safe" is another question, since there are endless of aspects to consider we do not know about. Generally using a simple web hoster (it sounds as if you do) can _never_ be considered safe, since you have absolutely no control over your files in that situation.
Comment: About the exact rules you have to configure: please start by reading the excellent documentation offered for the modules of the apache http server. You will find good explanations and a wealth of great examples.
Answer: You can deny all access from directly accessing the files in a directory using an .htaccess file (see below example). Users can still access this files if they have been enclosed in a download script as suggested. Note, that the download script should not be a redirection. It should send the file itself.
<code>Deny from all
</code>
Comment: Wouldn't it make much more sense to block access to the folder instead of specific file name extensions? What about the folder index for example? And other file name extensions? Upper case for example?
Comment: You changed the code, you should also change your description to match it. This are confusing the way they are now...


Is it necessary for a name server to publish its own IP address?

Question: Suppose I am setting up a new name server at ns1.example.com, and I have properly created the glue record at my registrar to tell the registry that ns1.example.com should point to my name server's IP address at 188.8.131.52. Is there anything in the configuration of my name server that needs to also publish this IP address in a zone? I.e. publish an NS or A record for itself?
If the name server didn't publish its own IP address (aside from in the registry glue record) would clients still be able to query me for other records successfully?
Answer: The name server needs to publish its own record for the name.  Glue records should only be used to "bootstrap" discovery, and then be discarded in favour of the result retrieved from the actual authoritative nameservers.  I'm not entirely sure what recursive resolvers will do when they get NXDOMAIN for a record they got glue for, but I'm pretty confident it won't be pretty, nor consistent between implementations.
Comment: Just what I thought. Thank you for the confirmation :-)


select where in - custom order

Question: $str = "25,12,13,19";

$sql = "select id, src, link from banners where id in (" . $str . ")";

This works but rows are ordered this way - 12,13,19,25
How can I get the rows ordered by $str values, i.e. - 25,12,13,19 ?
Comment: Possible duplicate of [MySQL sort order by array value](https://stackoverflow.com/questions/8055138/mysql-sort-order-by-array-value)
Answer: Unless you explicitly sort the result, the engine is free to return the rows of the result in any order. To sort a result you have to include an ORDER BY clause. Here you can use field(). It gets the position of a value in a list of values.
SELECT d,
       src,
       link
       FROM banners
       WHERE id IN (25, 12, 13, 19)
       ORDER BY field(id, 25, 12, 13, 19);

select where in - custom order


Request do MooTools: onSuccess não é disparado

Question: Estou usando KnockoutJS em conjunto com o MooTools, mas estou tento problemas com o Request.

      <select data-bind="options: classificacoes, optionsText: ds_classificacao, optionsValue: id"></select>

App.requests.classificacoes = new Request.JSON({
    url: "/classificacoes.json",
    method: "get"
});

App.viewModels.selectsProcedimentos = new Class({
    initialize: function() {
        this.classificacoes = ko.observableArray([]);
        App.requests.classificacoes.send({
            onSuccess: function(classificacoes) {
                this.classificacoes.push(classificacoes);
                alert("baixou");
            }
        });
        alert("initialize");
    }
});

O que acontece aqui é que o initialize é disparado, mas o método onSuccess não, sendo que o <select> fica vazio. Porém na aba network das ferramentas de desenvolvimento dá pra ver que o JSON é baixado. Não há erros no console.
Answer: Você tem de defenir o handler do evento onSuccess dentro da Classe Request. O método send() aceita dados para passar para o lado do servidor e opções para a Classe, mas não novos Eventos da Classe. Dê uma olhada na documentação e repare na diferença entre options e events.
Teste assim:
App.requests.classificacoes = new Request.JSON({
    url: "/classificacoes.json",
    method: "get",
    onSuccess: function(classificacoes) {
        // this.classificacoes.push(classificacoes); // acho que aqui está a usar o this de maneira incorreta
        alert("baixou");
    }
});

App.viewModels.selectsProcedimentos = new Class({
    initialize: function() {
        this.classificacoes = ko.observableArray([]);
        App.requests.classificacoes.send();
        alert("initialize");
    }
});

Com este código em cima resolve o problema mais evidente.
Porém não compreendo como quer usar o this.classificacoes.push(classificacoes); uma vez que o ajax é asincrono.
Não seria caso de fazer o pedido e no onSuccess então instanciar a Classe App.viewModels.selectsProcedimentos? ou fazer o .push() para a propriedade da Classe que guarda essa array com App.viewModels.selectsProcedimentos.classificacoes.push(classificacoes);
Comment: Realmente estou tendo dificuldades para achar o melhor jeito de fazer isto. A questão é que são 4 selects, este é só o primeiro, com os outros vou ter que puxar por AJAX depois de qualquer jeito. Eu vou fazer o seguinte: vou criar o Request dentro da classe mesmo. Assim que der certo atualizo a pergunta com a solução.
Comment: @Andrey quer dizer a Classe Knockout dentro do Request do MooTools e não "Request dentro da classe", certo? Se Colocar esses 4 selects num jsFiddle e postar aqui posso dar uma olhada.
Comment: Eu quis dizer fazer `new Request({...}).send();` dentro da minha classe do viewModel. Não fiz o JSFiddle porque o AJAX dele nunca funcionou direito pra mim.
Comment: @Andrey, porque não faz `classificacoes` sendo um `computed`? No momento em que o `computed` for "evaluado" pelo `knockout`, você faz o request. Isso é bom porque se você usar qualquer `observable` dentro do `computed`, ao alterar o valor do `observable`, o `computed` é "reevaluado".
Comment: @Wakim Estou começando com Knockout. Como funciona o computed? Eu faço a requisição AJAX dentro dele e retorno? `ko.computed(function() { return "meu array json" });`? O problema é que a requisição é assíncrona.
Comment: É, pensando bem não vale a pena, porque você teria que criar uma "flag" `observable` para criar uma dependência e forçar a "reavaliação" do `computed`. Isso só vale a pena se o AJAX para recuperar os valores de `classificacoes` depender de algum outro valor que pode mudar. Acho que não vai cair bem no seu caso.
Answer: Consegui fazer da seguinte maneira:
Javascript:
App.viewModels.selectsProcedimentos = new Class({
    initialize: function(classificacoes) {
        this.classificacoes = ko.observableArray(classificacoes);
    }
});

App.init.selectProcedimentos = function() {
    new Request.JSON({
        url: "/classificacoes.json",
        method: "get",
        onSuccess: function(classificacoes) {
            ko.applyBindings( new App.viewModels.selectsProcedimentos(classificacoes) );
        }
    }).send();
};

E o HTML:

    <select data-bind="options: classificacoes,
                       optionsText: 'ds_classificacao',
                       optionsValue: 'id',
                       optionsCaption: 'Selecione uma Classificação'"
            class="form-control input-sm"></select>

Agradeço a paciência do @Sergio e do @Wakim
Agora é quebrar a cabeça pra fazer os selects que são dependentes deste.


Most computationally efficient way to classify the comparison two numpy arrays of 1s and 0s; if an index of both contains 1s, or 0s, etc

Question: Say I have two numpy arrays
prediction = np.array([1, 0, 0, 1, 1, 0, 1, 1, 1])
groundtrue = np.array([1, 0, 1, 0, 1, 1, 0, 0, 1])

I would like to compare the two arrays, including a classification of each index comparison. So I want to classify if both prediction and groundtrue have 1s, or if prediction has 1 and groundtrue has 0, or vise versa, etc.
So an example desired result could look like this
comparison = np.array([1, 2, 3, 4, 1, 3, 4, 4, 1])
1 is used if both have 1s. 2 is used if both have 0s. 3 is used if if prediction has 0 and groundtrue has 1. etc.
The most straight forward way is to use a loop and directly compare each index but it seems that numpy may have some operators that can do this very computationally efficiently and much less lines of code
np.where(prediction == groundtrue, 1, 0)
Can get me an array where the two values are equal, or not, but I don't see it giving different types of comparisons.
Comment: `prediction + 2 * groundtrue` will give a classification, might not be the order you wanted though.
Comment: This solves my answer. You can submit this as an answer and I'll select it.
Answer: Since you have only 0s and 1s in prediction and groundtrue, there will be only 4 cases in total. Hence you can create a classification with:
prediction + 2 * groundtrue
# array([3, 0, 2, 1, 3, 2, 1, 1, 3])

It won't be the same order as in OP, but enough to distinguish different cases.

0 if both prediction and groudtrue are 0s;
1 if groudtrue is 0 and prediction is 1;
2 if groudtrue is 1 and prediction is 0;
3 if both are 1s;
Answer: One can do this with boolean masks.
import numpy as np

prediction = np.array([1, 0, 0, 1, 1, 0, 1, 1, 1])
groundtrue = np.array([1, 0, 1, 0, 1, 1, 0, 0, 1])

comparison = np.zeros_like(prediction)
comparison[(prediction==1) & (groundtrue==1)] = 1
comparison[(prediction==0) & (groundtrue==0)] = 2
comparison[(prediction==0) & (groundtrue==1)] = 3
comparison[(prediction==1) & (groundtrue==0)] = 4
comparison  # array([1, 2, 3, 4, 1, 3, 4, 4, 1])

The following gives the same output as the above, but you only need to compute two masks. This assumes that prediction and ground truth can only have values of 0 or 1.
import numpy as np

prediction = np.array([1, 0, 0, 1, 1, 0, 1, 1, 1])
groundtrue = np.array([1, 0, 1, 0, 1, 1, 0, 0, 1])

pred0 = prediction == 0
ground0 = groundtrue == 0
comparison = np.zeros_like(prediction)
comparison[~pred0 & ~ground0] = 1
comparison[pred0 & ground0] = 2
comparison[pred0 & ~ground0] = 3
comparison[~pred0 & ground0] = 4
comparison  # array([1, 2, 3, 4, 1, 3, 4, 4, 1])

The masks will have boolean values, where each value indicates whether the condition is true in the original array.
x = np.array([0, 1])
x == 0  # array([ True, False])

The & operator will compute the logical AND of both boolean arrays. See numpy.logical_and for more information.
Then, one can use the boolean mask to subset certain values. We can assign that subset of indices a new value.
x = np.array([0, 1])
x[x==0] = 2
x  # array([2, 1])

Answer: You can try using code like this:
import numpy as np
prediction = np.array([1, 0, 0, 1, 1, 0, 1, 1, 1])
groundtrue = np.array([1, 0, 1, 0, 1, 1, 0, 0, 1])
lut=np.array([2,4,3,1]) #look up table
pow_two=2**np.arange(2)
comparison=lut[np.dot(pow_two, np.vstack((prediction, groundtrue)))]


Change sort order of SOURCE STRING list at User interface translation page to alphabetical instead of date created

Question: At the User interface translation page (/admin/config/regional/translate) the SOURCE STRING list seems to be ordered by creation date/time (it is for strings I add). Is there a "good" (non-hackish) way to change the order to alphabetical? I haven't found anything in the interface.
For those who wonder why I want this, I use interface translation in an unconventional way. Instead of putting literals like t("Choose your options") in my code, I put in a key like t('rsc-string-choose-options') [rsc is the name of my custom module]. Then as the translation, I put in "Choose your options". This allows me to use "keys" for all strings (literals, messages, titles, email body text, etc.). It's easy to look up my keys because they all begin with 'rsc-' followed by 'string', 'message', 'email', etc. depending on usage. Doing this provide a nice interface for editors to go in and change the text of the strings, since they can look them up either by translation or by key. I also wrote a nice utility that allows me to add, remove, rename, and test keys (i.e. translation strings). It's working very well, but it would make review much easier if the source strings were alphabetical.
Answer: It depends on what you want to call "good" & "non-hackish".
If you're looking for a simple configuration change, then no; there's no configuration change that you can make to modify the translation strings order.
If non-hackish includes using Drupal APIs to override routes & services in a custom module, then yes.
You can use a custom module to override the locale.translate_page route with your own custom controller & form class that will do the same work of TranslateEditForm::buildForm(), but modify the behavior of
::translateFilterLoadStrings() so it produces a different ordered list of translation strings.
The string order is the result of a method in the locale.storage service that performs the dynamic query (see StringDatabaseStorage::dbStringSelect() where the query is built). You'll probably have to override that service in some manner to provide the same structured query object, but with an orderBy method added to execute the same query but with the sorted order you're looking for.
Comment: Yes, I consider this non-hackish. I'll try it and report.


Sublime 2 less2css not compiling automatically

Question: When I save my style.less, the code isn't being auto-compiled. Is there something I'm doing wrong? Below is what I have in my ox.sublime-project file:
{
        "folders":
        [
            {
                "path": "projects/example/web"
            }
        ],
        "settings":
        {
            "less2css":
            {
                "autoCompile":true,
                "main_file":"/projects/example/web/style.less",
                "minify":false
            }
        }
    }

I see this in the console when I save my style.less:

Traceback (most recent call last):
  File "/Applications/Sublime
  Text.app/Contents/MacOS/sublime_plugin.py", line 574, in run_
      return self.run(edit)
  File "less2css in /Users/jlei/Library/Application Support/Sublime Text 3/Installed
  Packages/Less2Css.sublime-package", line 57, in run
  File
  "lesscompiler in /Users/jlei/Library/Application Support/Sublime Text
  3/Installed Packages/Less2Css.sublime-package", line 152, in
  convert_one
  File "lesscompiler in /Users/jlei/Library/Application
  Support/Sublime Text 3/Installed Packages/Less2Css.sublime-package",
  line 254, in convertLess2Css
  File "./python3.3/os.py", line 251, in
  makedirs   File "./python3.3/os.py", line 251, in makedirs
  File
  "./python3.3/os.py", line 251, in makedirs
  File "./python3.3/os.py",
  line 262, in makedirs
PermissionError: [Errno 13] Permission denied: '/projects'
Comment: According to the error log, you need to check your permissions for `/projects`. I've been wondering about the mismatch: `projects` vs `/projects`. I installed the package via Package Control and had no problems saving LESS as CSS (I didn't use a project file)
Comment: Are there any errors in the console?
Comment: which console are you referring to? the thing at the bottom of sublime? if so, no there is no conflict. it just says it's saving but it doesn't say it's compiling
Comment: From the application menu `View > Show Console`
Comment: Also, is `lessc`  installed on your system?
Comment: Do I need that? I thought I only need Less2Css? Also in the console I've edited it to include what I can in the console
Comment: I don't know, it says so in the README: "Requires lessc installed on PATH."
Comment: Ok I installed lessc and restarted sublime. Still doesn't work. Using Package Control shouldn't make a difference right?
Comment: i changed the path and it works!
Answer: Could this be caused by the mismatch of path names? First, you're using "projects/example/web", later it's "/projects/example/web/style.less"(note the leading slash).


How to make featured image clickable? -Wordpress

Question: How to make all the featured image clickable automatically? As it's Wordpress theme, I can only edit php or add css.
Comment: Reina try my following code it may helpful to you
Comment: Visit https://stackoverflow.com/questions/37554683/make-featured-image-clickable-wordpress
Comment: i think at the time of adding feature image , it asked to choose from media and give a link box at the right side of the opened pop-up (through which you are going to choose image). where you can add link. and it will become clickable...
Comment: @AlivetoDie yes you are right but i think that functionality it depends on which theme are you use.
Answer: Simply add this code to your theme's functions.php file.
This code simply adds a link around the code generated to display featured images or post thumbnails on your website.
function wpb_autolink_featured_images( $html, $post_id, $post_image_id ) {
    $html = '' . $html . '';
    return $html;
    }
    add_filter( 'post_thumbnail_html', 'wpb_autolink_featured_images', 10, 3 );

This code will also add a link around featured images on single post pages. If you don't want to link featured images on single post to the same post, then use this code.
function wpb_autolink_featured_images( $html, $post_id, $post_image_id ) {

If (! is_singular()) {

$html = '' . $html . '';
return $html;

} else {

return $html;

}

}
add_filter( 'post_thumbnail_html', 'wpb_autolink_featured_images', 10, 3 );

Answer: Normally the functionality of a featured image has no link attached to it. Different themes use the functionality of featured image differently. The new Twenty Nineteen theme, for example, uses it as the background for the page header, behind the post title.
So it will be better to make a child theme of your parent theme and edit the php file to set a link. Without editing the code you cannot set the link of the featured image.
Answer: Insert image > Click on the desired cell you want to insert it > Down on the right: "Linked to" > Personalized URL.


Chrome collapsing the width of inline element with dynamic content

Question: If you open the following URL in google chrome you will see the problem, on first load it's ok but if you keep refreshing the width of the 3 items at the top (Bedingungen, Preise and So geht's) collapse. In firefox it's ok but I have no idea why it does it in chrome, anyone see why it might happen or is there a solution? Thanks!
The text is loaded in with Ajax/json and they are inline because I want them to be the width of the text. I don't want to set a fixed width.
http://alexanderlloyd.info/test/
CODE

<code>CSS:

#game-nav li a {
    background: none repeat scroll 0 0 rgb(255, 255, 255);
    border: 1px solid rgb(217, 195, 169);
    color: rgb(34, 34, 34);
    display: inline-block;
    padding: 8px 12px 8px 8px;
    text-decoration: none;
    text-transform: uppercase;
}

    JavaScript:

        $(document).ready(function() {
        var data;
        function loadContent(){
            $.ajax({
                url: "json/content.json",
                data: "nocache=" + Math.random(),
                type: "GET",
                contentType: "application/json",
                dataType: "json",
                success: function(source){
                    data = source;
                    showInfo();
                },
                error: function(data){
                    alert("Failed to load content");
                }
            });

        }

        loadContent();
            function showInfo(){
                $(".text").html(data[lang]['startpage']['text']);
        }
       showInfo();
        });
</code>
Answer: problem is with your float:left property of li.game-nav
since its updated dynamically it canot adjust properly
try removing float:left from the list and add it to its div container
Comment: it appears to be fixed now? but using position:absolute isn't a good fix, browsers like IE tends screw it


Endomorphism exercise

Question: Problem: Let $V$ be a vector space over a field $F$ which is not finitely generated, and fix $\alpha\in End(V)$ which is not the 0-endomorphism. Consider the set $A=\{\beta\in End(V)\ |\ \alpha\circ \beta=id\}$. Show that if $A$ has more than one element, it is infinite.
I have posted a solution attempt in the answers.
Answer: This is actually a result that holds for rings: if an element has more than one right inverse, then it has infinitely many right inverses.
Suppose that there are at least two elements in $A$, so that $\alpha$ cannot have a left inverse. Let $\beta_1$ be any element of $A$. Consider the map $f\colon A\to A$ given by $f(\beta) =\beta\alpha - \mathrm{id} + \beta_1$.
Note that this is well-defined: the image of $\beta$ is an endomorphism of $V$ (composition and sum of linear transformations is linear), and
$$\alpha\Bigl(\beta\alpha - \mathrm{id} + \beta_1\Bigr) = \alpha\beta\alpha -\alpha + \alpha\beta_1 = \alpha - \alpha +\mathrm{id} = \mathrm{id}$$
so if $\beta$ is a right inverse for $\alpha$, then so is $f(\beta)$.
Next: $f$ is one-to-one: if $f(\beta)=f(\beta')$, then
$$\beta\alpha - \mathrm{id} + \beta_1 = \beta'\alpha - \mathrm{id} + \beta_1$$
which yields $\beta\alpha = \beta'\alpha$. Now composing with $\beta_1$ on the right we obtain $\beta=\beta'$, since $\alpha\beta_1=\mathrm{id}$.
Finally, $f$ is not onto: we can never get $\beta_1$ in the image. For if $f(\beta)=\beta_1$, then $\beta\alpha - \mathrm{id} + \beta_1 = \beta_1$, hence $\beta\alpha=\mathrm{id}$. But that would mean that $\beta$ is both a left and a right inverse for $\alpha$, which is impossible since $\alpha$ has at least two right inverses.
Thus, $f\colon A\to A$ is one-to-one and not onto, which proves that $A$ is infinite.
Comment: This is very nice.
Comment: @Arturo Seems like $\,\beta_2\,$ in the third line in your post is superfluous
Comment: @DonAntonio: Yes; it's only used implicitly in arguing that $\beta_1$ cannot be in the image.

Endomorphism exercise


Listas encadeadas em Java

Question: supondo que eu tenha uma lista encadeada Alunos, onde deve-se registrar nome e nota, entretanto este mesmo aluno pode conter mais de uma nota. Na minha lógica, ele apenas cadastra um aluno com uma única nota, como pode-se observar no código abaixo:
Classe responsável pelos Getters e Setters dos dados (o dado "numero" seria o identificados de cada aluno)
public class Lista {

    private String nome;
    private Lista prox;
    private int numero;
    private double nota;

    public double getNota() {
        return nota;
    }

    public void setNota(double nota) {
        this.nota = nota;
    }

    public int getNumero() {
        return numero;
    }

    public void setNumero(int numero) {
        this.numero = numero;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Lista getProx() {
        return prox;
    }

    public void setProx(Lista prox) {
        this.prox = prox;
    }

}

Classe responsável pelos métodos de adicionar e posteriormente outras funções
public class Aluno {

    Lista topo;
    Lista ultimo;
    int numero = 1;

    public String pilharAluno(String nome, double nota) {
        Lista novo = new Lista();
        novo.setNome(nome);
        novo.setNumero(this.numero);
        novo.setNota(nota);
        this.numero++;
        if (topo == null) {
            topo = novo;
            ultimo = novo;
            novo.setProx(null);
        } else {
            novo.setProx(topo);
            topo = novo;
        }
        return "Aluno cadastrado";
    }

}

Comment: Sugiro você usar C para trabalhar com estruturas de dados, pois teoricamente elas não são orientadas à objetos e sim à endereços de memória!
Comment: @DanLucioPrada você vai precisar criar uma nova classe exatamente com as mesmas funções que a classe Lista porém com atributos diferentes. Recomendo que utilize herança neste caso para não repetir código. caso este comentário não lhe ajude a entender, me responda que amanha elaboro uma resposta completa para você.
Comment: Já tentou conectar uma lista de notas em cada aluno?
Comment: @Patrick eu pensei nesta lógica, mas não consigo implementa-lá.
Comment: @DanLucioPrada, você precisa implementar a lista encadeada, é isto? Você não pode usar `LinkedList` do java? Não ficou claro para mim se você precisa apenas resolver o problema que descreveu ou que precisa, além disto, implementar a lista encadeada.
Comment: @Dherik preciso implementar uma lista encadeada para cadastro de alunos, o problema está no fato de que cada aluno pode conter mais de uma nota. (sem funções nativas do Java, tudo em forma de estruturas de dados escrita manualmente)
Answer: Use o bom senso, o aluno pode(e deve) ter X notas. Creio que seja um trabalho de estrutura de dados ou coisa do tipo, faça uma lista genérica, e depois especialize ela para o que você quer.
    public class Lista<T>{
        Class<T> obj;
        Lista<T> prox;
        int tamanho = 0;
        ...
        {Métodos que qualquer lista usaria: insere, retira, tamanho etc...}
        ...
    }

Isso é um esboço de uma lista com template em java, esse T é um tipo genérico que é definido em tempo de execução, a partir disso é só fazer herança para modificar o objeto lista à sua vontade.
No seu caso você teria uma lista de alunos que seria uma herança de Lista ex:
    public class ListaDeAlunos extends Lista<Aluno>{
        {Métodos que apenas uma lista de alunos possui(?)}
    }

Caso não exista métodos/funções especificas de uma lista de alunos, basta instanciar uma lista genérica para alunos
Lista<Aluno> alunos = new Lista<Alunos>();

O aluno seria um Objeto qualquer que você gostaria de "colecionar" e nele conteria uma outra herança de lista de notas(Double) que possuiria as funções/métodos específicos para uma lista de notas:
    public class ListaDeNotas extends Lista<Double>{
        {Métodos que apenas uma lista de notas possui: média, maior, menor...}

    }

Listas encadeadas em Java


What is this called in Taylor Swift's song "Style"?

Question: In Taylor Swift's song "Style", there's a part that I can't make sense of.
See here, where the lyrics go "We never go out of style, we never go out of style."
In those words, the rhythm of the vocals temporarily goes against the rhythm of the bass, with a dotted eighth note rhythm superimposed over the 4/4 bass.
What would this be classified as?
Answer: There are a few ways to describe what is happening here. The most general is syncopation, which is emphasizing the rhythmically weak beats of a measure. It sounds to me like Taylor Swift is singing a 3+3+2 pattern, with the last note sustained over the barline. This type of rhythmic pattern is ubiquitous in popular music. This essay calls it "The World's Most Famous Rhythm Structure" and goes into some of its origins. There appear to be different names to classify this rhythmic unit depending on which "world" musical tradition (e.g. African, Latin American, North Indian) one adheres to. I know of no definitive term for it with respect to the Western classical tradition, however. That said, I prefer how the author refers to it: as simply "332." To me this label provides the least amount ambiguity when discussing rhythm.
Edit: Removed my discussion of a flawed wikipedia article and replaced it with a different reference.
Comment: The wikipedia article is incorrect - it even contradicts its own definition of additive rhythm.  Additive rhythms are found most famously in Messiaen's talas - notably in his Quartet for the End of Time.
Comment: Rhythm is different from metre. Additive rhythm is different from additive metre. The pop song shows additive rhythm which is overlaid on four-square metre and goes against it, causing syncopation, but the passages in Messiaen jjmusicnotes referred to have additive rhythm which is overlaid on additive metre and accords with it, so there is no syncopation.
Answer: Never mind, I think I figured it out.
I listened to it again, this time at full volume with headphones on so I could hear the beats better. I found that although the second word in "out of style" certainly came before the second beat, the next word "style" also comes before the third beat by the same amount.
This makes me think that it's a regular 4/4 rhythm in the bass with the same on the top, except that they're offset by a sixteenth note each time. In other words, the words "out of style" are a dotted eighth note, quarter note, then a quarter note.
Which I guess the best way to label it as is a syncopation, as N1hk said, albeit not a 332 one.
Comment: I found that setting the YouTube video's speed to 0.5 helps make clear the rhythm she's singing in. The "out" falls on the first sixteenth, "of" on the fourth, and "style" on the sixth and seventh (the 's' of the word on the sixth, and 'tyle' on the seventh). The 'tyle' of "style" is the accented part of the word, however. Thus, when one notates the accented parts of the phrase "out of style," a dotted 8th + dotted 8th + 8th (tied to another 8th across the bar) emerges.  These accents articulate the 3+3+2 rhythm.
Comment: I agree, I heard this song yesterday and thought of this question and it was clear to me that she's singing a 3-3-2 pattern.


Mysql query optimization

Question: Have follow query:
  SELECT tbl_yaca_sites.`id_site` FROM `tbl_yaca_sites`
   INNER JOIN `tbl_relation` ON tbl_relation.id_website = tbl_yaca_sites.id_site
   INNER JOIN `tbl_yaca_directories` ON tbl_yaca_directories.id_record = tbl_relation.id_category
   INNER JOIN `tbl_applications` ON tbl_applications.id_site = tbl_yaca_sites.id_site
  where
  tbl_applications.id_application IN (41)
  and tbl_yaca_directories.type = 0
  AND tbl_yaca_directories.work = 1
  AND tbl_relation.work = 1  GROUP BY tbl_yaca_sites.`id_site`

There are many indexies:

tbl_yaca_sites - for primary id_site and another one id_site (the same field, but another index)
tbl_relation - for primary ID and combined index (id_site, id_category, work)
tbl_yaca_directories - for primary id_record and combined index 'type' (type, work)
tbl_applications - there are not primary. Has one index id_application.

The query works good when I setup described indexies only (but without 'group by'). I tested it many times.
So, if I run this query without group by it takes one second. Enough good result, where are about 200 000 records in each table. Added 'group by', always takes 16 seconds.
if I do follow operation:
SELECT id_site FROM (SELECT tbl_yaca_sites.`id_site` FROM `tbl_yaca_sites`
   INNER JOIN `tbl_relation` ON tbl_relation.id_website = tbl_yaca_sites.id_site
   INNER JOIN `tbl_yaca_directories` ON tbl_yaca_directories.id_record = tbl_relation.id_category
   INNER JOIN `tbl_applications` ON tbl_applications.id_site = tbl_yaca_sites.id_site
  where
  tbl_applications.id_application IN (41)
  and tbl_yaca_directories.type = 0
  AND tbl_yaca_directories.work = 1
  AND tbl_relation.work = 1 ) as tbl GROUP BY id_site

it takes 1,7 seconds.
This is explain query:
1, 'SIMPLE', 'tbl_yaca_sites', 'index', 'PRIMARY,id_site', 'PRIMARY', '4', '', 102358, 'Using index'
1, 'SIMPLE', 'tbl_applications', 'ref', 'pair', 'pair', '8', 'webservices.tbl_yaca_sites.id_site,const', 1, 'Using index'
1, 'SIMPLE', 'tbl_relation', 'ref', 'comb', 'comb', '4', 'webservices.tbl_yaca_sites.id_site', 1, 'Using where; Using index'
1, 'SIMPLE', 'tbl_yaca_directories', 'eq_ref', 'PRIMARY,type', 'PRIMARY', '4', 'webservices.tbl_relation.id_category', 1, 'Using where'

Also tried to add count(*) | count(id_site) | count(1). result the same.
Why so long? Could anybody tell me what I have missed up?
Thanks everybody in advance!
Answer: You might also try:
SELECT DISTINCT tbl_yaca_sites.`id_site`
FROM `tbl_yaca_sites`
INNER JOIN `tbl_relation` ON tbl_relation.id_website = tbl_yaca_sites.id_site
INNER JOIN `tbl_yaca_directories` ON tbl_yaca_directories.id_record = tbl_relation.id_category
INNER JOIN `tbl_applications` ON tbl_applications.id_site = tbl_yaca_sites.id_site
WHERE
     tbl_applications.id_application IN (41)
     AND tbl_yaca_directories.type = 0
     AND tbl_yaca_directories.work = 1
     AND tbl_relation.work = 1

Comment: Almost the same result.
5 seconds when I run it for the first time.
And 1,5 seconds - follow times.
But it is better than nested query:)
Comment: Generally, the first time you run the query, SQL will create the execution plan, which causes it to run a bit slower.  Every time you run it after that, it will use a cached execution plan... and that's going to be the general speed of the query (assuming you end up saving it as a stored procedure).

Is 1.5 seconds too slow, in this case?
Comment: to be honest, I don't know is it a good result? Thinking a good result is when a query takes less than one second, isn't it? Is it possible to save time for join queries up to one second?
Comment: To speed it up beyond that, it would probably require the addition of some indexes.  One way (that I often use) to figure out what exactly is causing the slow-down, is to start by commenting out all the various inner joins and where clauses, and then running the query... and measuring how long it takes.  Then, add each inner join and/or where clause back in one-at-a-time, and you should then be able to see which one is causing it to slow down.  That will give you a clue which index needs to be added or rebuilt (if that is, in fact, the issue).
Comment: I see. I did it for query without 'group by'. It worked perfect. After adding 'group by'. It takes time writ double.
Comment: @Jacob The execution plan made by the optimiser is done very quickly and is just a best guess at how to query the data. It has to be done v.quickly and just a best guess otherwise it could spend a second deciding how to run a query that takes a few milliseconds! The increased performance on subsequent queries are in this case likely to be due to indexes and data being lifted into the disk cache, key cache or buffer pool.
Answer: Given that you only want a unique list of id_site values, you might be able to just use an In clause:
Select id_site
From tbl_yaca_sites
Where id_site In    (
                    Select id_site
                    From tbl_yaca_sites
                        Join tbl_relation
                            On tbl_relation.id_website = tbl_yaca_sites.id_site
                        Join tbl_yaca_directories
                            On tbl_yaca_directories.id_record = tbl_relation.id_category
                        Join tbl_applications
                            On tbl_applications.id_site = tbl_yaca_sites.id_site
                    Where tbl_applications.id_application In(41)
                        And tbl_yaca_directories.type = 0
                        And tbl_yaca_directories.work = 1
                        And tbl_relation.work = 1
                    )

Comment: Thank you for your answer.
The query takes 26 seconds:(

Mysql query optimization


Cannot get relation in Laravel pivot tables

Question: I want to build relations between three tables in laravel. Currently i have three models
Classroom,
public function subjects(){
return $this->belongstoMany('Subject','subject_section_classroom');
}

Section,
Subject
My Tables are
classrooms(id, name)
sections(id, name)
subjects(id, name)
subject_section_classroom( id, classroom_id, section_id, subject_id)

In my classroomsController I have
public function assignsubjects($class_id, $section_id){
        $classroom = Classroom::find($class_id);
        $section = Section::find($section_id);
        $subjects = Subject::lists('name','id');
        $selected_subjects = $classroom->subjects()->where('section_id', '=', 1);
        $subjects = Subject::lists('name','id');
        return view('assignedit', compact('classroom','section','subjects', 'selected_subjects'));
}

But I can't get the selected_subjects from above relation. And when I tried to get the sql of the above query (with ->toSQL()), I get
`"select * from `myschool_subjects` inner join `myschool_subject_section_classroom` on `myschool_subjects`.`id` = `myschool_subject_section_classroom`.`subject_id` where `myschool_subject_section_classroom`.`classroom_id` = ? and `section_id` = ?"`

I can't figure what I am doing wrong here.
Please Help.
Comment: I know Laravel 4 did not support triple table pivots, hence e.g. this package (https://github.com/jarektkaczyk/Eloquent-triple-pivot) by @jarektkaczyk was created. Not sure if something similar exists for Laravel 5.
Comment: I think, that your tables structure is a little bit wrong. Can you give me some examples of sections and subjects from your tables, so I would better understand your logic.
Comment: actually i want to output all subjects of a classroom with its section. simple i wanted the classroom subjects from pivot table where section is as defined ;)
Answer: I think your problem is coming from
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1);

Change it to:
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1)->get();


Prove that $ \lim_{n \to \infty}\int_0^{n^2} n\sin (x/n)e^{-x^2} dx = 1/2 $

Question:
Prove that
  $$ \lim_{n \to \infty}\int_0^{n^2} n\sin(x/n)e^{-x^2} dx = 1/2.$$

I've tried all of the techniques learned in the course so far and none of them seem to work, so if anyone could help me with this it would be much appreciated. Thanks!
Comment: Do you understand intuitively why it is true/how to practically get the answer? Can you name some of the techniques of your course, that you have tried?
Comment: You can take the limit under the integral and take the upper bound of the integral as $\infty$ right away, then you get an elementary integral returning the correct value
Comment: @stijn We've learned how to solve problems like this with integration by parts, using the power series, and differentiating under the integral sign. We haven't covered an example where the thing we're taking the limit of is in the limit of the integral though.
Comment: @Ellie_P so some people below answered in some detail already, and more properly than I will. I was asking for clarification partly because it is good practice to give a bit of background (on what you've tried) and partly because the level of rigor expected when "proving" something differs a lot between courses. Your case sounds not too formal. The main point is $\sin(y) \sim y$ as $y\rightarrow0$, so $n \sin{x/n} \rightarrow x$. You might worry whether this is ok to do inside the integral (it is here, see answers), once you do this the integral becomes something simple to evaluate.
Answer: Hint. You may need to show:
\begin{align}
|\sin(x/n) |\leq \frac{|x|} {n}
\end{align}
So now one has
\begin{align}
0\leq n|\sin(x/n) |e^{-x^2}\leq |x|e^{-x^2}
\end{align}
Your integral is:
\begin{align}
\int^\infty_0 \mathbf{1}_{(0,n^2)}n\sin(x/n)e^{-x^2}\,dx
\end{align}
Now apply The Dominated Convergence Theorem to conclude.


Estimate of $\text{Var}(\hat\beta)$ in a linear mixed model

Question: Let $Y = X\beta + Zu + \sigma\epsilon$ be a Gaussian linear mixed model.
Let $V = Var(Y)$ be the marginal variance matrix of $Y$. Define the matrix
$$
\Phi = {(X'V^{-1}X)}^{-1}.
$$
According to this SAS documentation, $\Phi$ underestimates $\text{Var}(\hat\beta)$.
I've checked by simulations, and I don't find this result:
library(lme4)

# simulates a mixed 2-way ANOVA model ####
SimAV2mixed <- function(I, J, Kij, mu=0, alphai, sigmaO=1,
                        sigmaPO=1, sigmaE=1, factor.names=c("Part","Operator"),
                        resp.name="y", keep.intermediate=FALSE){
  Operator <- rep(1:J, each=I)
  Oj <- rep(rnorm(J, 0, sigmaO), each=I)
  Part <- rep(1:I, times=J)
  Pi <- rep(alphai, times=J)
  POij <- rnorm(I*J, 0, sigmaPO)
  simdata0 <- data.frame(Part, Operator, Pi, Oj, POij)
  simdata0$Operator <- factor(simdata0$Operator)
  levels(simdata0$Operator) <-
    sprintf(paste0("%0", floor(log10(J))+1, "d"), 1:J)
  simdata0$Part <- factor(simdata0$Part)
  levels(simdata0$Part) <- sprintf(paste0("%0", floor(log10(I))+1, "d"), 1:I)
  simdata <-
    as.data.frame(
      sapply(simdata0, function(v) rep(v, times=Kij), simplify=FALSE))
  Eijk <- rnorm(sum(Kij), 0, sigmaE)
  simdata <- cbind(simdata, Eijk)
  simdata[[resp.name]] <- mu + with(simdata, Oj+Pi+POij+Eijk)
  levels(simdata[,1]) <- paste0("A", levels(simdata[,1]))
  levels(simdata[,2]) <- paste0("B", levels(simdata[,2]))
  names(simdata)[1:2] <- factor.names
  if(!keep.intermediate) simdata <- simdata[,c(factor.names,resp.name)]
  simdata
}

# marginal variance matrix V of y ####
Vfun <- function(vcs, sigma2, reTrms){ # vcs = variance components / sigma2
  G <- Diagonal(x = rep(vcs, times = diff(reTrms$Gp)))
  Zt <- reTrms$Zt
  H <- Diagonal(ncol(Zt)) + t(Zt) %*% G %*% Zt
  sigma2 * H
}

# calculate the Phi matrix ####
Kij <- c(3, 3, 3, 4, 4, 4)
dat <-
  SimAV2mixed(I=2, J=3, Kij = Kij, mu = 0, alphai = c(3,-3),
              sigmaO = 3, sigmaPO = 2)
reTrms <-
  lFormula(y ~ Part + (1|Operator) + (1|Operator:Part), data = dat)$reTrms
V <- Vfun(vcs = c(4,9), sigma2 = 1, reTrms)
Vinv <- chol2inv(chol(V))
X <- model.matrix(~ Part, data = dat)
( Phi <- solve(t(X) %*% Vinv %*% X) )
#           [,1]      [,2]
# [1,]  4.435113 -1.435089
# [2,] -1.435089  2.860920

# simulations ####
set.seed(666)
nsims <- 1000L
betahat <- matrix(NA_real_, nrow = nsims, ncol = 2L)
k <- 0L
while(k < nsims){
  dat <-
    SimAV2mixed(I=2, J=3, Kij = Kij, mu = 0, alphai = c(3,-3),
                sigmaO = 3, sigmaPO = 2)
  fit <-
    suppressMessages(
      lmer(y ~ Part + (1|Operator) + (1|Operator:Part), data = dat,
           start = setNames(c(2,3), c("Operator:Part", "Operator")),
           control = lmerControl(optimizer = "Nelder_Mead",
                                 optCtrl=list(maxfun=100000)),
           REML = TRUE)
    )
  if(!is.null(fit@optinfo$conv$lme4$code)){ # skip if non-convergence
    print(k)
    next
  }
  k <- k + 1L
  betahat[k,] <- fit@beta
}

cov(betahat)
#           [,1]      [,2]
# [1,]  4.194572 -1.332589
# [2,] -1.332589  3.011642
Phi
#           [,1]      [,2]
# [1,]  4.435113 -1.435089
# [2,] -1.435089  2.860920

As we can see, $\Phi_{1,1}$ is higher than $\text{Var}(\hat\beta)_{1,1}$.
Am I doing something wrong, or am I misunderstanding something?
Comment: Need to understand the difference between the parameters (or function of the parameters) and estimators of them. $\Phi$ and $\text{Var}(\hat\beta)$ are functions of parameters.
Comment: @user158565 I think I totally understand that. According to the SAS documentation I linked, $\Phi$ (the "true" $\Phi$, which is not a random variable) underestimates $\text{Var}(\hat\beta)$. What is wrong with my simulations ?
Comment: I withdraw from it.
Answer: The point in that the estimator for the marginal covariance matrix of $Y$, i.e., $\hat \Phi = {(X' \hat V^{-1}X)}^{-1}$ will be a biased estimator of $\Phi = {(X'V^{-1}X)}^{-1}$. If I see correctly in your simulation, you compare $\Phi$ with the empirically determined variance of $\hat \beta$, not $\hat \Phi$.
Nonetheless, this bias is not that great. Check also my version below (in the first simulation I use 30 subjects in which case you would expect more bias in the estimation of $\Phi$ than with 200 subjects):
simfun <- function (n = 100, K = 3) {
    # 'n' number of subjects
    # 'K' number of measurements per subject
    t_max <- 15 # maximum follow-up time

    # we constuct a data frame with the design:
    # everyone has a baseline measurment, and then measurements at random follow-up times
    DF <- data.frame(id = rep(seq_len(n), each = K),
                     time = c(replicate(n, c(0, sort(runif(K - 1, 0, t_max))))),
                     sex = rep(gl(2, n/2, labels = c("male", "female")), each = K))

    # design matrices for the fixed and random effects
    X <- model.matrix(~ sex + time, data = DF)
    Z <- model.matrix(~ time, data = DF)

    betas <- c(-2.13, 1, 0.9) # fixed effects coefficients
    D11 <- 4 # variance of random intercepts
    D22 <- 1 # variance of random slopes

    # we simulate random effects
    b <- cbind(rnorm(n, sd = sqrt(D11)), rnorm(n, sd = sqrt(D22)))
    # linear predictor
    eta_y <- drop(X %*% betas + rowSums(Z * b[DF$id, ]))
    # we simulate normal longitudinal data
    DF$y <- rnorm(n * K, eta_y, sd = 1)
    DF
}

library("lme4")

M <- 1000
betas <- var_betas <- matrix(NA_real_, M, 3)
for (m in seq_len(M)) {
    DF_m <- simfun(n = 30)
    fm_m <- suppressWarnings(lmer(y ~ sex + time + (time | id), data = DF_m))
    betas[m, ] <- fixef(fm_m)
    var_betas[m, ] <- diag(vcov(fm_m))
}

diag(var(betas))
colMeans(var_betas)

#########

M <- 1000
betas <- var_betas <- matrix(NA_real_, M, 3)
for (m in seq_len(M)) {
    DF_m <- simfun(n = 200)
    fm_m <- suppressWarnings(lmer(y ~ sex + time + (time | id), data = DF_m))
    betas[m, ] <- fixef(fm_m)
    var_betas[m, ] <- diag(vcov(fm_m))
}

diag(var(betas))
colMeans(var_betas)

Comment: Thanks, interesting answer (+1). But this is not what I meant. The SAS documentation I linked claims: *"even $\Phi$ (not $\hat\Phi$) underestimates $\text{Var}(\hat\beta)$ when $\sigma$ is unknown"*. This is the claim I want to check. Maybe I misunderstand it?
Comment: @StephaneLaurent It is not evident to me how you could validate this statement because if $V$ is unknown you cannot calculate $\Phi$. As far as I can see, in your simulation you calculate $\Phi$ with known $V$ and you compare it with $\mbox{var}(\hat \beta)$.


What is a non-hazardous method to remove the letters from keyboard keys without introducing a non-smooth texture?

Question: I need to remove the letters and numbers from the keys on a number of keyboards. This needs to be done in a non-hazardous fashion without introduction extra physical textures on the keys.
The keys are standard plastic keys on Microsoft keyboards.
Comment: You're probably just going to have to experiment with a number of solvents until you find one that works. Once the job is done, a wash in soapy water should remove the solvent. I would try things like Goo Gone, fingernail polish remover (both with and without acetone), lighter fluid and WD-40. Plan on sacrificing several key caps to the  point of needing replacement until you find a solution (no pun intended). I have to say, this is a very unusual request.
Comment: @Farseeker: n00b! That's "l337". ;-) If you want *real* l337 and have the US$1600 or so to spare, the Optimus Maximus is the must-have.
Comment: Can you elaborate on what you mean by non-hazardous?
Comment: I can't use any chemicals that will cause health problems or finger irritation after letter/number removal
Comment: @Dennis, I've seen this done for touch-typing tests. That's about the only situation I've seen where this would be desirable though apart from being incredibly leet (referring to your answer below).. sorry l33t...
Answer:
(source: daskeyboard.com)
Das Keyboard Ultimate - no key inscriptions
Comment: Warning: $129 may be hazardous.
Answer: This site also sells blank keyboards (and in 90's web style!) for ~$50.  They also sell blank key overlays, so maybe you could just cover over the keys instead of removing the ink?


Probability of all girls being in same group?

Question: There are 10 kids, consisting of 4 girls and 6 boys. The 10 kids are assigned to two different groups of equal size.
What is the probability that all girls are in the same group?
To try to solve this problem, I used the binomial distribution.
$${{n}\choose{x}} \cdot p^xq^{n-x}$$
I thought $P(x=4)$ for this problem, so I calculated it as
$${{5}\choose{4}} \cdot {\frac{4}{10}}^x{}\frac{6}{10}^{n-x}$$
I proceeded to multiply this by 2 because there are 2 groups, and thus 2 possibilities of this happening, but I do not think this is the correct approach. Could someone please guide in me the right direction?
Comment: Use the hypergeometric distribution instead.
Answer: Just to put you in the right direction, you need to be using the hypergeometric distribution in this case, instead of the binomial, as you're sampling without replacement.
As an analogy to your problem, assume you have a bowl with 4 white balls and 6 black balls. From it you want to take out 5 balls without putting any back (without replacement). The events you're looking for are:

taking out exactly 4 white balls and 1 black ball;
taking out 5 black balls (which means that 4 white balls and 1 black ball remain in the bowl).
Answer: You can surely use the hyper geometric distribution here to get the desired result, however, in this specific question you can approach it in a more intuitive way.
Part 1: regardless of the number of boys and girls in the group, in how many ways can you form a group of 5 kids? Answer: 10c5 = 252
Part 2: in how many ways you can form a group of 4 girls + 1 boy? Answer: 6 (because there are 6 boys and all 4 girls must be on the team)
Solution:  6/252 = 0.023
As initially mentioned, you can also use the hyper geometric distribution and you'll have the same result:
$$\frac{{{4}\choose{4}} * {{6}\choose{1}}}{{10}\choose{5}}$$
Answer: Alternatively, all girls being in the same group implies all boys are in the same group. Hence:
$$P(\text{all girls})=P(\text{all boys})=P(B_1\cap B_2\cap B_3\cap B_4\cap B_5)=\\
P(B_1)\cdot P(B_2|B_1)\cdot P(B_3|B_1\cap B_2)\cdot P(B_4|B_1\cap B_2\cap B_3)\cdot P(B_5|B_1\cap B_2\cap B_3\cap B_4)=\\
\frac{6}{10}\cdot \frac{5}{9}\cdot \frac{4}{8}\cdot\frac{3}{7}\cdot\frac{2}{6}=\frac{1}{42}\approx 0.0238.$$


How to count date difference excluding weekend and holidays in Computed Field

Question: How to count date difference excluding weekend and holidays?
I should count the number of days between two dates but the weekends and holidays must be excluded from the counting. I used Computed Field.
<code>$start_date_value = array_pop(field_get_items($entity_type, $entity, 'field_date_from'));

$end_date_value = array_pop(field_get_items($entity_type, $entity, 'field_date_to'));

$start_date = new DateObject($start_date_value['value'], '');

$end_date = new DateObject($end_date_value['value'], '');

$entity_field[0]['value'] =$start_date->difference($end_date, 'days');
</code>
Here is my working code for counting the days.
Answer: why would you try something like this,
create a variable array that contain all the Hollidays
<code>$currentyear=the current year;
$holiday['01-01-'.$currentyear,other holiday,other holiday];

$result=$start_date->difference($end_date, 'days');
for(ctr=0;ctr=sizeof(holiday);ctr++;)
{
    if(holiday[ctr]>=start_date && holiday[ctr]<=end_date)
    temp++;

}
$result -= temp;
</code>
Comment: Thanks @junnel. I'll try it.

But the code is for holidays only. Can you also help me to exclude the weekends in the counting?
Comment: by that i woudl now suggest to create first a function to count the weekdays base on your from_date to end_date befor you go to holliday exclusion
Answer: I think you'll find this answer helpful, though it's PHP only:
https://stackoverflow.com/questions/336127/calculate-business-days/19221403#19221403
So you should only need to input your <code>$start_date/$end_date</code> values in correct format and then also define the holidays.


SAS and Principal Components Analysis

Question: I'm new to SAS coding from SPSS point and click. I don't currently have SPSS, so SAS is my only option.
My question is: how do I get the percent variance explained and cumulative variance explained following varimax rotation?? I get the total that I would get under
'Rotation Sums of Square Loadings' but not the % variance or cumulative %.
Example SAS code below:
<code>PROC FACTOR DATA=survey
METHOD=PRIN
PRIORS=ONE
NFACT=2
MINEIGEN=1
SCREE
ROTATE=VARIMAX
FLAG=.32
OUT=ex4comp4;
VAR pn1 pn2 pn3 pn4 pn5 pn6 pn7 pn8 pn9 pn10 pn11 pn12 pn13 pn14 pn15 pn16 pn17 pn18 pn19 pn20;
RUN;
</code>
Essentially I want to know what % variance each factor explains but all I get is the Total.
So frustrated and confused!
Thank you in advance for any suggestions or solutions
KWAK
Comment: I can't check right now (with SPSS but no SAS now, ironically), but the percentages you want come as default (e.g. [1](http://support.sas.com/documentation/cdl/en/statug/63347/HTML/default/viewer.htm#statug_factor_sect004.htm), [2](http://www.yorku.ca/pek/index_files/quickstart/FactorQuickStart.pdf)). My guess is your nfact and mineigen statements might have suppressed them. Start from a simpler command and see if that's true.
Comment: How do you get from 'I don't have SPSS' to 'SAS is my only option'?
Comment: Hi Glen, what I meant is that I have SAS on my computer right now and I am trying to do the work right now. Thanks.
Comment: I typed my answer while you were typing your comment. :-). One further note, I think the MINEIGEN and NFACTORS statements are sort of either/or, NFACTORS insists on 2 factors while MINEIGEN says keep only those with eigenvalue over 1.
Comment: Hmm, even with the following basic code i still don't get what I'm looking for.  PROC FACTOR DATA=survey
NFACT=2
ROTATE=VARIMAX;
VAR pn1 pn2 pn3 pn4 pn5 pn6 pn7 pn8 pn9 pn10 pn11 pn12 pn13 pn14 pn15 pn16 pn17 pn18 pn19 pn20;
RUN;
Answer: It is part of the default output; see the table called "Eigenvalues of the correlation matrix" and look in the two columns on the right.
EDIT with additional info:
A bit of googling found this article which shows how to get this by using PROC PRINCOMP.
Comment: Thank you Peter - that's what I was expecting from my results, but I don't seem to get that output. I must be missing something obvious here. When I reduce the number of factors to 2 and run the varimax rotation I receive the initial (non-rotated) table with eigenvalues and the two columns on the right. However, I do not received a second similar table following the rotated solution. My output shows the correct total (e.g. 4.886) but not the % var or cumulative %. (Correct is known because I am trying to replicate some SPSS results done previously)
Comment: Hang on! I can't figure out how to get it to come up, BUT am i correct in saying that if my total after rotation is 4.886 and I have 20 items then my percent variance is 4.886/20*100!!!
Comment: My apologies Peter- the total variance remains the same but the % variance explained by each factor may change. Now I understand how to calculate it, I have to go and figure out why so I understand it properly. Thank you for your time and efforts!

SAS and Principal Components Analysis


Metronome markings vs. tempo markings (BPM vs. words)

Question:

The images are starting part of two different songs in Guitar Pro 6. My question is about the things that I circled in red.
I get that they indicate bpm. But what does the word Moderate mean there? Why the other song doesn't have the word Moderate?
Answer: Moderate or Moderato is a convention from back before the invention and widespread use of the quartz-powered metronome. Tempo markings are a relatively recent invention, and they are used for their simplicity and accuracy. However, many composers choose to omit them because the "idea" of the tempo of the piece is more important than an absolute value.
Other uses will indicate a range of metronome markings (BPM), or add a word like "Moderato" to give the player an idea of the "flavor", or style of the piece of music. In this case, (and in my opinion), Moderate indicates "Don't go nuts with the tempo!" here, since the classical tempo equivalences tend to put "moderato" around q=110, and q=158 to be somewhere in the zone of vivace, presto, or allegro vivace.
Answer: The word Moderate indicates the name for the tempo; each tempo has a different name. Here is a list of the names:
adagio:         very slow.
allegretto:     fairly quick, slightly slower than allegro.
allegro:        lively, rather quick.
andante:        rather slow, at a moderate, walking pace.
andantino:      this used to mean a little slower than andante, but now it usually means a little faster than andante.
con moto:       with movement, or a certain quickness.
grave:          extremely slow and solemn.
largamente:     broadly.
larghetto:      less slow than largo.
largo:          slow and broad.
lentamente:     slowly.
lento:          slow.
moderato:       moderate pace.
prestissimo:    as quick as possible.
presto:         very quick.
rapido:         rapid.
veloce:         with velocity.
vivace:         quick and lively.
As you can see, Moderate (in Italian Moderato) means that the speed of the song is a moderate pace
Comment: Is there a need for the colons? I don't know, they just bother me.
Answer: It's actually pretty pointless putting 'moderato' there, as a proper tempo is written. This gives exactly the speed of the piece, in beats per minute, each beat being shown as a crotchet.Back in the Classical days, composers would put the Italian words, which gave a rough to fairly good idea as to the pace of the piece.
Nowadays, it's more usual to put the actual tempo, in b.p.m and indicate what constitutes 'a beat'.
If 158bpm is 'moderato', then 81 bpm will be nearly half that speed, given that each uses a crotchet as the 'beat'.By the way, the number of beats in each bar will have no bearing on the speed the piece gets played.
On one metronome I have, 'moderato' is 108 to 120 bpm, so why that's marked as such on guitarpro, I don't know.
Comment: I don't think that's part of Guitarpro's code, at least not this example -- it's probably just text provided by whoever created the Guitarpro file.
Comment: @NReilingh If it's just text, why would it change to the bpm I set by selecting `t=158` from the `Sound` menu of the software.
Comment: @AmarDuplantier I don't know the software, but I'm not sure what you mean either. Does the text vary based on the BPM that you set?
Comment: @NReilingh Yes, the text vary when I set the BPM from the menu.
Comment: This is a option of Guitar Pro, you can choose to display the "speed name" or not with the tempo. I'm not sure where you set that though, maybe in the stylesheet (F7). I though you would set this name manually but as you noticed, it seems that GP does it automatically.