How to display (automatically in a field) all media that references this node?

Question: I have a content type, "Fruit". Using that content type I have created a "Bananas" node. It contains text and link fields that constitute "banana information".
I have media type, "Fruit Image", with a field, "FruitShown". Using that media type I have numerous images of bananas and other fruit.
On my Fruit pages, how can I display automatically in a field all images of bananas (i.e. All images of media type "Fruit Image" that have "bananas" in the "FruitShown" field)?
CONTEXT:
I believe I am able to display the banana images in a block using a View with a contextual filter. However I prefer to display the images in a field so that I can wrap the images around a "banana information" CSS float, not just place them in a separate rectangular block (which leaves empty space in my theme).
WHAT I TRIED:
I am able to display the banana images in a field by using an entity reference field with an entity reference view reference method, but when adding the "Bananas" node, the images must be selected manually one-by-one. I prefer all of them to display automatically.
Answer: Use the Views Reference Field module
When you've created your view, go to your node strcuture and create a field type using the module above. On node edit you then can select your banana view. This way your view is wrapped inside the same markup just like any other field of your node.
Comment: Thank you but in my experience so far, that has the drawback described in the last paragraph of my question. i.e. The images must be selected manually one-by-one, whereas I want them all to display without having to select them.
Comment: There is no difference between a view in a field, or a view in a block: If you can create a fitting contextual filter (and you stated you can do that), it will work in a field as well as in a block. I've to admit though that I don't understand why you have chosen nodes as data structure for your fruits... I would have chosen taxonomy terms as data structure for fruit types.
Comment: I found some drawbacks to using taxonomy, as described in my comment of Dec 6 at 14:58 on the 1st answer on [this question](https://drupal.stackexchange.com/questions/251633/on-a-content-page-that-references-a-taxonomy-term-how-can-i-display-only-conten). However I may still end up doing that. Regarding the question on this page I'm very sorry, I completely overlooked the 1st line of your answer when I read it earlier!! I will try the Views Reference Field module tomorrow. Thank you.
Comment: Your solution, View Reference Field, did work, however I think much more detail would assist others. Should I write another longer answer or accept yours and edit it?
Comment: Just do whatever helps other people the most :-)


Do isomorphisms of quotients give isomorphisms of groups?

Question: I have a group isomorphism $G/\mathbb{Z}\to \mathbb{Z}^{(*n)}$, can I conclude from this fact
that $G$ is isomorphic to $\mathbb{Z}^{(*(n+1))}$, the free product of (n+1) copies of $\mathbb{Z}$.
Comment: I'm not convinced that for $n+1\ge2$ that $\Bbb Z^{*(n+1)}$ has a normal subgroup isomorphic to $\Bbb Z$.
Answer: No, since perhaps $G$ is $\Bbb Z\times\Bbb Z^{(*n)}$.


Equivalent of hosts file in proper DNS server in Windows Server 2008R2

Question: In my hosts file %systemroot%\System32\drivers\etc\hosts I can have entries portfolio.local 192.168.4.175
Is it possible to have idrac.example.com point to an internal ip but have it  on the server 2008 r2 box doing our routing so it's network wide
Answer: Yes with a DNS server.
You create a DNS A record pointing to the correct IP, and its done network wide.


Foosball five-man wall bounce rule

Question: I've been playing foosball for a while now, but mostly in college and at friend's houses. Just recently I watched some friends playing in a state tournament, and there were some really funky rules about bouncing the foosball around with the five bar.
I remember them saying something like you can only bounce it off the wall twice, and on the second time you have to advance it? What happens if you accidentally don't? And what if the ball is stuck on the wall?
Answer: This is called a Three Wall Violation.
To understand this rule, you need to understand the Passing rule.  The International Table Soccer Federation Rule Book covers passing in Rule 23:

23.1 A ball which is advanced from a pinned or stopped position on the five-man rod cannot be directly caught on the three-man rod of the same team regardless of whether or not the ball is touched by the opposing five-rod. The ball must touch at least two player figures prior to advancing to legally be caught on the three-man rod. A pinned ball is one that is pinned to the wall or playfield.

Basically, this means that you cannot pin (stop) the ball at your five-man rod, then pass it to your three-man rod.
To get around this, if you have the ball stopped on your five-rod, you can either pass the ball back to your defense, or you can bounce the ball off the wall before advancing it.  However, you can't keep bouncing the ball off the wall over and over.  Rule 23.2 covers this:

23.2 A player cannot make the ball strike the side walls of the table (or the side strips if present) more than twice before passing or shooting from the five-man rod. Regardless of which wall the ball touches, a total of two times is all that is allowed prior to advancing the ball. If the ball goes to the wall a third time, it may not be struck again by any player figure on the passing rod.

You get two bounces.  The third consecutive time the ball goes from your five-rod to the wall (or side strips), you are not allowed to touch the ball with your five-rod again until it hits another man first.
The penalty for a Three Wall Violation is a loss of ball.  The other team gets to serve the ball from their five-man rod.

Foosball five-man wall bounce rule


F3 caching issue

Question: Recently, I got error

Warning: require_once(account_header.php): failed to open stream: No
  such file or directory in
  /home/contestium/dev/temp/dev.contestium.com.tpl.0oyr4na on line 1
  Fatal error: require_once(): Failed opening required
  'account_header.php' (include_path='.:/usr/share/pear:/usr/share/php')
  in /home/contestium/dev/temp/dev.contestium.com.tpl.0oyr4na on line 1

I have disabled caching with
<code>F3::set('CACHE',FALSE);
</code>
But it was not helpful for me. Any help will be appreciated. Thank you!
Answer: When using cached files, your relative path won't work, as the cached files are not in the original file's directory.
You'll either need to provide the full path to 'account_header.php', or add the path to the directory containing such to your include path. This can either be done in your php.ini file, or at [runtime][1].
It looks like the cached files are still being used, right? If you delete those files, will it fetch the original file (and not the cached files)?

F3 caching issue


How do I bulk delete taxonomy terms?

Question: I'm looking for a way to delete about 1300 taxonomy terms (of 5250 in total) and their association with nodes.
I firstly thought to delete the content of these tables:

taxonomy_index
taxonomy_term_data
taxonomy_ter_field_data
taxonomy_term_hierarchy
node__field_tags
node_revision__field_tag

Is this sufficient?
Is there a better way to do it, without Drush, which I cannot install?
EDIT :
I'm trying to do it programmaticaly, but I have an error
Error: Call to undefined function field_attach_delete() in delete_taxonomy_terms() (line 42 of /var/www/html/d8/delete_tags.php).

Trying to add call to module_load_include() but still get the same error.
I put the file at the root of my Drupal installation (../mydrupal/delete_tags.php).
<?php
error_reporting(E_ALL);
date_default_timezone_set('Europe/Paris');

define('DRUPAL_DIR', $_SERVER["DOCUMENT_ROOT"]); //__DIR__ ); //.'/../drupal');

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';
$kernel = new DrupalKernel('prod', $autoloader);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

/**
 * Deletes taxonomy terms.
 *
 * @param array $tids
 *   Array of taxonomy term IDs.
 */

$tids = [830];

delete_taxonomy_terms($tids);

function delete_taxonomy_terms($tids) {

module_load_include("inc", "field", "field.attach");

  db_delete('taxonomy_term_data')
    ->condition('tid', $tids, 'IN')
    ->execute();
  db_delete('taxonomy_term_hierarchy')
    ->condition('tid', $tids, 'IN')
    ->execute();

  $terms = taxonomy_term_load_multiple($tids);

  foreach ($terms as $term) {
    field_attach_delete('taxonomy_term', $term);
    module_invoke_all('taxonomy_term_delete', $term);
    module_invoke_all('entity_delete', $term, 'taxonomy_term');
  }

  // Reset static cache after all terms deleted.
  taxonomy_terms_static_reset();
}

Comment: you got some advance?
Comment: do yo need to clean the vocabulary or delete some ids?
Comment: you're trying to execute Drupal 7 code in Drupal 8. field_attach_delete() is a Drupal 7 function and you want Drupal 8. See my answer, I tested the code and it works.
Comment: yay, sorry i wasnt aware you were trying to use D8. Please see @AdrianCidAlmaguer post.
Comment: @tenken in my fist post I write Drupal 7 code too, and after I see that is for Drupal 8, so I edit the answer.
Comment: @AdrianCidAlmaguer What's difference between clean the vocabulary and delete some ids ?
Comment: With the clean you can change if you want some ids to others. But if you don't want change ids and only delete all the terms and lost all the references, you don't need this part, and use only the `taxonomy_vocabulary_clean()` function.
Comment: Ok, yes I just want to delete terms and references. Why use names and not directly tid in `taxonomy_vocabulary_clean()` ?
Comment: If you want to delete all the terms in a vocabulary you only need the vocabulary name, if you need to delete terms from different vocabularies then you need all the terms ids and in this case you need to  modify a little my function.
Answer: Before you clean the vocabulary you need to change the taxonomy reference field, to do this you can use this code:
$nids = \Drupal::entityQuery('node')->condition('type','YOUR_CONTENT_TYPE')->execute();
$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

foreach($nodes as $node) {
  // Change your term here
  $node->field_YOUR_TAXONOMY_REFERENCE_FIELD->value = '';
 $node->save();
}

To clean the vocabulary use this modification of a drush command that you can see in https://github.com/adrian-cid/drush_commands/blob/master/drush_taxonomy.drush.inc
You need to pass an array of vocabularies names to clean.
I use the dpm() function (you need to install Devel) to show the messages, but you can change it if you want.
function taxonomy_vocabulary_clean(array $names) {
  if (!empty($names)) {
    // Check for duplicate ids.
    $test_names = array_unique($names);
    if (count($test_names) != count($names)) {
      dpm('You have duplicate vocabulary names.');
      return;
    }
    //Searching the vocabularies in the site
    $vocabulary_in_db = array_keys(Drupal\taxonomy\Entity\Vocabulary::loadMultiple());
    $vocabulary_non_existent = array_diff($names, $vocabulary_in_db);
    $vocabulary_existent = array_diff($names, $vocabulary_non_existent);

    if (count($vocabulary_existent) == 0) {
      dpm("The desired vocabulary to clean doesn't exists.");
      return;
    }
    if (count($vocabulary_non_existent)) {
      dpm('Non-existent vocabulary:');
      dpm(implode(' ', $vocabulary_non_existent));
    }

    foreach ($vocabulary_existent as $name) {
      $tids = \Drupal::entityQuery('taxonomy_term')
        ->condition('vid', $name)
        ->execute();

      $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
      $entities = $controller->loadMultiple($tids);
      $controller->delete($entities);
    }
    dpm('Vocabulary cleaned:');
    dpm(implode(' ', $vocabulary_existent));
  }
  else {
    dpm('You must enter at least one vocabulary name.');
  }
}

Using the function:
taxonomy_vocabulary_clean(['tags', 'my_vocabulary_machine_name']);

The Drupal 7 code:
function taxonomy_vocabulary_clean(array $names) {
  if (!empty($names)) {
    // Check for duplicate ids.
    $test_names = array_unique($names);
    if (count($test_names) != count($names)) {
      dpm('You have duplicate vocabulary names.'));
      return;
    }
    //Searching the vocabularies in the site
    $vocabulary_in_db = array_column(taxonomy_get_vocabularies(), 'machine_name');
    $vocabulary_non_existent = array_diff($names, $vocabulary_in_db);
    $vocabulary_existent = array_diff($names, $vocabulary_non_existent);

    if(count($vocabulary_existent) == 0) {
      dpm("The desired vocabulary to clean doesn't exists.");
      return;
    }
    if(count($vocabulary_non_existent)) {
      dpm('Non-existent vocabulary:');
      dpm(implode(' ', $vocabulary_non_existent));
    }

    foreach ($vocabulary_existent as $name) {
      $vid = taxonomy_vocabulary_machine_name_load($name)->vid;
      foreach(taxonomy_get_tree($vid) as $term) {
        taxonomy_term_delete($term->tid);
      }
    }
    dpm('Vocabulary cleaned:');
    dpm(implode(' ', $vocabulary_existent));
  }
  else {
    dpm('You must enter at least one vocabulary name.');
  }
}

Answer: You can write a custom function let's say on some form submit and do something like this:
/**
 * Deletes taxonomy terms.
 *
 * @param array $tids
 *   Array of taxonomy term IDs.
 */
function delete_taxonomy_terms($tids) {
 // Required to use field_attach_delete. - @tenken
 module_load_include("inc", "field", "field.attach");

  db_delete('taxonomy_term_data')
    ->condition('tid', $tids, 'IN')
    ->execute();
  db_delete('taxonomy_term_hierarchy')
    ->condition('tid', $tids, 'IN')
    ->execute();

  $terms = taxonomy_term_load_multiple($tids);

  foreach ($terms as $term) {
    field_attach_delete('taxonomy_term', $term);
    module_invoke_all('taxonomy_term_delete', $term);
    module_invoke_all('entity_delete', $term, 'taxonomy_term');
  }

  // Reset static cache after all terms deleted.
  taxonomy_terms_static_reset();
}

of course it's better to write batch function but if it's one time operation you can try to do it simple (be aware that operation may be interrupted depends on your max_execution_time value).
Comment: As an additional suggestion a simple php script on the server calling this function should suffice so long as drupal 8 is bootstrapped at the top of the file. The cleanest example (untested) I can find to bootstrap D8 is from this tutorial http://allabouttodd.com/story/how-programmatically-bootstrap-drupal-8-php-script then simply execute the script with php, no drush needed.
Comment: Try to use your solution, combine with @tenken, but I get an error :
`Error: Call to undefined function field_attach_delete() in delete_taxonomy_terms()`
Comment: You need add a line like `module_load_include("inc", "field", "field.attach");` at the top of the function `delete_taxonomy_terms` because that function is apart of this modules included files. https://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_delete/7.x
Comment: @tenken Still not working, error still the same. I add my code in my first post
Answer: If you have taxonomy manager module installed, you can mass delete by running this javascript line in the console, which triggers a click on all the items
jQuery(".fancytree-checkbox").each(function() { jQuery(this).trigger("click")} )

How do I bulk delete taxonomy terms?


Geometric interpretation of penalized linear regression

Question: I know that linear regression can be thought as "the line that is vertically closest to all the points":

But there is another way to see it, by visualizing the column space, as "the projection onto the space spanned by the columns of the coefficient matrix":

My question is: in these two interpretations, what happens when we use the penalized linear regression, like ridge regression and
LASSO? What happens with the line in the first interpretation? And what happens with the projection in the second interpretation?
UPDATE: @JohnSmith in the comments brought up the fact that the penalty occurs in the space of the coefficients. Is there an interpretation in this space also?
Comment: I am not sure that it is possible to come up with such an interpretation. Simply because what you provided are images in the original space of features and responses. And penalized regression involves the space of coefficients, which is very different.
Comment: "the line vertically closest to all the points" ?
One usually takes the sum of squares -- see the nice picture on Wikipedia
[Coefficient_of_determination](http://en.wikipedia.org/wiki/Coefficient_of_determination).
The sum of vertical distances is the L1 norm,
which is less sensitive to outliers but much less common.
Answer: Sorry for my painting skills, I will try to give you the following intuition.
Let $f(\beta)$ be the objective function (for example, MSE in case of regression). Let's imagine the contour plot of this function in red (of course we paint it in the space of $\beta$, here for simplicity $\beta_1$ and $\beta_2$).
There is a minimum of this function, in the middle of the red circles. And this minimum gives us the non-penalized solution.
Now we add different objective $g(\beta)$ which contour plot is given in blue. Either LASSO regularizer or ridge regression regularizer. For LASSO $g(\beta) = \lambda (|\beta_1| + |\beta_2|)$, for ridge regression $g(\beta) = \lambda (\beta_1^2 + \beta_2^2)$ ($\lambda$ is a penalization parameter). Contour plots shows the area at which the function have the fixed values. So the larger $\lambda$ - the faster $g(x)$ growth, and the more "narrow" the contour plot is.
Now we have to find the minimum of the sum of this two objectives: $f(\beta) + g(\beta)$. And this is achieved when two contour plots meet each other.

The larger penalty, the "more narrow" blue contours we get, and then the plots meet each other in a point closer to zero. An vise-versa: the smaller the penalty,  the contours expand, and the intersection of blue and red plots comes closer to the center of the red circle (non-penalized solution).
And now follows an interesting thing that greatly explains to me the difference between ridge regression and LASSO: in case of LASSO two contour plots will probably meet where the corner of regularizer is ($\beta_1 = 0$ or $\beta_2 = 0$). In case of ridge regression that is almost never the case.
That's why LASSO gives us sparse solution, making some of parameters exactly equal $0$.
Hope that will explain some intuition about how penalized regression works in the space of parameters.
Comment: I updated the answer, introduced a more exact notation: $g(x)$ for the blue plots, $\lambda$ for the penalization paramater. Does that explain your concern better now?
Comment: Thanks for the clear illustration. I have read elsewhere that the minimum sum of the objectives occurs where they are tangent to each other. I get that if f(\beta)' = -g(\beta)' that would mean the derivative of the sum is zero which is a requirement for an extremum. Is this what is meant here by "when two contour plots meet each other"?
Comment: I think starting with a classical picture, as you've done, is a good start. To *really* understand this, I think it would be helpful to describe how the contours relate to the problem. In particular, we know in both cases, that the smaller we make our penalty, the closer we'll get to the OLS solution, and the larger it gets, the closer to a pure-intercept model we'll get. One question to ask is: How does this manifest itself in your figure?
Comment: By the way, your painting skills seem just fine.
Comment: Thanks for your comment! Everything is intuitively simple here: the larger penalty, the "more narrow" blue contours we get (and then the point two plots meet come closer to zero). An vise-versa: the smaller the penalty: the closer to the center of the red circle the plots will meet (OLS).
Comment: You're getting closer to my intended point: Relating the contours to the penalty in the prose of the answer would help communicate what exactly you're showing and how it changes as the penalization varies. It may not be clear to others that the admissible contours *expand* as the penalty *shrinks*. Also, something slightly different happens once the admissible contours overtake the center point of the ellipsoid.
Comment: Following this intuition, then in order for the contours to meet, you need to define the 'rate of growth' of the contours. I was struggling with this a bit, but it becomes easier to grasp if you think of the dual problem with inequality constraints; see: http://stats.stackexchange.com/questions/105671/geometric-interpretation-of-penalized-linear-regression-ii
Comment: Dumb question. The answer says "we have to find the minimum (of the sum of the two objectives) is achieved when two contour plots meet each other." Why is that the case?
Comment: The minimum is not necessarily achieved at the point where two contours for the same height $H$ meet (as could have been suggested by the figure, where we have three contours for both functions). At that point only $f(\alpha)=f(\beta)=H$. However, it must be necessarily achieved at a point where _some_ contours (even for different heights) touch, otherwise we could get a smaller solution by following the contour for one of the functions (i.e., not changing its value) and decreasing the value of the other function.
Comment: Where is intercept? MSE includes the intercept term, which means that contours don't make sense if you don't fix the intercept term.
Answer: The intuition I have is the following:
In the least-squares case, the hat matrix is an orthogonal projection thus idempotent. In the penalized case, the hat matrix is no longer idempotent. Actually, applying it infinitely many times, will shrink the coefficients to the origin. On the other hand, the coefficients still have to lie in the span of the predictors, so it is still a projection, albeit not orthogonal. The magnitude of the penalizing factor and the type of norm control the distance and direction of shrinkage towards the origin.
Comment: I can't see why it's not idempotent: if I project the vector in the space (even if it's not orthogonal projection), and I put a constraint in the coefficients, why would a new projection of this projected vector be different from the previous one?
Comment: Intuitively: Say you are minimizing the penalized sum of squares a second time. The sum of squares at the second minimization is smaller than the sum of squares of the first minimization. The relative importance of the penalized coefficients' norm will increase, i.e., there is more to be gained by shrinking the coefficients some more.
Ridge regression is a good example in which you have a nice closed form for the hat matrix and you can directly check if it is idempotent.
Answer: Second image
The geometric interpretation in the second figure will look as following:
With OLS the observations are projected onto a surface spanned by the regressor variables and this finds the point in the plane that has the shortest distance to the observed vector $(y_1,y_2,y_3)$.
With ridge regression we do not look for a closest point in the entire plane but for a closest point that is inside a circle on the plane (or sphere in higher dimensions and other shape for different types of regression).

Image from the question Why does regularization wreck orthogonality of predictions and residuals in linear regression?
First image
Regularisation will reduce the size of the parameters. So, the fitted line will have a smaller intercept and a smaller slope. In general this will mean that the line will be more flat and closer to the x-axis.


Limit of $\frac{(n-1)^{2n-1-k}}{n^n (n-1-k)^{n-1-k}}$

Question: I'm trying to calculate the limit of $$\frac{(n-1)^{2n-1-k}}{n^n (n-1-k)^{n-1-k}}$$ as $n \to \infty$. I know (using Wolfram Alpha) that the limit should be equal to $e^{k-1}$. However I'm unable to manipulate the expression in the way that I could see the limit to be true.
Answer: Just split it up appropriately. A possible way is as follows:
$$\frac{(n-1)^{2n-1-k}}{n^n (n-1-k)^{n-1-k}} =  \frac{(n-1)^{2n}\cdot (n-1-k)^{k+1}}{n^n\cdot (n-1-k)^n \cdot (n-1)^{k+1}} $$ $$ = \underbrace{\frac{(n-1-k)^{k+1}}{(n-1)^{k+1}}}_{\stackrel{n \to \infty}{\longrightarrow}1}\cdot \underbrace{\frac{(n-1)^n}{n^n}}_{\stackrel{n \to \infty}{\longrightarrow}e^{-1}}\cdot \underbrace{\frac{1}{\frac{(n-1-k)^n}{(n-1)^n}}}_{\stackrel{n \to \infty}{\longrightarrow}\frac{1}{e^{-k}} =e^{k}}$$
Comment: Great! I tried to do it in a similar way but seems that Im not that good of a splitter.
Answer: HINT
We have
$$\dfrac{(n-1)^{2n-1-k}}{n^n (n-1-k)^{n-1-k}}=\dfrac{(n-1)^n}{n^n }\dfrac{(n-1)^{n-1-k}}{ (n-1-k)^{n-1-k}}=\left( 1-\frac1n \right)^n\frac{1}{\left( 1-\frac k{n-1} \right)^{n-1-k}}$$


Internet Video | FFMPEG | 2-PASS encoding vs. 1-PASS CRF

Question: What is the most preferable way to encode internet video?
2-Pass encoding probably takes longer processing time, but results in lower file size, and more average bitrate (?) Correct?
CRF (constant rate factor) results in a constant rate, but higher file size?
What is default way sites like youtube, vimeo encode their videos? And should I do it any other way than I do now with 2-Pass encoding?
Answer: Fredrick is right about VBR vs. CBR, but dropson mentions CRF (constant rate factor), which is actually kind of a third method. CBR and VBR both lock in on a bit rate, while CRF locks in on a perceived visual quality. It also takes into account motion in the video, and can typically achieve better compression than 2-pass VBR. More info.
It's the default setting if you're using x264 or Zencoder. I'd go with CRF any time you're doing h.264.
Answer: There are two encoding modes for video
CBR or Constant Bit Rate
Main usage is when you have a fixed carrier for your data, the best example here is the video telephony Use Case, where audio/video/control information needs to co-exist on a fixed 64 kbit carrier. Since this is a real-time UC, one pass encoding is used and the rate-controller (RC) does it's best to have a fixed number of bits assigned to each frame so that the bitrate is deterministic.
VBR or Variable Bit Rate
This encoding scheme is used practically every where else. Variable here means that e.g. if the video goes black or no motion, no bits are sent, i.e bitrate is 0 for this particular moment, then when things starts to move again, the bitrate sky rockets.
This encoding scheme have normally no real-time requirements, e.g. when encoding/transcoding an video. Normally you would use a multipass encoder here to get the highest quality and to even out the bitrate-peakes.
Youtube uses VBR. Use e.g clive to download videos from youtube and analyse them using ffmpeg and you'll see the variable bitrate in action.
As always, wikipedia is your friend, read their entry on VBR and CBR
There is no reason for you to use anything else than VBR (unless you plan to set up an streaming-server)


What is the proper association measure of a variable with a PCA component (on a biplot / loading plot)?

Question: I am using FactoMineR to reduce my data set of measurements to the latent variables.

The variable map above is clear for me to interpret, but I am confused when it comes to the associations between the variables and component 1. Looking at the variable map, ddp and covis very close to the component in the map, and ddpAbs is a bit further away. But, this is not what the correlations show:
$Dim.1
$Dim.1$quanti
        correlation      p.value
jittAbs   0.9388158 1.166116e-11
rpvi      0.9388158 1.166116e-11
sd        0.9359214 1.912641e-11
ddpAbs    0.9327135 3.224252e-11
rapAbs    0.9327135 3.224252e-11
ppq5      0.9319101 3.660014e-11
ppq5Abs   0.9247266 1.066303e-10
cov       0.9150209 3.865897e-10
npvi      0.8853941 9.005243e-09
ddp       0.8554260 1.002460e-07
rap       0.8554260 1.002460e-07
jitt      0.8181207 1.042053e-06
cov5_x    0.6596751 4.533596e-04
ps13_20  -0.4593369 2.394361e-02
ps5_12   -0.5237125 8.625918e-03

Then there is the sin2 quantity, which is height for  rpvi (for instance), but that measure is not the variable that is closest to the first component at all.
Variables
           Dim.1    ctr   cos2    Dim.2    ctr   cos2
rpvi    |  0.939  8.126  0.881 |  0.147  1.020  0.022 |
npvi    |  0.885  7.227  0.784 |  0.075  0.267  0.006 |
cov     |  0.915  7.719  0.837 | -0.006  0.001  0.000 |
jittAbs |  0.939  8.126  0.881 |  0.147  1.020  0.022 |
jitt    |  0.818  6.171  0.669 |  0.090  0.380  0.008 |
rapAbs  |  0.933  8.020  0.870 |  0.126  0.746  0.016 |
rap     |  0.855  6.746  0.732 |  0.040  0.076  0.002 |
ppq5Abs |  0.925  7.884  0.855 |  0.091  0.392  0.008 |
ppq5    |  0.932  8.007  0.868 | -0.035  0.057  0.001 |
ddpAbs  |  0.933  8.020  0.870 |  0.126  0.746  0.016 |
ddp     |  0.855  6.746  0.732 |  0.040  0.076  0.002 |
pa      |  0.265  0.646  0.070 | -0.857 34.614  0.735 |
ps5_12  | -0.524  2.529  0.274 |  0.664 20.759  0.441 |
ps13_20 | -0.459  1.945  0.211 |  0.885 36.867  0.783 |
cov5_x  |  0.660  4.012  0.435 |  0.245  2.831  0.060 |
sd      |  0.936  8.076  0.876 |  0.056  0.150  0.003 |

So, what should I look at when it comes the association between a variable and the first component?
Comment: Althougt points on your map (which looks as the loading plot) clutter, I'd say that the plot corresponds to the "correlations" output nicely. Those "correlations" are the coordinates on Dim1. They, the loadings, are correlations between a factor and variables (when you based your anaysis on standardized data = on correlations b/w the variables).
Comment: In addition to answer(s) below please check [this one](https://stats.stackexchange.com/q/276645/3277) with further links in there.
Answer: Explanation of a loading plot of PCA or Factor analysis.
Loading plot shows variables as points in the space of principal components (or factors). The coordinates of variables are, usually, the loadings. (If you properly combine loading plot with the corresponding scatterplot of data cases in the same components space, that would be biplot.)
Let us have 3 somehow correlated variables, $V$, $W$, $U$. We center them and perform PCA, extracting 2 first principal components out of three: $F_1$ and $F_2$. We use loadings as the coordinates to do the loading plot below. Loadings are the unstandardized eigenvectors' elements, i.e. eigenvectors endowed by corresponding component variances, or eigenvalues.

Loading plot is the plane on the picture. Let's consider only variable $V$. The arrow habitually drawn on a loading plot is what is labeled $h'$ here; the coordinates $a_1$, $a_2$ are the loadings of $V$ with $F_1$ and $F_2$, respectively (please know that terminologically is more correct to say "component loads a variable", not vice versa).
Arrow $h'$ is the projection, on the component plane, of vector $h$ which is the true position of variable $V$ in the variables' space spanned by $V$, $W$, $U$. The squared length of the vector, $h^2$, is the variance$\bf^a$ of $V$. While $h'^2$ is the portion of that variance explained by the two components.
Loading, correlation, projected correlation. Since variables were centered prior extraction of components, $\cos \phi$ is the Pearson correlation between $V$ and component $F_1$. That should not be confused with $\cos \alpha$ on the loading plot, which is another quantity: it is Pearson correlation between component $F_1$ and variable vectored here as $h'$. As a variable, $h'$ is the prediction of $V$ by the (standardized) components in linear regression (compare with drawing of linear regression geometry here) where loadings $a$'s are the regression coefficients (when components are kept orthogonal, as extracted).
Further. We may remember (trigonometry) that $a_1 = h \cdot \cos \phi$. It can be understood as the scalar product between vector $V$ and unit-length vector $F_1$: $h \cdot 1 \cdot \cos \phi$. $F_1$ is set that unit-variance vector because it has no its own variance apart from that variance of $V$ which it explains (by amount $h'$): i.e. $F_1$ is an extracted-from-V,W,U and not an invited-from-outside entity. Then, clearly, $a_1 = \sqrt{var_{V} \cdot var_{F_1}} \cdot r = h \cdot 1 \cdot \cos \phi$ is the covariance between $V$ and standardized, unit-scaled$\bf^b$ (to set $s_1=\sqrt{var_{F_1}}=1$) component $F_1$. This covariance is directly comparable with the covariances between the input variables; for example, the covariance between $V$ and $W$ will be the product of their vector lengths multiplied by the cosine between them.
To sum up: loading $a_1$ can be seen as the covariance between the standardized component and the observed variable, $h \cdot 1 \cdot \cos \phi$, or equivalently between the standardized component and the explained (by all the components defining the plot) image of the variable, $h' \cdot 1 \cdot \cos \alpha$. That $\cos \alpha$ could be called V-F1 correlation projected on the F1-F2 component subspace.
The aforesaid correlation between a variable and a component, $\cos \phi = a_1/h$, is also called standardized or rescaled loading. It is convenient in interpretation of components because it in the range [-1,1].
Relation to eigenvectors. Rescaled loading $\cos \phi$ should not be confused with the eigenvector element which - as we know it - is the cosine of the angle between a variable and a principal component. Recall that loading is eigenvector element scaled up by the component's singular value (sq. root of the eigenvalue). I.e. for variable $V$ of our plot: $a_1= e_1s_1$, where $s_1$ is the st. deviation (not $1$ but original, i.e. the singular value) of $F_1$ latent variable. Then it comes that eigenvector element $e_1= \frac{a_1}{s_1}=\frac{h}{s_1}\cos \phi$, not the $\cos \phi$ itself. The confusion around two words "cosine" dissolves when we recall what kind of space representation we are in. Eigenvector value is cosine of the angle of rotation of a variable as axis into pr. component as axis within variable space (aka scatterplot view), such as here. While $\cos \phi$ on our loading plot is the cosine similarity measure between a variable as vector and a pr. component as ... well.. as vector too, if you like (albeit it is drawn as axis on the plot), - for we are currently in the subject space (which loading plot is) where correlated variables are fans of vectors - not are orthogonal axes, - and the vector angles are the measure of association - and not of space base rotation.
Whereas loading is the angular (i.e. scalar product type) association measure between a variable and a unit-scaled component, and rescaled loading is the standardized loading where the scale of the variable is reduced to unit either, but eigenvector coefficient is the loading where the component is "overstandardized", i.e. was brought to scale $1/s$ (rather than 1); alternatively, it can be thought of as a rescaled loading where scale of the variable was brought to $h/s$ (instead of 1).
So, what are associations between a variable and a component? You may choose what you like. It may be the loading (covariance with unit scaled component) $a$; the rescaled loading $\cos \phi$ (= variable-component correlation); correlation between the image (prediction) and the component (= projected correlation $\cos \alpha$). You might even choose eigenvector coefficient $e= a/s$ if you need (though I wonder what might be a reason). Or invent your own measure.
Eigenvector value squared has the meaning of the contribution of a variable into a pr. component. Rescaled loading squared has the meaning of the contribution of a pr. component into a variable.
Relation to PCA based on correlations. If we PCA-analyzed not just centered but standardized (centered then unit-variance scaled) variables, then the three variables vectors (not their projections on the plane) would be of the same, unit length. Then it automatically follows that a loading is correlation, not covariance, between a variable and a component. But that correlation won't be equal to "standardized loading" $\cos \phi$ of the picture above (based on the analysis of just centered variables), because PCA of standardized variables (correlations-based PCA) yields different components than PCA of centered variables (covariances-based PCA). In correlation-based PCA $a_1= \cos \phi$ because $h=1$, but principal components are not those same principal components as we get from covariances-based PCA (read, read).
In factor analysis, loading plot has basically the same concept and interpretation as in PCA. The only (but important) difference is the substance of $h'$. In factor analysis, $h'$ - called then "communality" of the variable - is the portion of its variance that is explained by common factors which are responsible specifically for correlations among variables. While in PCA the explained portion $h'$ is gross "mixture" - it partly represents correlatedness and partly unrelatedness among variables. With factor analysis, the plane of loadings on our picture would be oriented differently (actually, it will even extend out of our 3d variables' space into the 4th dimension, which we cannot draw; the loadings plane won't be a subspace of our 3d space spanned by $V$ and the other two variables), and projection $h'$ will be of another length and with another angle $\alpha$. (The theoretical difference between PCA and factor analysis is explained geometrically here via subject space representation and here via variable space representation.)

$\bf^{a,b}$ A reply to @Antoni Parellada's request in comments. It is equivalent whether you prefer to speak in terms of variance or in terms of scatter (SS of deviation): variance = scatter $/(n-1)$, where $n$ is the sample size. Because we are dealing with one dataset with same $n$, the constant changes nothing in the formulas. If $\bf X$ is the data (with variables V,W,U centered), then the eigendecomposition of its (A) covariance matrix yields same eigenvalues (component variances) and eigenvectors as the eigendecomposition of (B) scatter matrix $\bf X'X$ obtained after initial division of $\bf X$ by $\sqrt{n-1}$ factor. After that, in the formula of a loading (see the middle section of the answer), $a_1 = h \cdot s_1 \cdot \cos \phi$, term $h$ is st. deviation $\sqrt{var_{V}}$ in (A) but root scatter (i.e. norm) $\Vert V \Vert$ in (B). Term $s_1$, which equals $1$, is the standardized $F_1$ component's st. deviation $\sqrt{var_{F_1}}$ in (A) but root scatter $\Vert F_1 \Vert$ in (B). Finally, $\cos \phi = r$ is the correlation which is insensitive to the usage of $n-1$ in its calculations. Thus, we simply speak conceptually of variances (A) or of scatters (B), while the values themselves remain the same in the formula in both instances.
Comment: @AntoniParellada, please check the footnote.
Comment: I read your addendum, and it is very illuminating. Thank you! Without picking out specific sentences, it would explain some of the transitions from unit-variance to unit norm scaling of $F_1$ along the answer, which previously presented some difficulty (to me).
Comment: This answer is great and has a lot of info, but I think the actual answer to the question would lie in "what does $\alpha$ mean?"
Comment: @ssdecontrol, I added a line regarding that.
Comment: I have been reading your posts on the topic, and I'm stuck on seemingly the most obvious part, when you say... "clearly, $a_1 = \sqrt{var_{V} \cdot var_{F1}} \cdot r = h \cdot 1 \cdot \cos \phi$. Since $r=cos\phi$ and $\sqrt{var{F1}}=1$, it follows that $\sqrt{var_V}=h$. However, $h=\Vert V\Vert= \sqrt{\sum x^2}$, whereas $\sqrt{var_V}=\sqrt{\frac{\sum x^2}{n-1}}$. What am I missing?
Comment: @AntoniParellada, Of course so, but it is so trivial to ignore the n-1 constant term in these theoretical considerations that I thought everybody would take it for granted. All the "$h$s" in the answer can be taken as st deviations or as (centered) norms - as one wishes - without ruining the concept. Please see the footnote I added.
Comment: @ttnphns Ty! I'm still working on explaining the arrows in the R biplot on [this post](https://stats.stackexchange.com/a/276746/67822) and in particular their coordinate calculation as for example in: `cor(X[,1], scr[,1]) * 0.8 * sqrt(nrow(X) - 1)`, which is the correlation of, in this case the first column of the Iris dataset (not centered or scaled) with the first column of the scores calculated with R (which have variance = eigenvalues). The idea of correlation is clear conceptually, but I was trying to justify the $\sqrt{n - 1}$ factor expanding the equations in your post.
Comment: If the line of code in my previous comment is mathematically $a_1 =\text{cor(Sep.Length, scores}_{PC1})\cdot \sqrt{n-1}$, what I get following your post (excellent, by the way) is $a_1=\sqrt{\text{var}_{\text{Sepal.L.}}\cdot \text{var}_{\text{scores}_{\text{PC}1}}}\cdot r = \frac{\sqrt{\sum x^2}}{\sqrt{n-1}}\cdot \text{cor(Sep.Length, scores}_{PC1})$ instead...
Comment: and making sure that $\text{var}(\text{scores}_{\text{PC}1})=1$, as opposed to $\Vert\text{scores}\Vert=1.$
Comment: @AntoniParellada, I didn't grasp the aim of your last comments. Did you get a question for me? If it is about something that you can't conciliate your calculations in that your other thread with my current formulas (do you?), please let me know there, and show the figures computed by your code there, OK? Perheps then I might add here my calculations on the same data as you did there - if you find it helpful.
Comment: "The squared length of the vector, $h^2$, is the variance of $V$". How can a point $V$ have variance? Variance is a property of a sample / collection of points, and here we have a vector $h$ pinpoint to a point $V$. What does it mean for point $V$ to have variance? Thank you.
Comment: @Confounded, V is the name of the whole vector. On the other hand, what is a "vector"? It is an arrow from the origin (say) to a point. The whole picture is in the answer is the vector reprisentation in the so called "subject space", which is the topsy-turvey of a scaterplot.


Disallow Twitter Bootstrap modal window from closing

Question: I am creating a modal window using Twitter Bootstrap. The default behavior is if you click outside the modal area, the modal will automatically close. I would like to disable that -- i.e. not close the modal window when clicking outside the modal.
Can someone share jQuery code to do this?
Comment: @Trevor That's like the opposite of [modal](http://ux.stackexchange.com/questions/12045/what-is-a-modal-dialog-window).
Comment: what if, if there is a page at the background that can only be activated only if the user login first. By clicking the modal Ok button the user will be redirected to the login page. If the user can just clicking out, this means that the user skip the login page and just accessing the page without login. All Hell Break Loose
Comment: @Trevor I don't see any evidence at all to support your claim.
Comment: You may have a perfectly valid reason for doing this (and there are likely many others). However, it's worth noting that in general, UX considerations would advise against this--most users expect that clicking out of a modal will bring the content "below" to the "front."
Comment: The feature is sensible in a scenario when the user has to fill out many form fields in the modal.  If the user accidentally clicks outside of the modal, then all of the entered details would be lost; then they would have to reactivate the modal and refill the fields.  This feature would avoid such an irritation.
Answer: I believe you want to set the backdrop value to static. If you want to avoid the window to close when using the Esc key, you have to set another value.
Example:

OR if you are using JavaScript:
$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
});

Comment: @user1296175 What was your final code to achieve this? I want to do the same.
Comment: Thank you @nobita, add data-backdrop="static" does the trick! Twitter bootstrap document is poor :(
Comment: Check answer from @@Varun Chatterji and include this on your modal definition
Comment: disable out-side click for all modals with single line of js:
 $.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
Comment: For Angular users: var modalInstance = $modal.open({
      templateUrl: 'modalTemplate.html',
      controller: 'modalController',
      backdrop: 'static',
    });
Comment: There is an issue with this if you are using it for a login modal
Any user can add a close button Close
To the modal - live and just close it
Comment: This also disables the controls on the background. Is there a way to keep other controls active but just let the modal not close ?
Comment: Add these attributes to the modal's container div and not the triggering button or anchor !
Comment: I found the show/hide behaviour changed when I just added the `backdrop` and `keyboard` values via javascript, but was able to fix that by additionally specifying `show`, as posted [here](http://stackoverflow.com/a/41293550/1294318).
Comment: I used the version in the comment from Lukas to disable it across all dialogs, but had to use this on Bootstrap 4: $.fn.modal.Constructor.Default.backdrop = 'static';
Answer: Just set the backdrop property to 'static'.
$('#myModal').modal({
  backdrop: 'static',
  keyboard: true
})

You may also want to set the keyboard property to false because that prevents the modal from being closed by pressing the Esc key on the keyboard.
$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
})

myModal is the ID of the div that contains your modal content.
Comment: Also to avoid modal displaying immediately pass in show: false
Comment: Yep, this is the cleanest, simplest answer (since it avoids adding data attributes). For reference, `backdrop` and `keyboard` are mentioned [here in their documentation](http://getbootstrap.com/javascript/#modals-usage) under the _Options_ section.
Comment: Are data attributes something to be avoided? Kindly guide on this.
Comment: @GopalAggarwal: Depends on how you setup the modal. If you associate a modal to multiple anchor tags, then using data attributes might make sense. But when there is just one modal per tag, I would go with the script parameters where every behaviour is visible in one place.
Answer: You can also include these attributes in the modal definition itself:

Comment: Yep, this is the cleanest, simplest answer (since it works by adding data attributes). For reference, backdrop and keyboard are mentioned here in their documentation under the Options section.
Comment: If you launch modal on page load this is the best way to remove other closing options.
Answer: If you already have initialized the modal window, then you may want to reset the options with $('#myModal').removeData("modal").modal({backdrop: 'static', keyboard: false}) to make sure it will apply the new options.
Comment: For now: $('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false});
Comment: This helped me out. After setting the "backdrop: 'static'" the user could still close the modal with a click; seemed like a bug, but this did the trick!
Answer: Override the Bootstrap 'hide' event of Dialog and stop its default behavior (to dispose the dialog).
Please see the below code snippet:
   $('#yourDialogID').on('hide.bs.modal', function(e) {

       e.preventDefault();
   });

It works fine in our case.
Comment: then, how to revert it?
Comment: Just elegant. thx :)

And @sertaconay just create a boolean variable (for instance) which will be checked to decide if u want to prevent the default
Comment: only option here that worked after a modal was opend
Comment: This is a perfect solution if you want to have finer control over when modals are closable and when they're not.
Answer: Yes, you can do it like this:

Comment: This is perfect for a case where the modal is declared in the html, and only opened via javascript - ie there is no link to it. Thanks!
Answer: Kind of like @AymKdn's answer, but this will allow you to change the options without re-initializing the modal.
$('#myModal').data('modal').options.keyboard = false;

Or if you need to do multiple options, JavaScript's with comes in handy here!
with ($('#myModal').data("modal").options) {
    backdrop = 'static';
    keyboard = false;
}

If the modal is already open, these options will only take effect the next time the modal is opened.
Comment: http://stackoverflow.com/questions/16030448/convert-a-twitter-bootstrap-uncloseable-modal-into-a-closeable-one But I dont like this solution though
Answer: Just add these two things
data-backdrop="static"
data-keyboard="false"

It will look like this now

It will disable the escape button and also the click anywhere and hide.
Comment: This advice was provided years earlier.
Answer: You can disable the background's click-to-close behavior and make this the default for all your modals by adding this JavaScript to your page (make sure it is executed after jQuery and Bootstrap JS are loaded):
$(function() {
    $.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
});

Answer: As D3VELOPER says, the following code resolve it:
$('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false});

I'm using both jquery & bootstrap and simply removeData('modal') don't work.
Answer: bs 5
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

   ...

bs 4.4
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#staticBackdrop">
  Launch static backdrop modal
</button>

   ...

Answer: The best I found is add this code to the link

<-- Div -->

Answer: Doing that is very easy nowadays. Just add:
data-backdrop="static" data-keyboard="false"

In your modal divider.
Comment: This advice was provided years earlier on this same page.
Answer: Attribute names have changed in Bootstrap 5. You can use the following :
data-bs-backdrop="static" data-bs-keyboard="false"

Answer: In case anyone comes here from Google trying to figure out how to prevent someone from closing a modal, don't forget that there's also a close button on the top right of the modal that needs to be removed.
I used some CSS to hide it:
#Modal .modal-header button.close {
    visibility: hidden;
}

Note that using "display: none;" gets overwritten when the modal is created, so don't use that.
Comment: Can you not also just remove the button from the modal-header?
Comment: Sometimes it's beneficial to use CSS instead of altering the HTML.
Answer: If you want to conditionally disable the backdrop click closing feature. You can use the following line to set the backdrop option to static during runtime.
Bootstrap v3.xx
jQuery('#MyModal').data('bs.modal').options.backdrop = 'static';

Bootstrap v2.xx
jQuery('#MyModal').data('modal').options.backdrop = 'static';

This will prevent an already instantiated model with backdrop option set to false (the default behavior), from closing.
Answer: You can set default behavior of modal popup by using of below line of code:
 $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';

Comment: like +1 this method, I don't want that option for all modals.
Answer: The updated syntax according to bootstrap 5 is as followed.
Reference Link

Answer: Well, this is another solution that some of you guys might be looking for (as I was..)
My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.
The solutions presented here were not working 100%.
My solution was this:
showLocationModal = function(loc){

    var is_loading = true;

    if(is_loading === true) {

        is_loading  = false;
        var $modal   = $('#locationModal');

        $modal.modal({show:true});

        // prevent Modal to close before the iframe is loaded
        $modal.on("hide", function (e) {
            if(is_loading !== true) {
                e.preventDefault();
                return false
            }
        });

        // populate Modal
        $modal.find('.modal-body iframe').hide().attr('src', location.link).load(function(){

            is_loading = true;
     });
}};

So I temporarily prevent the Modal from closing with:
$modal.on("hide", function (e) {
    if(is_loading !== true) {
        e.preventDefault();
        return false
    }
});

But ith the var is_loading that will re enable closing after the Iframe has loaded.
Answer: <button type="button" class="btn btn-info btn-md" id="myBtn3">Static
Modal</button>

      <button type="button" class="close" data-dismiss="modal">×</button>

Static Backdrop

You cannot click outside of this modal to close it.

      <button type="button" class="btn btn-default" data-
      dismiss="modal">Close</button>

Answer: To Update the backdrop state in Bootstrap 4.1.3 after the modal have been Display, We used the following line from Bootstrap-Modal-Wrapper plugin. Plugin Repository code reference.
$("#yourModalElement").data('bs.modal')._config.backdrop = (true : "static");

Answer: Try main line with:

Answer: $(document).ready(function(e){

  $("#modalId").modal({
     backdrop: 'static',
     keyboard: false,
     show: false
  });

});

"backdrop:'static'" will prevent closing modal when clicking outside of it;
"keyboard: false" specifies that the modal can be closed from escape key (Esc)
"show: false" will hide the modal when the page has finished loading
Answer: The solution presented as an answer does not work, what is wrong?

$(document).ready(function(){
            $('.modal').modal('show');
            $('.modal').modal({
              backdrop: 'static',
              keyboard: false
            })
        });

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  ×
                </button>

<button type="button" class="btn btn-primary">print</button>

Comment: You should post this as a new question, not as an answer to an existing question.  Your new question can reference this original post.
Answer: When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-bs-backdrop="static" data-bs-keyboard="false" for bootstrap 5 and data-backdrop="static" data-keyboard="false" for bootstrap 4

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://email@example.com/dist/css/bootstrap.min.css">

          When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-bs-backdrop="static" data-bs-keyboard="false"
          <button type="button" class="btn btn-primary my-4" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
            Launch static backdrop 5 modal
          </button>

Modal title

                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                  ...

                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Understood</button>

          When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-backdrop="static" data-keyboard="false"
          <button type="button" class="btn btn-primary my-4" data-toggle="modal" data-target="#exampleModal">
            Launch static backdrop 4 modal
          </button>

Modal title

                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                  </button>

                  ...

                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Save changes</button>

Answer: Just set static for backdrop option (backdrop: 'static'). And prevent closing the modal by pressing Esc from keyboard you have to set false for keyboard option (keyboard: false)
So, the code will be.
var jq = jQuery.noConflict();
jq(document).ready(function(){
    jq('#exampleModal').modal({backdrop: 'static', keyboard: false});
});

Answer: Nobita's answer works for single cases, but I have like 20-30 modals on an old site and was looking for an answer that set this for every modal opened with bootstrap.
You can target the event namespace for the modal and add in default settings for every bootstrap modal.
You might not want to do this for every modal but in case you did, there's no need to statically specify each modal call.
$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
    var $this = $(this)
    var href = $this.attr('href')
    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
    var option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data(), {backdrop: 'static', keyboard: false})

    e.preventDefault()

    $target
      .modal(option)
      .one('hide', function () {
        $this.focus()
      })
})

In my case, I added {backdrop: 'static', keyboard: false} to the option structure.
Answer: If you are using bootstrap 5 or above, use the below code in modal div

This will restrict user, now popup won't get closed by 'Esc' button and by clicking outside.
Answer: If you are using Bootstrap 5 or later, it's recommended to use data-bs-backdrop and data-bs-keyboard. If you are using Bootstrap 4 or an earlier version, you can use data-backdrop and data-keyboard. Ensure that you are using the correct attribute based on the version of Bootstrap you are working with.
v5
 data-bs-backdrop="static" data-bs-keyboard="false"

v4
 data-backdrop="static" data-keyboard="false"

https://getbootstrap.com/docs/5.2/components/modal/#static-backdrop


duvida ao fazer mapeamento nhibernate

Question: Tenho o seguinte cenário:
public class ExemploDTO
{
    public virtual int Id { get; set; }
    public virtual List<PessoaDTO> Cliente { get; set; }
    public virtual ServicoDTO Servico { get; set; }
}

Como seria o mapeamento dessa classe usando:
NHibernate.Mapping.ByCode.Conformist ou Fluentnhibernate
Comment: http://pt.stackoverflow.com/questions/22354/como-usar-o-fluent-nhibernate-apropriadamente?rq=1
Answer: Usando Fluent ficaria assim:
public class ExemploMap : ClassMap<ExemploDTO>
{
    public ExemploMap()
    {
        Id(x => x.Id);
        .Length(10)
        .Not.Nullable();
        References(x => x.ServicoDTO);
        HasMany(x => x.PessoaDTO);
    }
}

Te aconselho a dar uma olhada aqui, aqui e aqui,
com certeza vai clarear tuas ideias. E, se tu estiver começando agora, dá uma olhada no ActiveRecord.
Comment: Lembrando que é preciso mapear a tabela, então antes de Id, colocar Table("Owner.TableName");

duvida ao fazer mapeamento nhibernate


How to display datetime in SourceTree terminal bash

Question: This is referring to the git Terminal that can be launched from the Atlassian SourceTree desktop client on Windows (7). I just want to be able to see the datetime for when a command was run. Right now all I see when I run a git command in this Terminal is:
username@machine MINGW64 /path/to/git/dir (branch)

I want to see something like:
2016-06-22T21:01:48+00:00 username@machine MINGW64 /path/to/git/dir (branch)

Where can I edit the .bashrc file to show this? I can't find an option in the SourceTree desktop client.
Comment: I think you can in the git terminal `cd ~` to witch to your local directory,  and edit `.profile` and more precisely the environment variable PS1
Answer: If you know the path of git used by SourceTree (embedded or external git), you can modify <git>\etc\profile.d\git-prompt.sh with:
PS1="$PS1"'\w \t'             # current working directory

The \t will add the timestamp to the git bash prompt:
vonc@voncavn7 MINGW64 /d/git/tests/subm/p1 23:45:37 (master)


Performing a statistical model/test like "random effects model" to account for pseudoreplicates

Question: I'm trying to estimate whether the values of signal (S) and background (B) intensities for a probe with 3 replicate spots (i.e. pseudoreplicates) are statistically significantly different at a given p value in a microarray experiment. This means that I have 3 values for signal intensities and 3 values for the (local) background values.
I have found it inappropriate to conduct any "standard" statistic such as Student t-test or Wilcoxon test on such data, as individual observations (the replicate spots) are heavily dependent on each other. This is because these replicates were dispensed on the microarray slide during the same printing run. In addition, the sample size is extremely small.
According to some articles, one could account for this dependence while performing the statistical analysis by e.g. using a statistical model which accounts for the dependence, like a hierarchical model or random effects model.
I'm wondering if there is anyone who can tell me how I should proceed to perform a random effects model for my data in R language. Furthermore, I truly appreciate if anyone can provide input for handling the statistical analysis in this example.
Answer: This question is part CrossValidated ("what's the proper statistical analysis?"), part Stack Overflow ("how do I do it in R?")
Short answer: you're looking for something like
library(nlme)
lme(response~spotType,random=~1|probe/spotType,data=myData)

where spotType is a factor (categorical variable) with levels S and B and probe is a factor with a different value for each probe (assuming there are 6 observations per probe, 3 S and 3 B). Alternatively, you should be able to average the 3 S values and the 3 B values for each probe and run a simple t-test, something like
myData  <- data.frame(spotType=rep(rep(c("S","B"),each=3),10),
              probe=factor(rep(1:10,each=6)),
              response=rnorm(60))
d2 <- aggregate(response~spotType+probe,FUN=mean,data=myData)
t.test(response~spotType,data=d2,paired=TRUE)

(these don't give absolutely identical answers, I haven't quite figured out why ...)
Comment: Having said that I was thinking to conduct your suggested statistical modeling/testing probe-wise instead of doing the test for spotType (B vs. S) with respect to all probes at once. What do you say? Cheers!
Comment: many thanks for your interest in my question! The basic idea is to detect the number of "true" probes by using the values of S and B intensities that are statistically significantly different at a given p value. This might be used as a guide to further explore and evaluate signal-to-noise ratios in a more objective manner. You can imagine a scenario where one has made a dilution series of the probes and now wants to determine at which dilution (concentration) the values of S and B for a given probe is not statistically significantly different (simply to find optimal dilutions).


Unable to connect to signal in QML emitted from Python

Question: I have a QQuickItem class created in Python:
class MyPage(QQuickItem):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        error_encountered = Signal(str)

    @QtCore.Slot(QUrl, result=None)
    def load_report(self, file_path: QUrl) -> None:
        print(f"Called with: {file_path}")
        self.error_encountered.emit("Uh oh!")

The above class is registered as:
qmlRegisterType(MyPage, "MyPage", 1, 0, "MyPage")
My QML looks like:
MyPage {
    signal errorEncountered(string text)
    Component.onCompleted: error_encountered.connect(errorEncountered)
    onErrorEncountered: console.log(text)
}

However, I get the following error:
qrc:/qml/main.qml:93: ReferenceError: error_encountered is not defined
The pattern for PySide2 to connect to signals from QML to the source code is a bit different in Python than C++ and I'm having trouble figuring it out.  In C++ I would have had a signal defined like void errorEncountered(const QString& errorMessage); and in my QML I could have simply done onErrorEncountered: console.log(errorMessage).
Answer: The signals are declared as an attribute of the class, that is, they should not be created in any method of the class. The solution is:
class MyPage(QQuickItem):
    error_encountered = Signal(str) # <---

    def __init__(self, parent=None) -> None:
        super().__init__(parent)

    @QtCore.Slot(QUrl, result=None)
    def load_report(self, file_path: QUrl) -> None:
        print(f"Called with: {file_path}")
        self.error_encountered.emit("Uh oh!")


Fail2Ban unbans after 10 minutes. bantime none warning?

Question: having a bit of an issue with fail2ban filters, for some reason it unbans after 10 minutes even though I set the ban length to one year. Could you assist a brother out?
jail.local declaration for filters:
[nginx-proxy]
enabled  = true
#port    = http,https
action   = iptables-multiport[name=NoProxy, port="http,https"]
filter   = nginx-proxy
logpath  = /etc/nginx/logs/*access*.log
bantime  = 31536000 # 1 year
maxretry = 0

[nginx-shellshock]
enabled  = true
#port    = http,https
action   = iptables-multiport[name=ShellShock, port="http,https"]
filter   = nginx-shellshock
logpath  = /etc/nginx/logs/*access*.log
bantime  = 31536000 # 1 year
maxretry = 0

nginx-proxy.conf
[Definition]
failregex = ^<HOST> .* "GET http.*
ignoreregex =

nginx-shellshock.conf
[Definition]
failregex = ^<HOST>.*\(\s*\)\s*\{[^"]*\}\s*\;[^"]+.*

ignoreregex =

Here is my fail2ban.log file
2015-10-27 06:21:48,953 fail2ban.jail           [8319]: INFO    Jail 'nginx-auth' started
2015-10-27 06:21:48,981 fail2ban.jail           [8319]: INFO    Jail 'nginx-badbots' started
2015-10-27 06:21:49,022 fail2ban.jail           [8319]: INFO    Jail 'nginx-proxy' started
2015-10-27 06:21:49,062 fail2ban.jail           [8319]: INFO    Jail 'nginx-shellshock' started
2015-10-27 13:17:40,737 fail2ban.filter         [8319]: INFO    [nginx-shellshock] Found 184.108.40.206
2015-10-27 13:17:41,667 fail2ban.actions        [8319]: NOTICE  [nginx-shellshock] Ban 18.104.22.168
2015-10-27 13:17:41,747 fail2ban.filter         [8319]: INFO    [nginx-shellshock] Found 184.108.40.206
2015-10-27 13:17:41,747 fail2ban.filter         [8319]: INFO    [nginx-shellshock] Found 220.127.116.11
2015-10-27 13:17:41,880 fail2ban.actions        [8319]: NOTICE  [nginx-shellshock] 22.214.171.124 already banned
2015-10-27 13:27:42,572 fail2ban.actions        [8319]: NOTICE  [nginx-shellshock] Unban 18.104.22.168

On fail2ban service restart, I also get an error about shellshock bantime being set to none:
2015-10-28 00:29:31,351 fail2ban.transmitter    [11600]: WARNING Command ['set', 'nginx-shellshock', 'bantime', 'None'] has failed. Received ValueError("invalid literal for int() with base 10: 'None'",)

Greatly appreciate any help, thank you.
Answer: The entire issue was dedicated around me using the comment tag, which apparently in fail2ban configurations comments the entire line. Either change the hash tag to a semi colon or put it on another line.


Effectively describing all elements of the Borel $\sigma$-algebra

Question: Consider, for simplicity, the Borel $\sigma$-algebra of the unit interval $[0,1]$.
Let $\{A_i\}$ be a family of Borel subsets which generate the sigma algebra (can be either countable or uncountable). I was wondering if there is some way of describing all subsets of the sigma-algebra only using $A_i$ and set operations.
Moreover, I am curious if we can linearly order all elements of the Borel sigma algebra in a way that any element in the ordering is either one of the generating elements or can be described as a countable union of elements that have appeared before it.
My motivation is, among other things, to prove following two statements in a straightforward way;
(1) The cardinality of the Borel $\sigma$-algebra equals the cardinality of $\mathbb{R}$.
(2) If a $\pi$ system $K$ is contained in a Dynkin system $D$, then the $\sigma$-algebra generated by $K$ is contained in $D$.
Answer: Yes.  The usual construction is the following (from memory, someone please double check me):
Let $\mathcal{C}_0$ be some collection of sets, and for ordinals $\alpha > 0$, define $\mathcal{C}_\alpha$ recursively as the collection of all countable unions and complements of sets from $\bigcup_{\beta < \alpha} \mathcal{C}_\beta$.  Then $\sigma(\mathcal{C}_0) = \mathcal{C}_{\omega_1}$, where $\omega_1$ is the first uncountable ordinal.
So in a sense, any Borel set can be produced by taking the sets $A_i$, taking countable unions and complements, and iterating uncountably many times.
Comment: @a12345 For the proof, you can take a look at section 4.1 in *The joy of sets* by Keith Devlin. That is probably the most readable exposition. The book also shows how one can use the construction to show there are as many real numbers as Borel sets.
Comment: This is very nice, although I don't think I can prove it. So, the statement $\sigma(C_0)=C_{\omega_1}$ proves (1)?


How to keep groups when pulling with git

Question: I have a staging site that is a working directory of a git repository. How to set up git to let a developer pull out a branch or release without changing the group of the modified files?
An example. Let's say I have two developers, robin and david. They are both in git-users group, so initially they can both have write permissions on site.php.
-rw-rw-r--  1 robin git-users   46068 Nov 16 12:12 site.php
drwxrwxr-x  8 robin git-users    4096 Nov 16 14:11 .git

After robin-server1$ git pull origin master:
-rw-rw-r--  1 robin robin       46068 Nov 16 12:35 site.php
drwxrwxr-x  8 robin git-users    4096 Nov 16 14:11 .git

And david do not have write permissions on site.php, because the group changed from 'git-users' to 'robin'. From now on, david will get a permission denied, when he tries to pull to this repository.
Answer: This is best addressed with setting the permissions on all of the directories. If you set the the group 'setgid' bit, all files in the directory will maintain the group of the directory when members of the group modify them. So, to quickly set this on the staging site do the following:
chmod g+ws [directory]
find [directory] -type d -exec chmod g+ws {} \;
find [directory] -type f -exec chmod g+w {} \;

The first command sets the write and setgid bits for the group on the site top level directory. The second then finds all subdirectories of the top level folder and does the same. The third then makes sure the the group has write access to all of the files.
When you initially create the git repository, you can have it do the above automatically by using the --shared option:
git create --shared [directory]

Comment: The question is obviously about files in the working directory and not the Git data files. This setting does **not** effect the working directory files, though.
Answer: Try with git submodules, that should be solution to what you need.
Or if you really don't want it, you can implement some scripts for this that will stash some files before pull and then pop them out, but this will also make you problems later with merging.
Comment: I don't really get it. How would a git submodule help me?
Comment: With git submodule different users can have control over different submodules, not clashing with each other, exactly what you asked for.

Or, I had situation once with script which was stashing some files, run by some users, and then doing stash pop when it's run by other user, but the big issue here is merge conflicts, which you however have to resolve...
Comment: I'm not sure I get you. Do you suggest to create a new, empty repository, and put the whole project into the root as one submodule because 'git submodule update' will not mess with the groups?


how to download php53 on centos 5.3 ( i had installed php54 before)

Question: I would like to install php53 on centos5.3 (had installed php54 before but removed) I did it as below.

sudo yum remove php php-common php-cli
sudo yum install php53
sudo yum install zabbix-web-mysql

but when i tried last thing, it shows the following error:
Installed: php53.x86_64 0:5.3.3-26.el5_11
Dependency Installed: php53-cli.x86_64 0:5.3.3-26.el5_11 php53-common.x86_64 0:5.3.3-26.el5_11
Complete!
[root@QCacti ~]# sudo yum install zabbix-web-mysql
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * epel: ftp.jaist.ac.jp
 * atomic: mirrors.neusoft.edu.cn
 * rpmforge: ftp.riken.jp
 * base: centos.mirror.cdnetworks.com
 * updates: centos.mirror.cdnetworks.com
 * extras: centos.mirror.cdnetworks.com
 * addons: centos.mirror.cdnetworks.com
Excluding Packages from CentOS / Red Hat Enterprise Linux 5 - atomicrocketturtle.com
Finished
Setting up Install Process
Parsing package install arguments
Resolving Dependencies
--> Running transaction check
---> Package zabbix-web-mysql.x86_64 0:2.4.7-1.el5 set to be updated
--> Processing Dependency: zabbix-web = 2.4.7-1.el5 for package: zabbix-web-mysql
--> Processing Dependency: php-mysql for package: zabbix-web-mysql
--> Running transaction check
---> Package zabbix-web.x86_64 0:2.4.7-1.el5 set to be updated
--> Processing Dependency: php53-bcmath for package: zabbix-web
--> Processing Dependency: php53-gd for package: zabbix-web
--> Processing Dependency: php53-mbstring for package: zabbix-web
--> Processing Dependency: php53-xml for package: zabbix-web
---> Package php-mysql.x86_64 0:5.1.6-45.el5_11 set to be updated
--> Processing Dependency: php-common = 5.1.6-45.el5_11 for package: php-mysql
--> Processing Dependency: php-pdo for package: php-mysql
--> Running transaction check
---> Package php53-xml.x86_64 0:5.3.3-26.el5_11 set to be updated
---> Package php-common.x86_64 0:5.1.6-45.el5_11 set to be updated
---> Package php-pdo.x86_64 0:5.1.6-45.el5_11 set to be updated
---> Package php53-gd.x86_64 0:5.3.3-26.el5_11 set to be updated
---> Package php53-bcmath.x86_64 0:5.3.3-26.el5_11 set to be updated
---> Package php53-mbstring.x86_64 0:5.3.3-26.el5_11 set to be updated
--> Processing Conflict: php53-common conflicts php-common
--> Finished Dependency Resolution
php53-common-5.3.3-26.el5_11.x86_64 from installed has depsolving problems
  --> php53-common conflicts with php-common
Error: php53-common conflicts with php-common

Comment: Please use [Markdown](http://serverfault.com/editing-help) and/or the formatting options in the edit menu to properly type-set your posts to improve their readability. Also use cut-and-paste for posting console output and format it as "`code`" rather than posting screenshots. That improves readability, attracts better answers  and allows indexing by search engines, which may help people with similar questions.
Answer: Are you sure you're installing PHP 5.3, not just PHP?
Try following this guide and specify php version during installation like:
yum install php53 php53-cli php53-common php53-gd php53-imap php53-intl php53-mbstring php53-mysql php53-odbc php53-pdo php53-pspell php53-snmp php53-xml php53-xmlrpc
Also, before downgrading, you should remove php54, you sad you had been using:
rpm -qa | grep -i php
yum remove php
yum remove php-cli
yum remove php-pdo
yum remove php-common
yum remove <other php packages>

Now the zabbix-web-mysql you're trying to install has dependency on php5.4. It is not supported with PHP 5.3, however you can try to install it from RPM-package without dependencies:
wget http://repo.zabbix.com/zabbix/2.4/rhel/5/x86_64/zabbix-web-mysql-2.4.7-1.el5.x86_64.rpm
wget http://repo.zabbix.com/zabbix/2.4/rhel/5/x86_64/zabbix-web-2.4.7-1.el5.x86_64.rpm
rpm -ivh --nodeps zabbix-web-2.4.7-1.el5.x86_64.rpm zabbix-web-mysql-2.4.7-1.el5.x86_64.rpm`

But me why would you use CentOS 5.3 which should have been upgraded to 5.11 like 5 years ago?
You should consider installing zabbix on CentOS 7 instead
Comment: thank you for your help. cause i am using that server for test, i made it like what you said at first. Thank you so much haha
Comment: well, you should consider upgrading, otherwise you might run into dependency-hell when trying to install anything (probably you're going there right now with zabbix)
Comment: @PYO So has you solved the problem? It's unclear from your message...


Combining standard errors of fit parameters

Question: I have fitted a 3 parameter (mean, sigma & tau) model to my data and have also computed the standard error for each of them. The statistic of interest for my data is the sum of mean and tau. My question is how do I estimate the total error for this new statistic? I know I can't simply add up the errors for mean and tau. Any help would be greatly appreciated. Thanks in advance.
Comment: $Var(X + Y) = Var(X) + Var(Y) + 2 Cov(X, Y)$ (http://en.wikipedia.org/wiki/Variance)
Answer: If you can't derive Cov(mu, tau) you can bootstrap the statistic of interest, i.e. mu+tau (note that the standard bootstrap may not be valid for non-iid data)


Using CASE WHEN to check if a UserID exists within a column

Question: I created a temp table that creates a list of userid's of users that are subscribed to two different lists. So the table looks something like this:
|userid|
+++++++++
1
2
3
4
5

I want to create a Yes/No flag simply is any value for userid is present in this row. I tried building it out like this:
CREATE TABLE temp.flags AS
SELECT distinct userid,
                         CASE WHEN _______
                         then 'Y' ELSE 'N' END AS Both
FROM temp.usertable

I want the output to look this:
|userid|
+++++++++
Y
Y
Y
Y
Y

Answer: Personally, I'd reverse the logic:
SELECT distinct
  userid,
  CASE WHEN userid IS NULL THEN 'N' ELSE 'Y' END as is_userid_present
FROM temp.usertable

But you could also:
SELECT distinct
  userid,
  CASE WHEN userid IS NOT NULL THEN 'Y' ELSE 'N' END as is_userid_present
FROM temp.usertable


"Explanation or submission guidelines" missing

Question: In editing a content type on a Drupal 8 site, I added text to the Explanation or submission guidelines, but when I surf to the node create/edit form, the text is nowhere to be seen.
Is this a bug, or are there extra steps involved that aren't documented in the UI?
Answer: That information is displayed in the help block. Make sure the theme you are using on those pages has a help block.
The Seven theme does have that by default, but either you've configured the node add/edit pages to use the front page theme, or you removed the help block.
Answer: You have to place the "Help" block in your administration theme block layout.
Keep in mind that you need to have the Help module enabled to have the "Help" block available
Answer: Note that in Drupal 8, you currently may have to clear caches to see this text in the help block.


How can I have a fixed height for table cells in Firefox?

Question: How can I have fixed height for table cells in Firefox? The following works in IE and Chrome, but Firefox is not using the specified height:
<!DOCTYPE html>

        <title>Table Cell Height Test</title>

                    Staff

                    Staff
                    Monday

                     27th

The aim is to have overlay the same height as the test table.
One solution I have found is to wrap the cell contents in a div and set the height on the div.
Another solution I have found is using jQuery,
$('table.overlay tr').height($('table.test tr').outerHeight());

Are there any other solutions?
Answer: The height of a cell depends on the height requirements of its contents, and any height value set will be taken as imposing a minimum height. When the content is text, the height requirements depend on the number of lines of text and on the line height, which may vary by browser. So if you really want consistent rendering within some fixed (in pixels) area, you would need to set font size and line height in pixels (which implies problems of its own of course).
Comment: Looking at the white "Staff" cell in Firebug layout pane, I see content height as 33 (pixels), top and bottom padding both as 4, and bottom border as 1, making a total of 42. Some other browsers may treat the `height` property as setting a minimum on *content* height. If this causes undesired variation, I don't think there's a better option than wrapping cell contents in a `div`, setting any desired padding inside it, and setting table cell padding to zero.
Comment: Well Firefox is not taking it as minimum height. It is rendering the cell has less height then the specified one. Hence my question
Comment: yeah.. weird.. Shouldn't it be using box-sizing: content-box; ??


Dúvida com a função compareTo

Question: Quando eu executo o código abaixo o compareTo retorna um valor menor que zero.
public class compare
{
 public static void main ( String [] args )
 {
    String str1 = "araraaaaaa";
    String str2 = "asa";

    int comp = str1.compareTo(str2);

    System.out.println(""+comp) //  printa -1 na tela

 }
}

Teoricamente, str1 não é maior que str2?
Por que ele retorna negativo?
Comment: Se estiver querendo comparar o conteúdo dessas strings, use `str1.equals(str2);` que retorna 'true' se forem iguais.
Answer: O método compareTo da classe String é utilizado para ordenar as Strings alfabeticamente*, e não por tamanho. Desta forma temos que "araraaaaaa" vem antes de "asa", e portanto o compareTo dá -1, porque ao comparar a primeira letra as duas Strings são iguais (a) e ao comparar a segunda, o r vem antes do s.
Para comparar as Strings por tamanho, você deveria invocar o método length das Strings e então comparar os tamanhos diretamente. (Sugestão do Marcelo Bonifazio)
Vale lembrar também que sempre que temos a.compareTo(b) retornando -1 (ou algum outro número negativo) significa que a antecede b, se retorna +1 (ou algum outro número positivo) então a sucede b e se retorna 0 então a e b são similares. Entrentanto a definição exata de "antecede", "sucede" e "similar" fica a critério de cada classe que implementa o compareTo. No caso da classe String a definição é dada pela ordenação alfabética*.

(*) - Na verdade a comparação não é exatamente alfabética, e sim é baseada em comparação de sequências de valores numéricos de codepoints unicode.
Comment: uma alternativa seria nomeDaString.length();
Comment: @MarceloBonifazio Exato

Dúvida com a função compareTo


which is the recommended way to install sshd in cygwin on windows 7 enterprise

Question: What is the recommended procedure to install sshd on Windows 7 Enterprise ? I have already installed cygwin and openssh on this computer.
i'm open to non-cygwin sshd as long as there won't be any compatibility issues with cygwin related programs.
UPDATE
I want setup/config information as well. Currently, I get an error if I try to connect to localhost.
$ ssh localhost
ssh: connect to host localhost port 22: Connection refused
Answer: ssh-host-config. See also /usr/share/doc/Cygwin/openssh.README.
Answer: You've already got it installed. It's part of the openssh package in cygwin. Type "man sshd" in your Cygwin shell and you should see it.
Comment: Are you actually running sshd yet? Since you have it installed, you need to run it. Like any other software. If you want to run it as a service, look into cygrunsrv.
Comment: i am not running it yet. i was looking for a detailed guide into doing so -- the whole question was looking for detailed steps to run sshd.
Comment: So do what I suggested : type "man sshd" and read it.
Answer: Check out this step by step guide: http://pigtail.net/LRP/printsrv/cygwin-sshd.html
Answer: Personally, I just install Bitvise WinSSHD as my SSHD service on Windows systems.


Finding the irreducible components of a rank 3 tensor

Question: In 3 dimensions, a rank-2 tensor can be identified via a scalar, a vector and a (symmetric, traceless) tensor component by contracting it with $\delta_{ij}$ or $\epsilon_{ijk}$:
$$ T_{ij} = \underbrace{\frac{1}{3}T_{kk}\delta_{ij}}_\text{scalar} + \underbrace{\frac{1}{2}(T_{ij}-T_{ji})}_\text{vector} + \underbrace{\frac{1}{2} (T_{ij}+T_{ji}) -\frac{1}{3}T_{kk}\delta_{ij}}_\text{symm., traceless tensor} $$
The components are $1 + 3 + 5 = 9$, which is fine for a general rank-2 tensor $T_{ij}$.
Now my question is: how does such a decomposition into irreducible representations work for a rank-3 (...or even rank-$n$?) tensor?
Comment: Related: [Irreducible representation of $SO(3)$ by rank-3 tensors and higher?](https://math.stackexchange.com/questions/3747810/irreducible-representation-of-so3-by-rank-3-tensors-and-higher), [What are the tensors forming an irreducible representation of $SO(3)$ by rank-3 tensors and higher?](https://math.stackexchange.com/questions/3752859/what-are-the-tensors-forming-an-irreducible-representation-of-so3-by-rank-3)
Answer: Using the bold-number notation to denote the representation of dimension $2\ell+1$ (with total angular momentum number $\ell$), the decomposition you give of rank-2 tensors is equivalent to the decomposition
$$
\mathbf{3}\otimes\mathbf{3} = \mathbf{1} \oplus \mathbf{3} \oplus \mathbf{5}
$$
for the $\rm SO(3)$ rotation group, with the $\mathbf{1}$, $\mathbf{3}$ and $\mathbf{5}$ corresponding, respectively, to the scalar, vector, and symmetric traceless tensors. (In terms of dimensions, you can write $\dim(\mathbf{3}\otimes\mathbf{3} )=3\times 3=9$ and $\dim(\mathbf{1} \oplus \mathbf{3} \oplus \mathbf{5})= 1 + 3 + 5=9$.)
For rank 3, you basically do the same:
\begin{align}
\mathbf{3}\otimes\mathbf{3}\otimes\mathbf{3}
& = (\mathbf{3}\otimes\mathbf{3})\otimes\mathbf{3}
\\ & = (\mathbf{1} \oplus \mathbf{3} \oplus \mathbf{5})\otimes\mathbf{3}
\\ & = (\mathbf{1}\otimes\mathbf{3}) \oplus (\mathbf{3}\otimes\mathbf{3}) \oplus (\mathbf{5}\otimes\mathbf{3})
\\ & = (\mathbf{3}) \oplus (\mathbf{1} \oplus \mathbf{3} \oplus \mathbf{5}) \oplus (\mathbf{3} \oplus \mathbf{5} \oplus \mathbf{7})
\\ & = \mathbf{1} \oplus \mathbf{3} \oplus \mathbf{3} \oplus \mathbf{3} \oplus \mathbf{5} \oplus \mathbf{5} \oplus \mathbf{7}.
\end{align}
(In terms of dimensionality,
$$\dim(\mathbf{3}\otimes\mathbf{3}\otimes\mathbf{3})=3^3=27$$
whereas
\begin{align}
\dim(\mathbf{1} \oplus \mathbf{3} \oplus \mathbf{3} \oplus \mathbf{3} \oplus \mathbf{5} \oplus \mathbf{5} \oplus \mathbf{7})
& = 1+3+3+3+5+5+7 = 27,
\end{align}
which works out fine.)
This means that the decomposition into irreducible representations must contain

one scalar representation,
three vector representations,
two quadrupole representations (isomorphic to symmetric traceless tensors of rank 2), and
one octupole representation.

It is important to note that this is only true for a general rank-3 tensor, with no symmetry relations between the various indices. If there are symmetry constraints, the picture will obviously change.

So, the next question is, of course, what are these tensor representations?
The structure of these representations is encased within the symmetry of the tensor, so it's important to break it down as such. Thus, we separate $T$ into
$$T_{ijk} = S_{ijk} + A_{ijk} + N_{ijk},$$
where $S$ is totally symmetric under exchange of indices, $A$ is totally antisymmetric, and $N$ is a remainder which is neither symmetric nor antisymetric.
With that in hand, let's see what representations are in each symmetry sector.

The symmetric part $S$ contains the first vector representation, by contracting it with a Kronecker delta, $\alpha_k = \delta_{ij}S_{ijk}$ (its "trace part"), or $$\alpha_k = \frac13\left( \delta_{ij}T_{ijk} + \delta_{ij}T_{ikj} + \delta_{ij}T_{kij}\right)$$ in terms of our initial tensor. This can be lifted back to a full rank-3 tensor which contributes directly to $T$ in the form $$K_{ijk} = \frac15 \left( \alpha_i \delta_{jk} + \alpha_j \delta_{ik} + \alpha_k \delta_{ij} \right).$$

The remaining part of $S$, defined as $R$ in $S_{ijk} = K_{ijk}+ R_{ijk}$, is the octupole, $\ell=\mathbf 3$, representation. (In other words, the totally symmetric part $S$ of $T$ is already "almost" an invariant subspace under $\rm SO(3)$, and all we needed to do was remove a vector component.)

Turning now to the antisymmetric part, this is already an irreducible representation as it stands, because it is actually just a one-dimensional subspace. This is the scalar representation, which can be seen because there is only a single rank-3 totally antisymmetric isotropic tensor, the Levi-Civita tensor, so we must have $A_{ijk} = A\, \epsilon_{ijk}$, with $A=\frac16 \epsilon_{ijk}A_{ijk}=\frac16 \epsilon_{ijk}T_{ijk}$ the relevant (pseudo)scalar.

The rest of the game (two vector and two quadrupole representations) must therefore be encoded in the mixed-symmetry remainder, $N_{ijk}$. This mixed-symmetry part looks quite intimidating (starting with, what does mixed-symmetry even actually imply?), but here is the simple trick to make sense of it: just do a partial contraction with the Levi-Civita symbol, i.e. something of the form
$$
A_{ij} = \epsilon_{ikl}T^{jkl}, \quad B_{ij} = \epsilon_{ikl}T^{kjl}, \quad C_{ij} = \epsilon_{ikl}T^{klj},
$$
which gives you three separate rank-2 tensors directly from $T$. However, it's important to note that these are not all independent, since one can show that their sum,
$$
A_{ij} + B_{ij} + C_{ij} = 3\epsilon_{ikl}A_{jkl},
$$
reduces to the antisymmetric part. (On the other hand, the symmetric part $S$ does not contribute at all to the $B$ and $C$ tensors.) The upshot from that is that we can forget about $A_{ij}$ (which is then just a re-encoding of the scalar $A_{ijk} = A\, \epsilon_{ijk}$) and use it to get two independent rank-2 tensors,
$$
\tilde B_{ij} = B_{ij} - 2A\delta_{ij} \quad\text{and}\quad \tilde C_{ij} = C_{ij} - 2A\delta_{ij},
$$
(whose definition ensures they are all traceless), which are given directly in terms of the mixed-symmetry part $N$ as
$$
\tilde B_{ij} = \epsilon_{ikl}N^{kjl} \quad\text{and}\quad \tilde C_{ij} = \epsilon_{ikl}N^{klj}.
$$
These two rank-2 tensors are linearly independent (as are any two linearly independent combinations of $\tilde B_{ij}$ and $\tilde C_{ij}$ with $\tilde A_{ij} = \epsilon_{ikl}N^{jkl}$). As traceless rank-2 tensors they each have dimension 8, which (times 2) accounts for the full dimensionality (16) of the mixed-symmetry part $N$.
And, as traceless rank-2 tensors, each of $\tilde B_{ij}$ and $\tilde C_{ij}$ contains

one quadrupole representation (symmetric traceless rank-2 tensor), and
one vector representation (antisymmetric rank-2 tensor).

This concludes the count.

References
My account of this decomposition is strongly based on

Decomposition of third-order constitutive tensors. Yakov Itin and Shulamit Reches. arXiv:2009.10752 (2020).

... which is honestly a much better description, though it is longer and more technical.

 I have re-posted a copy of this answer to the thread Rank 3 tensor decomposition on the Physics Stack Exchange site.


Assume that 495 divides the integer $\overline{273x49y5}$ where $x,y \in \{0,1,2...9\}$. Find $x$ and $y$.

Question: So, I know that $495 = 5\times 9\times 11$. So then, if that's the case, then the number $\overline{273x49y5}$ must be divisible by $495$ if and only if it is divisible by $5$ and $9$ and $11$.
Then, I know that $5$ divides it for any number $x$ and $y$ because it only has to divide the digits number which is $5$.
To see if it divides by $9$, the sum of the digits must be divisible by $9$, and as for $11$, the alternating sum of digits must be divisible by $11$.
So, to test it by $9$, then, $2+7+3+x+4+9+y+5 = 30+x+y$ has be divisble by $9$. So, the only numbers $x$ and $y$ that make $30+x+y$ divisible by $9$ are $x= \{0,1,2,3,4,5,6\}$ and $y=\{0,1,2,3,4,5,6\}$.
But $11$ is what gets me. To make it divisible by $11$, then the alternating sums must be divisible by $11$. So then, $-2+7-3+x-4+9-y+5= 12+x-y$ must be divided by $11$. Then, the only numbers $x$ and $y$ that make it divisible by $11$ must be $x=\{0,1,2,\ldots,8\}$ and $y=\{1,2,\ldots,9\}$, if I did my math right.
Next, I assume we must then find numbers in $x$ and $y$ that satisfy the division by $9$ and $11$. So, if that is the case, then I know that since the number must be divisible by $9$ and $11$, then the numbers $x$ and $y$ must fit between $0$ to $6$ because that's $6$ is the highest number $x$ or $y$ can be in the sequence to divide the number. So, how do I check to see which numbers both satisfy division of $9$ and $11$?
Answer: $30+x+y$ doesn't have to equal 9; it has to equal a multiple of 9.  So it could be $36$ or $45$ or $54\ldots$.  And $x$ could be $7$, if $y$ is 8, for example.  But they can't be anything at all; if $x$ is 7 then $y$ must be $8$; no other value of $y$  works.  And if $x$ is 3 then $y$ must be $3$ also.  So make a table that shows for each $x$, what can $y$ be, if $30+x+y$ is to be a multiple of 9.
Then do the same for the $12+x-y$ must be divisible by $11$: if $x$ is 1, then $y$ must be $2$, and so on.
Then see which pairs are in both tables.
Answer: $30+x+y$ must be a multiple of 9 which leads to:$$30+x+y=9a$$$$x+y=9a-30\tag{1}$$
$12+x-y$ must be a multiple of 11 which leads to:$$12+x-y=11b$$$$1+x-y=11c\text{ where c=b-1}\tag{2}$$
the biggest difference between two digits is 9 therefore the maximum value of $x-y$ is 9 which leads to (from (2)):$$11c\le1+9\le10$$therefore $c=0$ which leads to:$$y=x+1\tag{3}$$substitute (3) into (1) to get:$$2x+1=9a-30$$$$2x=9a-31$$Hopefully you can solve from here.
Answer: You are wrong considering $x,y\in\left[0,6\right]$.
$30+x+y$ is divisible by $9$. That's correct, but it may be $30+x+y=36$ or $30+x+y=45$. It cannot be $30+x+y=54$, since the greatest value of $\left(x+y\right)$ is $9+9=18$.
From these two options you have $x+y=6$ or $x+y=15$. Remember this.
From the division by $11$, you achieved that $12+x-y$ must be divisible by $11$. That's also correct.
Note that you cannot get $12+x-y=22$, since the maximum value $\left(x-y\right)$ can reach is $9-0=9$, so you have to use negative values of $\left(x-y\right)$ like $12+x-y=11$, i.e, $x-y=-1$. It means $x$ and $y$ are two consecutive numbers where $y=x+1$; it also means that one of them is odd and the other is even, because of this, there is no way $x+y=6$, it must be $x+y=15$.
Now, you have a linear system
$$\begin{cases}x+y=15\\x-y=-1\end{cases}$$
Solve this and you will have your answer.
Answer: I do not follow "So, the only numbers $x$ and $y$ that make $30+x+y$ divisible by $9$ are..." and I think that is the source of trouble.
If $9$ divides $30+x+y$, then either $30+x+y=36$ or $30+x+y=45$.
If $11$ divides $12+x-y$, then for sure $12+x-y=11$.
Add one of the first two equations to the second. Either $42+2x=47$ or $42+2x=56$. The first can't be, since $47$ is odd. So it's the second situation, and $x=7$. Then $y$ must be $8$.
Answer: Notice $495 = 5\times 99$. It will be easier to look at everything modulo $99$.
$$0 \equiv \overline{273x49y5}
\equiv 27 + \overline{3x} + 49 + \overline{y5}
\equiv \overline{yx} + 111
\equiv \overline{yx} + 12 \pmod{99}
$$
This leads to $\overline{yx} = 87 \implies (x,y) = (7,8)$.