Why is $\sum_{d\mid p^r}\phi(d)=\sum_{h=0}^r\phi(p^h)$

Question: $\sum_{d\mid p^r}\phi(d)=\sum_{h=0}^r\phi(p^h)$
I read this relation in a proof, but can't work out why it is the case.
Thanks in advance for the help.
Answer: Assuming that $p$ is a prime number (which is reasonable and necessary for this to be true), the set of divisors of $p^r$ is $1, p, p^2, \dots, p^r$. So summing over all $d \mid p^r$ and summing over $p^i$ from $i=0$ to $r$ is the exact same thing.
(The $\phi$ is tangential for this, it would be true for any function whatsoever.)
Answer: It is obvious since $\{ \mbox{divisors of } p^r\} = \{ 1, p, \dots, p^r \}$, so roughly speaking you have
$$\sum_{d|p^r} f(d)= \sum_{j=0}^rf(p^j) = f(1) + f(p) + \cdots + f(p^r)$$
whenever $f$ is any function.


Git merge driver is beeing executed without a conflict on some files

Question: From time to time our custom merge driver is executed on files that did not conflict (They don't have any conflicts if you remove the merge driver, so in the merge driver you can just do a git merge-file and everything works great).
We are using Git 2.5.1
My perception of Git merge drivers was that they are only executed for conflicting files?
The .gitattributes:
* merge=keeplocalversion

The .gitconfig entry:
[merge "keeplocalversion"]
        name = "Keep local pom version"
        driver = /home/atlstash/pommergetreiber/pommergedriver.sh %A %B %O %P

pommergedriver.sh:
#!/bin/bash
echo "==== STARTING MERGE DRIVER ===="

echo $1
echo $2
echo $3
echo $4

# CURRENT = destination branch (checked out branch)
CURRENT=$1
# OTHER = source branch
OTHER=$2
# ANCESTOR = common parent commit
ANCESTOR=$3

FULL_BRANCH_NAME="$(git symbolic-ref HEAD )"
if [ "$?" -ne "0" ]; then
        echo "Detecting branch name failed!"
        exit 1
fi
DESTINATION_BRANCH="$(echo $FULL_BRANCH_NAME | sed 's%refs/heads/%%')"
if [ "$?" -ne "0" ]; then
        echo "Transforming destination branch failed!"
        exit 1
fi

DESTINATION_BRANCH="$(echo $FULL_BRANCH_NAME | sed 's%refs/heads/%%')"
git merge-file --diff3 --marker-size=25 -L $DESTINATION_BRANCH -L "COMMON BASE" -L "SOURCE BRANCH" "${CURRENT}" "${ANCESTOR}" "${OTHER}"

What leads to the following behaviour:
<stash>@<machine>:<project>> git merge origin/feature/<branch>
==== STARTING MERGE DRIVER ====
.merge_file_bm9SCU
.merge_file_MU9B7n
.merge_file_IsOa8q
<project>/...BusinessLogicPositionImpl.java
==== STARTING MERGE DRIVER ====
.merge_file_RjSwel
.merge_file_WvT0MO
.merge_file_baS3FR
<project>/...AbstimmungRestServiceImpl.java
==== STARTING MERGE DRIVER ====
.merge_file_ZWlr2L
.merge_file_22faFf
.merge_file_14SIpi
<project>/...AbstimmungRestService.java
==== STARTING MERGE DRIVER ====
.merge_file_yd2o1c
.merge_file_zf9wHG
.merge_file_5UohlJ
<project>/...WPDAbstimmposten.java
Auto-merging <project>/...BusinessLogicPositionImpl.java
CONFLICT (content): Merge conflict in <project>/...BusinessLogicPositionImpl.java
Auto-merging <project>/...AbstimmungRestServiceImpl.java
CONFLICT (content): Merge conflict in <project>/...AbstimmungRestServiceImpl.java
Auto-merging <project>/...AbstimmungRestService.java
Auto-merging <project>/...WPDAbstimmposten.java
Automatic merge failed; fix conflicts and then commit the result.

The two conflicting files have real conflicts, the two merged files have not.
Why is the merge driver beeing executed for these two files?
Answer: Custom merge drivers are run whenever a 3-way merge is needed, i.e. whenever a file has changed in both merge parents since the merge base. If you only want to run your logic in case of conflicts, you can call git merge-file -p and (if the exit code is 0) overwrite $1 with the result or (if the exit code is not 0) run your special conflict resolution logic.
Comment: @BlackEye, that definition is correct. It is just that custom merge drivers aren't only run for conflicts.
Comment: So it's the definition of a conflict, that was misleading for me.

I always thought a conflict is only when the automatic merge on a file failed.
Comment: What would the commandline for his driver look like then in this instance? `git merge-file -p %A %O %B || /home/atlstash/pommergetreiber/pommergedriver.sh %A %B %O %P`?
Comment: To answer my question (I think), it looks like `git merge-file -p %A %O %B > /dev/null && git merge-file %A %O %B || /home/atlstash/pommergetreiber/pommergedriver.sh %A %B %O %P` would do what I want.


Generalizing Bayesian methods by assuming a "distribution of distributions" instead of a prior

Question: Bayesian methods assume a prior distribution with several hyperparameters. Unfortunately, this is asymptotically incorrect, because distributions in the real world are never exact. For example, the output of flipping a coin doesn't have a Bernoulli distribution, because it may stand on its side; the measured weight distribution of people within a certain can't be normal, because numbers from a normal distribution are "almost surely" irrational.
I propose to assume a distribution of distributions instead of a prior distribution, and then to update the distribution of distributions with sample data as usual. This is a generalized Bayesian method since I'm essentially using $\aleph$ hyperparameters. I suppose doing so would result in an asymptotically correct inference method.
However, applying this method is nontrivial for me. I can't even figure out what should a "distribution of distributions" look like, and updating this distribution is presumably harder. Is there any prior work on this or a similar method?
Comment: This is called Bayesian non-parametrics.
Comment: [Nonparametric Bayes on this site](https://stats.stackexchange.com/search?q=nonparam*+baye*+answers%3A1)
Answer: This is called nonparametric bayes, see nonparametric-bayes. For a gentle introduction, see the text Bayesian Nonparametric Data Analysis (Springer Series in Statistics).
A similar question was Books for learning non parametric Bayesian model.


OpenCV trackbar performance in OSX

Question: I've just noticed that performance of openCV is drastically slowed down when a trackbar is present in a window with changing image from camera or a movie frame. What could be done resolve this issue?
Answer: The solution to that is to move trackbars to a separate window. For me on OSX the performance increased 4.7 times (from 3 FPS up to 14). I don't know if it works like this always or it's just like that on my computer but I haven't seen such a clue anywhere before so I decided to share.
string title = "My window";
int p = 2;

// Create a different window for controls
namedWindow(title + " - controls");
// I show an image once just to resize the window
imshow(title + " - controls", Mat::zeros(1, 500, CV_8UC1));
createTrackbar("Parameter", title + " - controls", &p, 3);

// Create a different window for actual image
namedWindow(title);
while (!done) {
    // Do some calculations
    flip(image, image, p);
    imshow(title, image);
}

Comment: additional benefit, that you now can resize it without affecting the trackbar usabilty
Answer: I also encountered the same problem in OSX-10.9.
And I have resolved the issue in the following ways:
port variants opencv
sudo port install opencv +qt4 +tbb +eigen +opencl

important option is "+qt4" only, the other options are extra.
OpenCV support Qt for GUI backend. And I suspect the cause of the problem is in the implementation of the default GUI backend.
I was able to virtually eliminates the problem by re-build OpenCV library with Qt support and re-install(update).
Answer: For me, this seemed to be an issue with the Anaconda distribution of OpenCV.
Installing OpenCV with pip fixed my performance issues.
Answer: Try to tune
cv2.waitKey(value)

I used cv2.waitKey(100) and works smoothly

OpenCV trackbar performance in OSX


List all node titles to better iterate on a list of names

Question: I have a content type called Country and I have to verify what countries already exists in db and save the missing ones, comparing to a variable with all countries ($country_list). I am having trouble accessing countries names of my nodes, that are specified as the content type title.
  $country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];
  $nodes = node_load_multiple(array(), array('type' => 'country_profile'));
  $nodes_name = node_title_list($nodes);

  foreach ($country_list as $country_name) {
    if (!in_array($nodes_name, $nodes)) {
      // should create new node
    } else {
      // shouldn't do anything
    }
  }

The problem is, when i get the node_title_list() it doesn't return the 'raw title' (see output below)
Output:
    Array
(
    [#theme] => item_list__node
    [#items] => Array
        (
            [0] => Tanzania
            [1] => Mexico
        )

    [#title] => 1
)

How can i do that, so that the output of this list is
Array
        (
            [0] => "Tanzania"
            [1] => "Mexico"
        )

Comment: Pass the array results through the PHP [strip_tags](https://www.w3schools.com/php/func_string_strip_tags.asp) function.
Answer: If you just need to create the nodes that don't have a specific title (which I guess it's just a country name), you don't need to use node_title_list(), whose purpose is rendering a list of node titles as links. Just load the nodes and check which titles aren't already used.
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}

Even better, load those nodes whose title is equal to one of the country names you already have.
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('title', $country_list)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}

Comment: Thanks, that makes sense. The only problem is, it only falls in the create nodes if the list is empty, what if just some of the countries were already created?
Comment: The code in the answer removes from the country list the nodes that already exist with that title. It's done from `foreach ($nodes as $node) { unset($country_list[$node->title]); }`. It also avoids to create nodes if the country list is empty: `if (!empty($country_list)) { /* ... */ }`.
Comment: (To be correct, the code should have used `array_flip()`.)
Comment: Guess i wasn't paying enough attention, i am sorry. Tried using the code and worked! Tyvm. Used array_flip before if(isset...)


Statistica Significane of the Slope Coefficient

Question: Can someone please help me with this?
Consider that you are examining the relationship between the height of children and their parents. You decide to collect data from 110 college students, and estimate the following relationship :
(hat) Studenth = 19.6 + 0.73 × Midparh
with R2 = 0.45, the Standard Error of the Regression (SER) = 2.0, standard error for the intercept is (7.2) and for the slope is (0.10), where StudentHeight is the height of students in inches, and AveragePaentHeight is the average of the parental heights. Both variables were adjusted so that the average female height was equal to the average male height.
How do you set for the statistical significance of the slope coefficient?
Comment: how do you est***
Answer: Hints:
$H_0: \beta_1=0$
$H_1:\beta_1 >0$
The test-value is t-distributed, if $H_0$ is true.
$t_{emp}=\frac{b_1}{s_{B1}}=\frac{0.7}{0.1}=7$
The critical value is $t_c=t_{(\alpha,n-2)}$. It is a one-sided t-test.
If $t_{emp}>t_c$, the Null-Hypothesis should be rejected at a significance level of $\alpha$. Otherwise the Null-Hypothesis has to be not rejected.
Comment: thank you! Where can I find the table for the critical value, and further information for which one I should select.
Comment: As I said it is a one-tailed test. $\alpha$ you have to choose. And $n-2=100-2$ are the degrees of freedom (df). A table can be found here:http://easycalculation.com/statistics/t-distribution-critical-value-table.php


What does one slash through a half note stem AND 4 dots above it mean?

Question: In a version of "Overture to Lucio Silla" by Mozart, half of the viola part of the song has half notes with a SINGLE slash through it, but 4 dots on the base part of every not (The circular part). Right before it in many cases, there are 4 eighth notes in which all have a single dot for staccato.
Thank you for your consideration.
Comment: Is [this](http://imslp.org/wiki/Special:ReverseLookup/111551) the piece in question? Can you clarify what you mean by "4 dots on the base part of every not[e]", and provide a specific example from that score?
Answer: The slash symbol through the stem of a note is called a "tremolo" notation, and signals that the same pitch or chord is to be repeated at a certain rate. In your example, it is a shorthand for eighth notes. The half note signifies the length of time the notes will fill (in this case two beats). The stem plus the dots shows the division.
Here is a good example of how this can be useful practically, from a flute method book.
Answer: As Reina pointed out, the slash is a kind of an abbreviated beam, indicating, that the note has to be played as repeated eigth notes (two slashes/beams would indicate 16th etc.). The dots are most likely the staccato dots for the resulting four eights, so nothing changes in comparison to the previous bars.
Answer: There is a difference between a single slash and the several slashes for a tremolo.  A half note with a slash through it in this case with the four dots underneath, is a shorthand meaning that you play four notes for each one written.  So if you have half notes written and four dots then you play eighth notes.


Use selected NID from Entity Reference field to populate second Entity Reference field

Question: I have three content types:

organization profile
internship posting
hours submission

The 'hours submission' content type has two entity reference fields:

Entity reference for 'organization profile' nodes
Entity reference for 'job posting' nodes

I'd like to pass the NID from the first entity reference such that the second entity reference is filtered (only shows nodes that are associated with that NID).
The 'job posting' content type is tied to an 'organization profile' via an entity reference field.
Any help or guidance would be appreciated.
Answer: My solution is to:

Pre-populate and disable the first entity reference field with a node ID
Add an extra path component with the same nid and have the second field use an entity reference view with default: Path Component 4

So the URL looks like /node/add/hacky/123?field_solution=123.
While hacky, it has uses, especially if you want to filter fields that don't have a connection. In that case the URL could be /node/add/hacky/123/456?field_solution=789.
Comment: Thanks for sharing this solution! I've actually implemented this approach into the approach that I shared (first NID is pre-populated via url params) to simplify the UI.
Answer: The Dynamic Dependent Fields (DDF) module does exactly what I described above.
The module introduces a new view mode: "Filter by an entity reference view with dynamic arguments". Then you can filter the entity reference view you set up with the value from a field in the entity.
In the Entity Reference View, use contextual filters to filter the results.
For example, I added the NID (provided by content ID) as a contextual filter.


Prevent backspacing HTML in an iFrame.

Question: I am using an iFrame as a text editor and want to ensure that the first part of the body is always a p tag. As such, I have it set so when users first click on the body it will insert

This works, unless the user holds down the backspace button. Once the user runs out of plaintext to backspace, it removes the tags above.
I have captured the event for backspace, but how can I prevent the users from removing the paragraph tags?
Comment: It's not navigation that I am trying to avoid, its backspacing away HTML.
Comment: Ah ..my bad. Mind if I ask what the intention of keeping it there is? Is it just to keep some kind of space there for aesthetic reasons. or is because you want to pass that value back?
Comment: It normalizes the way return works on all browsers, so they create a new p rather than br or div.
Comment: It guess my answer didn't help any. I would like to still help out and work with you to brainstorm ideas. It could be a learning experience for me too. Do you have a github repo or a jsbin/jsfiddle link to provide code samples from your project?
Comment: It helped, only unfortunately there were still ways to break it. I ended up just scrapping the idea and taking another route (Dealing with browser inconsistencies server side)
Answer: I got 11 options (I'm assuming you are using jQuery).
First, capture the keydown event, and if the value is equal to the default value, prevent the action. This will probably be inside to source html of the iframe.

$('#editor').unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;
    if (event.keyCode === 8 && $('#editor').html() === '

'){

      event.preventDefault();
    }
});

Option two: just make the element that's editable a div instead.
I prefer to avoid the use of an iframe. They make things needlessly complicated (imo).

<!DOCTYPE html>

<input id="showContentBtn" type="button" value="Show Content">

Added a button in case there was some requirement to get the value for the content and keep those elements in it.
Option 3: If it needs to be inside the iframe, just set url for the above as the src for the iframe.

Edit Frame

I hope that this will give you a few ideas you can work with inside your project.

Prevent backspacing HTML in an iFrame.


What distribution should I use to model bounded count data (that also feels a bit like a proportion)?

Question: I am trying to determine the correct model for my data. I want to model the effect of two categorical independent variables (and their interaction) on my outcome variable. I am using SAS (proc genmod, probably).
The outcome variable can range from 0-6 and is the count of items in a sample of 6 with a particular feature. I do not think a Poisson model is appropriate because of the bounds of the count.
Consider, for example, an individual selecting a sample of 6 pieces of fruit from a basket of apples and oranges, with a goal to select a representative sample. I want to model the number of apples selected. I'm not sure if the goal is relevant for the model determination, but it seems like it should be relevant: there is a normative response of 2.4 apples (obviously, the sample is discrete, but this is what I'd expect on average), based on the proportion of apples in the basket (2/5).
What distribution should I use to model this outcome? I have ruled out normal (failed Shapiro-Wilk test for normality) and I think I should also rule out Poisson (because of the bound between 0 and 6).
Answer: Sounds like a job for the binomial distribution, with 6 trials and a "success" probability that denotes the probability of selecting the feature of interest.
Answer: If your counts are bounded between 0 and 6 you my consider as a possible model the Binomial(6,$\theta$). This however, doesn't help in case your 'counts' are not integers.
If you have many non integer values, an option could be to divide everything by 6, which if I got it correctly, is the maximum observable value. In this way you would get values between 0 and 1 so you could apply a beta model. Comment below if you need more details.
Comment: Thank you! They are all integer values. However, my understanding is that for the binomial model all trials are independent. I don't think this is the case, since the sample is selected with the goal of being representative. (If you pull two apples out of the basket, you may be less likely to pick another apple than if you first pulled two oranges.) I don't have information about the order in which the sample was selected, only the final sample (N apples out of 6). Could you help me understand whether the binomial distribution would still be appropriate given this clarifying information?
Comment: what do you mean by representative sample? Could you explain exactly how the sampling is done? Are you sampling apples from a basket of 6 apples or what?
Comment: There are humans selecting 6 fruits from the basket to later test for quality. They want to select a "representative sample" (includes both apples and oranges, representing the contents of the basket) so that both fruits get tested for quality, but of course they are humans so they don't always do so. I am interested in modeling the factors that bias their sample selection.
Comment: how large is the basket? Does it only have apples and oranges or something else? Why the selection is biased and biased towards what?
Comment: also, are you trying to estimate nr.apples/nr.oranges in the population?
Comment: Thank you! No population estimate: I am interested in the (bias in) the selection of 6. In this study, I only have two different items in the basket.


Javascript Slickgrid timeout

Question: I'm using Slickgrid to display data on a html site. The user can choose a table and the columns.
The code works well, but one table contains around 30 columns and around 500000 rows. Now the script takes too long and I get a firefox javascript timeout.
I know, that i can use setTimeout(), but i don't know how to use in this function.
What can i do, to avoid the javascript timeout?
    function addRow(){
      for (var i=0;i<arrayRow.length;i++){
        var row ='{"id": "' + i + '", ';
        for (var j=0;j>arrayColumn.length;j++){
          row = row + '"' + arrayColumn[j] + '" : "' + array[j]+[i] + '",'
        }
        row = row.substr(0,row.length-1);
        row = row + '}';
        data[i]=JSON.parse(row);
      }
      if (i==arrayRow.length){
        dataView.setItems(data);
      }
    }

Edit1: I've updated my code, but now I get the error "too much recursion".
    i=0;
    function addRow(){
      if (i<arrayRow.length){
        var row ='{"id": "' + i + '", ';
        for (var j=0;j>arrayColumn.length;j++){
          row = row + '"' + arrayColumn[j] + '" : "' + array[j]+[i] + '",'
        }
        row = row.substr(0,row.length-1);
        row = row + '}';
        data[i]=JSON.parse(row);
        i++;
        if(i%100000==0){
          setTimeout(addRow,0);
        } else {
          addRow();
        }
      }
      if (i==arrayRow.length){
        dataView.setItems(data);
      }
    }

Comment: possible duplicate of [Prevent long running javascript from locking up browser](http://stackoverflow.com/questions/672732/prevent-long-running-javascript-from-locking-up-browser)
Answer: The timeout for script execution measure the time that took the execution of one method.
You need to separete "for" loop into several loops. For example you can make a method that add 100000 rows and call it with settimeout 5 times
Maybe it should be something like that:
var iFirstRow = 0;
funtion AddRows( _iFirstRow, _nRowsToAdd )
{
   ..implementation of adding nRows
   iFirstRow = iFirstRow  + nRowsToAdd;

   if ( There is rows to add )
   {
      Call AddRows via timeout
   }
   else
   {
      ..its ready
   }
}

Javascript Slickgrid timeout


Special character not displaying as expected

Question: I have the following simple HTML page:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        méywe

When displaying it in Chrome or Firefox (I did not test other browsers), I see the following:
m�ywe
What did I miss? The html file is saved in UTF-8 encoding. The server is Apache. My machine is Windows 7 pro. The text editor is UltraEdit.
Thanks!
Update
Initially, I used UltraEdit for editing this html file and I got the problem. Based on cmbuckley's input and install of Notepad++ (from Heatmanofurioso's suggestion), I thought about the possibility of my file being corrupt somehow (even though it looks fine in both UltraEdit and Notepad). So I saved my file with Notepad in utf-8 encoding. Still saw the problem (maybe due to cache???). Then I used UltraEdit to save it again. See the page in the browser and the problem is gone.
Lesson Learned
Have two text editors if that that is your tool, and try the different one if you see unexplainable problem. No tool is perfect, even though you use one everyday. In my case, Notepad++ fixed the utf8 issue with my file that UltraEdit somehow failed.
Thanks to folks for helping!!!
Comment: Just to coment on the part that you showed great interest in trying to solve your problem. And made an update in the end with the answers you achieved and how you got them. Not many people do that, and if i could upvote your question more, i would. i don't see that kind of interest much these days. Awessome!
Comment: What is the encoding that the browsers render the page as? I know it should be UTF-8, but it also shouldn't be causing troubles either....
Comment: Are you sure it's in UTF-8? What does `hexdump -C file.html` show? The bytes for `méywe` should be `6d c3 a9 79 77 65`, where `c3 a9` is `é`.
Comment: may be thats because, the font is not supported by the browser.
Comment: If the font in use doesn't have the character in it the browser uses that character as a placeholder. What font are you using?
Comment: isherwood, I did not add any font specs. Browsers use their defaults. In Chrome, I found out it is Times New Roman under Computed style. Cannot find this info in Firefox.
Comment: cmbuckley, I dont have hexdump on my machine. I use Windows pro 7.
Comment: I think you mean "Lesson learned: Use a real editor which gives you  complete control over this, and learn to use it properly." #oneEmacsToBindThem
Comment: I was having a similar problem. We use `html-pdf` nodeJS package to print invoices from the HTML Templates. After deploying the module on oure Ubuntu server, the generated invoice PDF did not display the Indian Language text properly. Solution was to install the fonts on the server itself and then restart the processes. `fonts-indic` was the package that we installed. Hope somebody finds this useful.
Answer: 1 - Replace your
<meta charset="utf-8">

with
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

2 - Check if your HTML Editor's encoding is in UTF8. Usually this option is found on the tabs on the top of the program, like in Notepad++.
3 - Check if your browser is compatible with your font, if you're somehow importing a font. Or try and add a css to set your fonts to a default/generally accepted one like
body
{
    font-family: "Times New Roman", Times, serif;
}

Hope it helps :)
Comment: Just tried the style and meta change. None is working. Somebody else downvoted. Thanks for chiming in!
Comment: Just installed Notepad++. Double-checked the encoding to make it utf8. Still got the same issue.
Comment: This is a really long shot. But try fully cleaning yoour browsers cache.
Comment: Why downvote my answer?
At least explain why, please
Comment: Good insight on changing the editor's encoding. I inherited a legacy site that used ISO-8859-1 and switching to UTF-8 fixed the problem. Thanks for the answer!
Comment: Option 2 worked for me. In my case i'm using MobaXterm and the built-in editor was using ANSI for some reason.
Answer: The reason for having saved the file with Windows-1252 encoding (most likely) instead of UTF-8 encoding resulting in getting the non-ASCII character displayed wrong in the browsers was missing knowledge about UTF-8 detection by UltraEdit and perhaps also appropriate UTF-8 configuration.
How currently latest version 22.10 of UltraEdit detects UTF-8 encoding is explained in detail in user-to-user forum topic UTF-8 not recognized, largish file. This forum topic contains also recommendations on how to configure UltraEdit best for HTML writers who use mainly UTF-8 encoding for all HTML files. The UTF-8 detection was greatly improved with UltraEdit v24.00 which detects UTF-8 encoded characters also on in very large files on scrolling to a block containing a UTF-8 encoded character.
Unfortunately the regular expression search used by currently latest UltraEdit v22.10 and previous versions to detect a UTF-8 HTML character set declaration does not work for short HTML5 variant as reported in forum topic Short UTF-8 charset declaration in HTML5 header. The reason is the double quote character between charset= and utf-8. I reported this by email to IDM Computer Solutions, Inc. as the referenced topic was created with the suggestion to make the small change in the regular expression to detect also short HTML5 UTF-8 declaration. The UTF-8 detection was updated later by the developers of UltraEdit for UE v24.00 and UES v17.00 as a post on referenced forum topic explains in detail.
However, when an HTML5 file is declared as UTF-8 encoded, but UltraEdit loaded it as ANSI file, the user can see the wrong loading in the status bar at bottom of main window. A small (less than 64 KB) UTF-8 encoded HTML file should result in getting

either U8- and line terminator type (DOS/UNIX/MAC) displayed for users of UE < v19.00 or when using basic status bar in later versions of UE
or UTF-8 selected in encoding selector in status bar for users of UE v19.00 or later versions not using basic status bar.

If this is not the case, the UltraEdit user can use

Save As from menu File and select UTF-8 - NO BOM for Encoding (Windows Vista or later) respectively Format (Windows 2000/XP) to convert the file from ANSI to UTF-8 without byte order mark, or
ASCII to UTF-8 (Unicode editing) from submenu Conversions in menu File to convert the file from ASCII/ANSI to UTF-8 without an immediate save, or
select Unicode - UTF-8 via encoding selector in status bar (UE v19.00 or later only) resulting also in an immediate conversion from ASCII/ANSI to UTF-8 and enabling Unicode editing.

For the last two options the UTF-8 BOM settings at Advanced - Settings or Configuration - File Handling - Save determine saving the file without or with byte order mark on next save.
Once the word méywe is saved into the file using UTF-8 encoding resulting in byte stream 6D C3 A9 79 77 65 (hexadecimal) which would be displayed as méywe when UTF-8 encoded file is opened in ASCII/ANSI mode (option in File - Open dialog) using Windows-1252 as code page, UltraEdit detects this file on next opening automatically as UTF-8 encoded file although <meta charset="utf-8"> is not recognized because there is now at least one UTF-8 encoded character in the first 64 KB of the file.
To answer the question:

What did I miss?

You missed to save the file as UTF-8 encoded file after having it opened or created as ANSI file (or more precise single byte per character encoded text file using a code page) and having it declared as UTF-8 encoded. This is a common problem of many users writing into an HTML file
<meta charset="utf-8">

or
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

or
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

or into an XML file
<?xml version="1.0" encoding="UTF-8"?>

or
<?xml version="1.0" encoding='utf-8'?>

and other variations depending on usage of ' or " and writing either UTF-8 or utf-8 (and other spellings) without really knowing what this string means for the applications interpreting the bytes of the file.
What's the best default new file format? contains lots of useful information and links to web pages with useful information about text encoding, which one to use for which file types and how to configure UltraEdit accordingly.
Answer: Check and see if the server is sending a charset in the Content-type header. The encoding specified in that will take precedence over what you specify with the meta element.
Comment: This was a lead for me, in 2020's Chrome Inspect I see `"Content-Type: text/html; charset=ISO-8859-1"`. I can only imagine this is an old server that doesn't support utf8 or something..
Answer: Changing font-family to Calibri (or any other generally accepted font) worked for me.
Example:
# My_Text

Answer: I am using MS access accdb database and PHP. It had problem in displaying the "±" character . It was displaying "�".
I added the following line in PHP at the beginning  to get it right. My problem is solved now.
    header('Content-type: text/html; charset=ASCII');

Another method is to use mb_convert_encoding($row,'UTF-8','ASCII' );
The header declaration is not required.
Answer: In my case I converted the special character to decimal NCR and it worked. I have to do this because using meta tag do not work and I do not want to change my font.
There are many online unicode to decimal or hex converter.
Χαίρετε -> Χαίρετε

Answer: save AS HTML page, click drop down to save with encoding, select the option with UTF-8
enter image description here
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Replace meta charset="utf-8" with meta http-equiv="Content-Type" content="text/html; charset=utf-8". Maybe it will help.
Otherwise, what is your font?
Comment: tried this solution before. just tried it again. none is working.
Comment: No, the current charset declaration is valid HTML5 and recognised by all browsers.


Fechar o teclado IOS ao clicar confirmar

Question: como faço para que o teclado suma quando eu clicar em um botão confirmando aquele nome que esta no textbox?
Eu quero que quando eu clicar no botao confirmar jogador o teclado suma, pois ele continua aparecendo cortando a metade da tela onde está o jogo
Answer: Como você não pressiona o return do teclado no campo, você não tem o textField em que ocorreu o evento. Logo você precisa dizer que a view não está mais sendo editada, da seguinte maneira:
self.view.endEditing(true)

Outra maneira de fazer isso, quando você conhece o campo que foi editado (normalmente quando se tem apenas um na tela você pode fazer isso), seria:
txtName.resignFirstResponder()

Onde txtName é o nome do seu textField.
Comment: Funcionou perfeitamente!

Muito obrigado!


Relation between the angles of two projectiles landing in the same spot

Question: Given that two projectiles are fired at the same velocity, from the same spot, and land at the same point following different trajectories, how can I find the difference between the two angles of projection and the times taken for the projectiles to land?
EDIT: Not a duplicate since this one involves two projectiles and two different angles rather than trying to find one unique one.
Answer: The equations of motion are
$$\left\{\begin{array}{rcl}x(t) &=& v t\cos(\theta)\\y(t)&=&vt\sin(\theta)-\frac{1}{2}gt^2\end{array}\right. $$
hence the projectile travels for a time equal to $\frac{2v\sin\theta}{g}$, landing at a point whose distance from the origin is
$$ (v\cos\theta)\cdot\frac{2v\sin\theta}{g} = \frac{v^2}{g}\,\sin(2\theta) $$
and if two different projectiles land at the same point, $\sin(2\theta_1)=\sin(2\theta_2)$ holds, from which $\theta_1=\theta_2$ or $\theta_1+\theta_2=90^\circ$.
Answer: Horizantal range = vvsin(2θ)
From this we get that sum of the two angles will have to be 90 degrees.
Time = {2vsin(θ)}/g
From this, the ratio of the times will be tanθ.
Comment: Your redaction is very very allusive. You should be more explicit ; for example $\sin(2\theta_1)=\sin(2\theta_2)$ and $\theta_1 \neq 2\theta_2$ implies $2\theta_2=\pi-2\theta_1 \ \iff \ \theta_1+\theta_2=\pi/2$, etc.
Answer: Re: angles. Shreyash seems right. Consider: there's only one possible trajectory for a maximum range shot, 45deg. there are a pair of possibilities for a shot of 0 range, one cannon fires straight up (90 deg) and the other fires along the ground plane (0 deg). Intuitively, the relation should hold for intermediate pairs of ranges: that the sum of the cannon angles will = 90deg. The same relation would hold of the incoming trajectories at the target point.


SSH Lockout after failed login attempts

Question: I have an Ubuntu Server for my git repositories and other stuff. Sometimes someone trying to hack it (I think it's ok for servers) and after few failed login attempts SSH is locking out. I mean no one can do anything via SSH for 5 minutes or so. For example - "git pull" ends with "Connection timed out".
Since I'm not a Linux guy I can't figure out where I can change lockout time. I found this in the /etc/pam.d/login
auth optional pam_faildelay.so delay=3000000
But this only 3 seconds delay after single failed attempt.
I didn't find any mentions of "tally" in /etc/pam.d. What else could it be?
Comment: Sounds like fail2ban or something similar is active.
Comment: /etc/fail2ban/jail.conf and add the IP you want "whitelisted" under "ignoreip"
Answer: @Orphans helped me with this hint:

/etc/fail2ban/jail.conf and add the IP you want "whitelisted" under "ignoreip"

SSH Lockout after failed login attempts


Must a countable disjoint union of closed balls in $\mathbb{R}^n$ with positive radius be disconnected?

Question: A disjoint union of open balls is of course disconnected. Here it is proved that a locally compact, connected, Hausdorff space is not a countable disjoint union of compact subsets, so a countable disjoint union of closed balls in $\mathbb{R}^n$ can't be connected and locally compact (hence cannot be open or closed connected), which rules out the connected sets for $n=1$. But what if we just ask this disjoint union to be connected?
Please forgive me if this question turns out to be trivial. Thank you in advance for any help.
Edit. Actually I should have asked about something more general, like

Is there a connected subset $\mathbb{R}^n$ that can be written as a countable disjoint union of closed sets in $\mathbb{R}^n$? If not, is there a connected subset $\mathbb{R}^n$ that can be written as a countable disjoint union of closed sets in the subspace topology?

And the answer to the second question above is still negative for $n=1$, or for open subsets of $\mathbb{R}^n$ (the link requires also local connectedness which is satisfied for open connected sets). However, I will keep the question as it was given the discussion already presented.
Edit 2. A connected subset of $\mathbb{R}^3$ as a countable disjoint union of closed sets has be constructed in the existing answer. I would still be interested in the closed ball case: Must a countable disjoint union of closed balls in $\mathbb{R}^n$ not be connected?
Comment: @Joseph_Kopp But each closed ball is not necessarily an open subset of the union, as an  infinite union of closed sets is not necessarily closed.
Comment: But they will be open in their subspace topology, which is all that matters.
Comment: @Randall $\{0\}$ is not open in $\{0\}\cup\left\{\dfrac{1}{n}:n\in\mathbb{N}\right\}$, and this can be modified to be an example containing closed segments
Comment: Correct, and those also aren't closed intervals of positive radius.
Comment: You are correct in that there is a good question here.  Your concern is that the balls could converge in a strange way, in the same way we build the topologist's sine curve to make pathology happen.
Comment: @Randall If you like, $[-1,0]$ is not open in $[-1,0]\cup\left[\dfrac{1}{2},1\right]\cup\left[\dfrac{1}{4},\dfrac{1}{3}\right]\cup\cdots$.
Comment: Doesn't the disjoint part already kill it?
Comment: A connected space is defined as a topological space that cannot be represented as the union of 2 or more disjoint non-empty open subsets. So, by definition, the answer is pretty trivially yes.
Comment: @Randall Yes, in a counterexample every closed ball should be non open, which is quite strong.
Comment: The result follows from Sierpinski's theorem in the case $n=1$.  Any countable disjoint union of closed intervals in $\mathbb R$ is disconnected.  So you can edit your question to assume $n>1$.
Answer: Example of countable family of pairwise disjoint closed sets on a plane whose union is connected
Here is a relatively simple example. The other section has an older, more complicated example in $ℝ^3$.
Let $D = \{d_n : n=0,1,\dots\}$ be a dense subset of unit sphere with $d_n \neq d_m$. For each $n=1,2\dots$ define the line segment
$$
A_n = \{ λd_n : 2^{-n} ≤ λ ≤ 1 \},
$$
and $A_0 = \{ λd_0 : 0 ≤λ≤1 \}$.
Let $\text{Sun} = \bigcup_{n=0}^∞ A_n$. It is a union of closed, pairwise disjoint, connected sets. We show that $\text{Sun}$ is connected. Before proof, here is how $A_0,A_1 \dots, A_5$ might look like.

Proof. Let $U,V$ be open disjoint sets with $\text{Sun} = U \cup V$. Without loss of generality assume that $U$ contains  $0\in A_0$. Since $A_0$ is connected, it must be contained in $U$. It suffices to show that $A_1, A_2, \dots$ are in $U$ as well.
First, note that there is $N$ for which ball $B = B(0, 2^{-N})\cap A$ is contained in $U$. Consequently, for each $k>N$ an endpoint of $A_k$, namely $2^{-k}d_k$, is close enough to the origin to be contained in $B \subset U$. Hence, all $A_k$ with $k>N$ are in $U$ ($A_n$'s are connected).
It remains to show that $A_1, A_2, \dots, A_N$ are also in $U$. Pick $1≤t≤N$. By construction $d_t \in A_t$. Assume that this point sits in $V$. Then there would be a neighborhood of $d_t$ with no points in common with $U$. This is impossible because $U$ contains $\{d_k : k>N \} \subset D$ which is dense in the unit sphere since it's just $D$ with finitely many points thrown out. Hence $d_t$ belongs to $U$, and so $A_t$ is in $U$.
□
Note. Via the natural embedding, this will work in higher dimensions.
Edit. I have just found a construction of set with the same property in the literature: In the 1922 paper, Anna Mullkin presented perhaps the first example of such set. It's called Mullikin Nautilus and it is constructed by taking an infinite union of such polygonal chains:

See: Certain Theorems Relating to Plane Connected Point Sets.
Old example in $ℝ^3$
We construct a family  $\{A_n: n =0,1, \dots\}$ of pairwise disjoint, closed subsets of $ℝ^3$ whose union is connected.
First, let $A_0 =\{(0,t,0): t≤0\}$ be ray. For $n≥1$ set $A_n$ is made of a ray $\{(0,2^{-n},0) : t≤ 0\}$ and a certain polygonal chain. Here is a sketch of the projection of $A_0, A_1, \dots A_5$ to XY plane.

Important bits:

Each $A_n$ live on XY plane (the Z-coordinate is zero) except "bridge". Bridges make $A_n$'s pairwise disjoint.
Each $A_n$ is closed and connected.
For $n=1,2, \dots$ point $(0,2^{-n},0)$ and $(n,2^{-n},0)$ belong to $A_n$. Fix $n$, then for $t>n$ point of the form $x_{n,t} = (n,2^{-n}+2^{-t},0)$ belongs to $A_t$. Note $$x_{n,t}\stackrel{t→∞}→(n,2^{-n},0)\in A_n.$$ In the picture example with $n=2$.

This is all we need to know to prove that $A = \bigcup_n A_n$ is connected. At the end of the proof, we define $A_n$ for $n≥1$ at the end in detail. I will be glad for a verification!
Proof. Say $U,V$ are open (in the subspace topology) disjoint sets with $U\cup V=A$. We will show that one of them is empty. WLOG assume that $U$ contains the origin point $(0,0,0)$. Hence $U$ must contain $A_0$. Also, there must be some $N$ such that for $n≥N$ points $(0,2^{-n},0)$ are in $U$. Becasue each $A_n$ is connected, each $A_n$ with $n≥N$ is in $U$.
When $N=1$ set $U$ contains all $A_n$'s, that is $A\subset U$. So must be $V$ is empty as $U\cap V =∅$. Assume that $N>1$. We show that $U$ contains the remaing $A_{N-1}, A_{N-2}, \dots, A_2, A_1$. Pick any $k \in \{1,2, \dots, N-1\}$ and assume $A_k \subset V$. By construction point $x = (k, 2^{-k}, 0)$ sits in $A_k$. On the other hand, the sequence of points from $U$, namely $(x_{k,t})_{t=N}^{∞} = ((k, 2^{-k}+2^{t}, 0))_{t=N}^{∞}$ where  $x_{k,t}\in A_t \subset U$, conveges to $x\in A_k \subset V$. Hence $V$ will contain almost all points of this sequence. But all terms of the sequence are members of $U$. So  $U$ and $V$ will have infinitely many points in common! A contradiction with $U$ and $V$ being disjoint.
□

$A_1$ consist of:

Ray $\{(2^{-1},t,0): t≤0\}$.
A "bridge" made of a polygonal chain connecting three points$$(0,2^{-1},0), \quad (0,2^{-1},1), \quad (1,2^{-1},0).$$

For $n≥2$ let $A_n$ be a union of:

Ray $\{t, (2^{-n} ,0): t≤0\}$.
Line segment connecting $$(0,2^{-n},0),\quad (1,2^{-1}+2^{-n},0),$$ and for $k=1,2, \dots, n-2$ line segment connecting $$(k,2^{-k}+2^{-n},0),\quad (k+1,2^{-(k+1)}+2^{-n},0).$$
And a "bridge" made from polygonal chain connecting $$(n-1, 2^{-(n-1)}+2^{-n},0), \quad (n-1, 2^{-(n-1)}+2^{-n},1),\quad (n,2^{-n},0).$$
Comment: Excellent example and demonstration! Just a remark: The negative part of the example $\{(t,0,0):t\le 0\}$ and $\{(t,2^{-n},0):t\le 0\}$ for $n\in\mathbb{N}^*$ is not needed. I would simplify the proof as follows: Suppose that the union can be written as $U\cup V$, with $U$ and $V$ open. Each $A_k$ is connected, so it is entirely included in $U$ or in $V$. For any $k\in\mathbb{N}^*$, $A_k\subset U$ means that $A_n\subset U$ for all sufficiently large $n$, since $x_{k,n}\in A_n$ converges to a point in $A_k$ as $n\to\infty$. This implies that every $A_k$ lies in fact in the same open set.


gvim not operator in substitute command

Question: I've got a number of files that look like the one below:
HR0100001012010093001
EF0000120100930000000
HR0200001012010093001
EF0000120100930000000
HR0900001012010093001
EF000012010093000000
HR1000001012010093001
EF000012010093000000
HR1100001012010093001
text
EF000012010093000000
HR1200001012010093001
EF000012010093000000
HR1300001012010093001
EF000012010093000000
HR0100001012010093001
text
EF0000120100930000000
HR2000001012010093001
EF000012010093000000
HR2200001012010093001
EF000012010093000000

I'd like to strip off all the blocks starting with HRxx and ending with EF* except for those starting with HR01, i.e. I'd like to get the result below:
HR0100001012010093001
EF0000120100930000000
HR0100001012010093001
text
EF0000120100930000000

Using the command below:
:%s/HR01\_.\{-}EF.*$//g

I am able to DELETE the lines I'm searching for; as a final step, I'd like to use the "Not Operator" to reverse the result thus getting the lines I actually need. Unfortunately I don't understand how to do this.
Any help is greatly appreciated.
Thanks,
Francesco
Answer: Solution found:
%s/HR\(01\)\@!\_.\{-}EF.*$//g

gvim not operator in substitute command


Intermittent EMFILE, ENOTDIR, ENOENT errors during generation

Question: I'm running npx eleventy in a docker container without changes to the source and see intermittant errors.
I see these errors every now and then:

EMFILE: too many open files
ENOTDIR: not a directory
ENOENT: no such file or directory

Here's an example to reproduce the output:
$ while true ; do npx eleventy ; done
[11ty] Wrote 95 files in 1.42 seconds (14.9ms each, v2.0.1)
[11ty] Wrote 95 files in 1.71 seconds (18.0ms each, v2.0.1)
[11ty] Wrote 95 files in 1.55 seconds (16.3ms each, v2.0.1)
[11ty] Wrote 95 files in 2.01 seconds (21.2ms each, v2.0.1)
[11ty] Wrote 95 files in 1.47 seconds (15.5ms each, v2.0.1)
[11ty] Wrote 95 files in 1.45 seconds (15.3ms each, v2.0.1)
[11ty] Wrote 95 files in 1.62 seconds (17.1ms each, v2.0.1)
[11ty] Wrote 95 files in 1.73 seconds (18.2ms each, v2.0.1)
[11ty] Wrote 95 files in 1.78 seconds (18.7ms each, v2.0.1)
[11ty] Wrote 95 files in 1.52 seconds (16.0ms each, v2.0.1)
[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] EMFILE: too many open files, stat './src/DIR/index.md' (via Error)
[11ty]
[11ty] Original error stack trace: Error: EMFILE: too many open files, stat './src/DIR/index.md'
[11ty] Wrote 0 files in 1.53 seconds (v2.0.1)
[11ty] Wrote 95 files in 1.56 seconds (16.4ms each, v2.0.1)
[11ty] Wrote 95 files in 1.70 seconds (17.9ms each, v2.0.1)
[11ty] Wrote 95 files in 1.86 seconds (19.6ms each, v2.0.1)
[11ty] Wrote 95 files in 1.48 seconds (15.6ms each, v2.0.1)
[11ty] Wrote 95 files in 2.06 seconds (21.7ms each, v2.0.1)
[11ty] Wrote 95 files in 1.64 seconds (17.3ms each, v2.0.1)
[11ty] Wrote 95 files in 1.58 seconds (16.6ms each, v2.0.1)
[11ty] Wrote 95 files in 1.98 seconds (20.8ms each, v2.0.1)
[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] EMFILE: too many open files, stat './src/DIR/index.md' (via Error)
[11ty]
[11ty] Original error stack trace: Error: EMFILE: too many open files, stat './src/DIR/index.md'
[11ty] Wrote 0 files in 1.02 seconds (v2.0.1)
[11ty] Wrote 95 files in 1.52 seconds (16.0ms each, v2.0.1)
[11ty] Wrote 95 files in 1.60 seconds (16.8ms each, v2.0.1)
[11ty] Wrote 95 files in 1.45 seconds (15.3ms each, v2.0.1)
[11ty] Wrote 95 files in 1.53 seconds (16.1ms each, v2.0.1)
[11ty] Wrote 95 files in 1.48 seconds (15.6ms each, v2.0.1)
[11ty] Wrote 95 files in 1.57 seconds (16.5ms each, v2.0.1)
[11ty] Wrote 95 files in 1.57 seconds (16.5ms each, v2.0.1)
[11ty] Wrote 95 files in 2.01 seconds (21.2ms each, v2.0.1)
[11ty] Wrote 95 files in 1.39 seconds (14.6ms each, v2.0.1)
[11ty] Wrote 95 files in 2.00 seconds (21.1ms each, v2.0.1)
[11ty] Wrote 95 files in 1.55 seconds (16.3ms each, v2.0.1)
[11ty] Wrote 95 files in 1.52 seconds (16.0ms each, v2.0.1)
[11ty] Wrote 95 files in 1.49 seconds (15.7ms each, v2.0.1)
[11ty] Wrote 95 files in 1.56 seconds (16.4ms each, v2.0.1)
[11ty] Wrote 95 files in 2.07 seconds (21.8ms each, v2.0.1)
[11ty] Wrote 95 files in 1.62 seconds (17.1ms each, v2.0.1)
[11ty] Wrote 95 files in 1.65 seconds (17.4ms each, v2.0.1)
[11ty] Wrote 95 files in 1.76 seconds (18.5ms each, v2.0.1)
[11ty] Wrote 95 files in 1.48 seconds (15.6ms each, v2.0.1)
[11ty] Wrote 95 files in 1.86 seconds (19.6ms each, v2.0.1)
[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] EMFILE: too many open files, stat './src/DIR/index.md' (via Error)
[11ty]
[11ty] Original error stack trace: Error: EMFILE: too many open files, stat './src/DIR/index.md'
[11ty] Wrote 0 files in 1.12 seconds (v2.0.1)
[11ty] Wrote 95 files in 1.53 seconds (16.1ms each, v2.0.1)
[11ty] Wrote 95 files in 1.51 seconds (15.9ms each, v2.0.1)
[11ty] Wrote 95 files in 1.49 seconds (15.7ms each, v2.0.1)
[11ty] Wrote 95 files in 1.96 seconds (20.6ms each, v2.0.1)
[11ty] Wrote 95 files in 1.59 seconds (16.7ms each, v2.0.1)
[11ty] Wrote 95 files in 1.48 seconds (15.6ms each, v2.0.1)

The content is confidential, so I can't provide additional information with the current config. Before I start to create a reproducible image, I'd like to ask if there are any known root causes for this kind of non-deterministic behavior?
Thanks in advance!
Answer: Solved. The root cause was the default number of open files of the (macos) host:
$ ulimit -n
256

The limit can be increased per shell session by adding ulimit -n NNNNNN to your shell resource file (.zshrc, .bashrc, .profile, etc).
For a persistent fix, see Max open files per process.


Select rows before null value in each group

Question: How to subset or select rows before the occurrence of first null value in particular column for each group?
example
id sales
12   1
12   3
12
12   5
15   4
15   6
15   9
15
15   1

and select only
df sales
12  1
12  3
15  4
15  6
15  9

Answer: Using groupby with a custom function utilising pd.Series.isnull:
def index_filter(x):
    nulls = x.isnull()
    n = nulls[nulls].index[0] - 1
    return x.loc[:n]

res = df.groupby('id')['sales']\
        .apply(index_filter).astype(int)\
        .reset_index().drop('level_1', axis=1)

Alternatively, you can use a generator expression with next:
def index_filter(x):
    n = next((i for i, j in enumerate(x) if np.isnan(j)), len(x))
    return x.iloc[:n]

Result:
print(res)

   id  sales
0  12      1
1  12      3
2  15      4
3  15      6
4  15      9

Answer: One way would be to get the nulls, groupby on ID, take the cumsum so that all rows before the first null have count 0 and those at and after the first have count 1 or more, and then select those.  IOW:
In [19]: df.loc[df["sales"].isnull().groupby(df["id"]).cumsum() < 1]
Out[19]:
   id  sales
0  12    1.0
1  12    3.0
4  15    4.0
5  15    6.0
6  15    9.0

Comment: you're correct.  Thanks for the notifcation.  You've arrived at what my ahsnwer should have been. +1


How do I use my existing G Suite apps inside Squarespace?

Question: I am paying for a G Suite business plan. I have a domain, host, and emails set up already, and would like to use the G Suite apps inside my website builder (Squarespace).
But Squarespace does not let me do this without signing up to a new G Suite account through their platform. Their exact words are, "If you have G Suite through Google or another reseller, it isn't possible to link it to your Squarespace site".
So I tried looking at Google's other website builder partners like WordPress, Wix and Weebly for example. They all say the same thing.
WordPress: "If you would like to transfer your G Suite account to WordPress.com (G Suite Reseller), then this is unfortunately not possible at the moment"
WIX: "Currently, transferring your existing G Suite Account to Wix is not supported".
I could not find any documentation telling me that Weebly supports the transfer either.
All I want to do, is use the G Suite apps on my site without having to delete my current G Suite account and sign up to a new one. I have already paid the money for the subscription for my existing G Suite.
If I deleted my existing G Suite and signed up with a new G Suite account through the website builder, I'd have to delete the domain name, wait until it is available again, then re-purchase it. Essentially spending twice the money. I'd also have to figure out what to do with my emails because I read that after you delete them, you can't re-create  them. I'm sure I could migrate them over somehow but what a hassle. I have also paid for business cards that I'd have to re-print as well. I don't want to go down that pathway.
Surely you can use your G Suite account with a new website. Surely. But how?
And I'm not talking about just transfering the domain over, or chaning the MX records so I can use my email... I'm talking about everything. Integrating calendar for example in the website, using the files in google drive, basically managing everything through the website builder as if I had originally created the G Suite account in the website builder to begin with.
Is there anyone that can help me figure out a solution? I can't find information on this anywhere, I feel like I'm missing something really obvious.
I should also mention I am very new to G Suite and website builders.
Answer: You got your answer.. "If you have G Suite through Google or another reseller, it isn't possible to link it to your Squarespace site". I'm sure most platforms/resellers work this way.
Aside from deleting the account, and waiting, using 'embeddable code' on you website, like Add a Google calendar to your website is about your only option.


node js node-exec-promise.exec command to call retire.js through command line works but ends with an error

Question: Trying to run the command mentioned in sections below, it is intended to run retire.js on some javascript files/libraries and pipe the output in a json file. The command works and produces output in a json file but ends with an error.
When I try the same command directly by copy pasting the command in command line it works without an error.
I have tried the exexSync version and shelljs as well though get error in Shelljs as well. However, I am not able to understand what is causing the problem.
using node-exec-promise.exec :
exec('node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json').
                            then(function(retire_out){
                                console.log('Retire Command Success ');
                                console.log(' Retire_out Result  ',retire_out);
                                return retire_out;
                                }, function(err){
                                 console.error(err)
                            }

Using Shelljs:
   if (shell.exec('node
   C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json').code !== 0) {

    shell.echo('Error: Git commit failed');
    shell.exit(1);
  }

Expected Result is a Json file with known vulnerabilities found by retire.js, the file gets populated and it has valid json.
However, I get the following error in command line:
{ Error: Command failed: node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json

    at ChildProcess.exithandler (child_process.js:294:12)
    at ChildProcess.emit (events.js:189:13)
    at maybeClose (internal/child_process.js:970:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
  killed: false,
  code: 13,
  signal: null,
  cmd:
   'node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json' }

Comment: retire.js exits with exit code 13 (can be changed) when vulnerabilities are found - this is expected behaviour
Comment: @JaromandaX however it doesn't give this code when I run retire via command line.
Comment: And I think the command should not fail since vulnerabilities were found which is the purpose of retire.js.
Comment: I bet it does exit with exit code 13 - how are you testing for exit code on the command line? It's up to you to handle the exit code as required
Comment: by the way, running `retire` with an outputpath specified will mean that there will be no output except to the file specified - therefore, even if the error code wasn't 13, your code would still not get anything in `retire_out`
Comment: what you'll want to do is ... a) `exec('.....').catch(err => {check if exit code is 13, if not then throw err}).then(() => { read the output file if you want to display it here }).catch(err => { handle other errors here})`
Comment: @JaromandaX thank you, your first answer was a light-bulb,  I am checking for it via  a function of err but I think catch approach might be better. I will get back here once I get somewhere.
Comment: @JaromandaX how do I select your comment as an answer .
Comment: function execute_command(cmd,filename, outputpath)
    {
        return new Promise((resolve,reject)=>{
            spawn.exec(cmd, (err, stdout, stderr) => {
            }).on('exit', code => {
                console.log('final exit code is', (code));
                console.log(typeof(code));
                if(code === 13)

I did the above approach.
Comment: You can't - I haven't posted an answer - I can post one now if you like, it may help others in the future I guess
Comment: It will indeed. Thank you and I cannot up vote your answer since I am a new user and my reputation is very low at the moment.
Comment: You should be able to accept the answer (if it's correct)
Comment: By the way, the `node-exec-promise` "library" (it's like 20 lines of code, so ...) is flawed in that it only gives you access to `stderr` in the case of a non-zero exit code - it is extremely easy to write a "better" version of it - though, as I said, in this case it wouldn't make a difference since the JSON is written to a file, not stdout/stderr
Comment: Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.
Comment: I cannot accept the answer , I am a newbie :)
Comment: really? I thought you had to wait before accepting. Seriously, I don't know, never asked a question!
Answer: Because retire exits with an exitcode of 13 if there are vulnerabilities found, you'll want a .catch before any .then to "allow" exitcode 13.
Also, since you've specified --outputpath for retire, the output will NOT go to stdout, so you will need to read the outputfile in the .then code - also, since retire would return an "error" (13) - node-exec-promise doesn't even give you access to stdout/stderr in the err that is passed to the .catch code anyway!
The following is pseudo-code, since I'm not fully familiar with node-exec-promise:
exec('node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json')
.catch(err => {
    if (err.code !== 13) {
        throw err;
    }
})
.then(() => {
    // read the output file if you want to display it here
})
.catch(err => {
    //handle other errors here
});


Getting error while autowiring dataSource

Question: Am getting an error saying :
exception
javax.servlet.ServletException: Servlet.init() for servlet spring threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.labs.dao.LoginDao com.labs.controllers.LoginController.loginDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\Program Files\Apache Software Foundation\Tomcat 7.0\wtpwebapps\Annotated\WEB-INF\classes\com\labs\dao\LoginDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.labs.dao.LoginDao]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:160)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

And here is my controller
@Controller
public class LoginController {
    @Autowired
    private LoginDao loginDao;
    @RequestMapping(value="/login", method=RequestMethod.POST)
    public ModelAndView login(@ModelAttribute User user){
        if(loginDao.login(user))
            return new ModelAndView("success", "user", user);
        return new ModelAndView("failure");
    }
    public void setLoginDao(LoginDao loginDao) {
        this.loginDao = loginDao;
    }
    public LoginDao getLoginDao() {
        return loginDao;
    }

}

And MyDao
@Repository
public class LoginDao {
    @Autowired
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());

    public boolean login(User user){
        String name = jdbcTemplate.queryForObject("select name from users where name=? and password=?",new Object[]{user.getUserName(),user.getPassword()},String.class);
        if(!name.isEmpty())
            return true;
        return false;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    public DataSource getDataSource() {
        return dataSource;
    }
}

spring configuration is
<context:annotation-config/>
     <context:component-scan base-package="com.labs"/>

     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byName">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
        <property name="username" value="postgres"/>
        <property name="password" value="Raju"/>
     </bean>

     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"></property>
     </bean>

Comment: is com.labs base package for your controllers?
Comment: looks like its "com.labs.dao.LoginDao". you probably have config files or the dataSource config file is not called.
Answer: This line is the problem
private JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());

Instance variables are initialized before the constructor is called and before Spring has time to autowire any fields. In other words, dataSource is null and getDataSource() therefore returns null. JdbcTemplate throws an Exception if the DataSource argument is null.
Instead change your code to
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

@Autowired
public LoginDao(DataSource dataSource) {
    this.dataSource = dataSource;
    this.jdbcTemplate =  new JdbcTemplate(this.dataSource);
}

Comment: Thanq @SotiriosDelimanolis for ur time, I didn't added jdbc jar. After adding the jar it is working fine.
Comment: @Raju Consider upvoting (when you can) and/or accepting the answer if it helped.
Comment: Sure. But i am sorry,i didn't try the solution u gave me.Instead i put jdbcTemplate bean into xml file and then referred dataSource. Is it a best practice when we have annotations ?
Comment: @RajuMandala There is no best practice. Use XML or annotations to better suit your needs. Both are accepted. Do you understand why the error happened though?


Very slow disk performance on HP P410 with RAID1+0

Question: I have HP Microserver N54L, until recently i have used integrated software raid without problems.
I have 2x WD Black and 2x WD Red (non-pro) disks for my raid array. I also have SSD directly on the motherboard (not that it matters, just to get all facts straight).
I purchased HP P410 with 256MB memory back with a Battery Back Write Cache module.
I'm using esxi 5.1 and i have one windows virtual machine. In this windows machine i get terrible read speeds (only up to 40-60 MB/s) write speed is kinda OK (around 100MB/s) but still slower than when i used integrated raid.
For example this is copying a large file from raid to ssd http://img.hihi.si/Upload/vYbD.png :(
This is my raid controller and array info
<code>~ # esxcli   hpssacli cmd -q "ctrl all show config detail"

Smart Array P410 in Slot 1
 Bus Interface: PCI
 Slot: 1
 Serial Number: PACCRCN80ZK1TXH
 Cache Serial Number: PACCQID11090TB9
 RAID 6 (ADG) Status: Disabled
 Controller Status: OK
 Hardware Revision: C
 Firmware Version: 6.60
 Rebuild Priority: Medium
 Expand Priority: Medium
 Surface Scan Delay: 15 secs
 Surface Scan Mode: Idle
 Queue Depth: Automatic
 Monitor and Performance Delay: 60  min
 Elevator Sort: Enabled
 Degraded Performance Optimization: Disabled
 Inconsistency Repair Policy: Disabled
 Wait for Cache Room: Disabled
 Surface Analysis Inconsistency Notification: Disabled
 Post Prompt Timeout: 0 secs
 Cache Board Present: True
 Cache Status: OK
 Cache Ratio: 50% Read / 50% Write
 Drive Write Cache: Enabled
 Total Cache Size: 256 MB
 Total Cache Memory Available: 144 MB
 No-Battery Write Cache: Enabled
 Cache Backup Power Source: Batteries
 Battery/Capacitor Count: 1
 Battery/Capacitor Status: OK
 SATA NCQ Supported: True
 Number of Ports: 2 Internal only
 Encryption Supported: False
 Driver Name: HP HPSA
 Driver Version: 5.0.0
 Driver Supports HP SSD Smart Path: False

 Array: A
  Interface Type: SATA
  Unused Space: 0  MB
  Status: OK
  Array Type: Data

  Logical Drive: 1
     Size: 1.8 TB
     Fault Tolerance: 1+0
     Heads: 255
     Sectors Per Track: 32
     Cylinders: 65535
     Strip Size: 256 KB
     Full Stripe Size: 512 KB
     Status: OK
     Caching:  Enabled
     Unique Identifier: 600508B1001CC56A2CBC714D023D29CD
     Logical Drive Label: A002F51APACCRCN80ZK1TXH0967
     Mirror Group 0:
        physicaldrive 2I:0:5 (port 2I:box 0:bay 5, SATA, 1 TB, OK)
        physicaldrive 2I:0:6 (port 2I:box 0:bay 6, SATA, 1 TB, OK)
     Mirror Group 1:
        physicaldrive 2I:0:7 (port 2I:box 0:bay 7, SATA, 1 TB, OK)
        physicaldrive 2I:0:8 (port 2I:box 0:bay 8, SATA, 1 TB, OK)
     Drive Type: Data
     LD Acceleration Method: Controller Cache

  physicaldrive 2I:0:5
     Port: 2I
     Box: 0
     Bay: 5
     Status: OK
     Drive Type: Data Drive
     Interface Type: SATA
     Size: 1 TB
     Native Block Size: 512
     Firmware Revision: 05.01D05
     Serial Number:      WD-WCATR3871895
     Model: ATA     WDC WD1002FAEX-0
     SATA NCQ Capable: True
     SATA NCQ Enabled: True
     Current Temperature (C): 40
     Maximum Temperature (C): 53
     PHY Count: 1
     PHY Transfer Rate: 3.0Gbps

  physicaldrive 2I:0:6
     Port: 2I
     Box: 0
     Bay: 6
     Status: OK
     Drive Type: Data Drive
     Interface Type: SATA
     Size: 1 TB
     Native Block Size: 512
     Firmware Revision: 05.01D05
     Serial Number:      WD-WCATR3904352
     Model: ATA     WDC WD1002FAEX-0
     SATA NCQ Capable: True
     SATA NCQ Enabled: True
     Current Temperature (C): 40
     Maximum Temperature (C): 44
     PHY Count: 1
     PHY Transfer Rate: 3.0Gbps

  physicaldrive 2I:0:7
     Port: 2I
     Box: 0
     Bay: 7
     Status: OK
     Drive Type: Data Drive
     Interface Type: SATA
     Size: 1 TB
     Native Block Size: 4096
     Rotational Speed: 5400
     Firmware Revision: 01.01A01
     Serial Number:      WD-WCC4J4478782
     Model: ATA     WDC WD10EFRX-68P
     SATA NCQ Capable: True
     SATA NCQ Enabled: True
     Current Temperature (C): 32
     Maximum Temperature (C): 34
     PHY Count: 1
     PHY Transfer Rate: 3.0Gbps

  physicaldrive 2I:0:8
     Port: 2I
     Box: 0
     Bay: 8
     Status: OK
     Drive Type: Data Drive
     Interface Type: SATA
     Size: 1 TB
     Native Block Size: 4096
     Firmware Revision: 01.01A01
     Serial Number:      WD-WCC1U5116513
     Model: ATA     WDC WD10EFRX-68J
     SATA NCQ Capable: True
     SATA NCQ Enabled: True
     Current Temperature (C): 30
     Maximum Temperature (C): 36
     PHY Count: 1
     PHY Transfer Rate: 3.0Gbps

SEP (Vendor ID PMCSIERA, Model  SRC 8x6G) 250
  Device Number: 250
  Firmware Version: RevC
  WWID: 50014380118D3DBF
  Vendor ID: PMCSIERA
  Model:  SRC 8x6G
</code>
Any ideas what to do? Do i need to provide more information?
Answer:
You're mixing 4k-sector (Advanced Format) disks and 512-byte drives in the same array. That's one consideration.
WD Red and Black disk drives have different characteristics.
What type of performance are you expecting? ESXi isn't compatible with software RAID, so are you comparing the right things? If you're comparing another OS to ESXi, that's not a valid comparison.
Adjust your RAID controller cache ratio to be biased towards writes, not 50:50.
The MicroServer is a slow system.
Comment: @DejanDakić Has this improved at all?
Comment: No, i have set different sectors, no change
Comment: I'll look up about 1.
2. i'm aware of this but in previous scenario i had good speeds (cca 150MB/s read and write) 3. I'm using external raid controller that is compatibile with ESXi (HP P410). Previously i had hyper-v server, why is not that valid comparison? 4. Writes are fine, reads are terrible. 5. I just want to get barely same speeds as previously on sfotware raid
Answer: I catch one situation in HP ML350 G6 p410i raid controller, first I build a three disk in Raid 5, the speed is more fast than a SATA III disk, about 600-800M read and same write speed, it's amazing for me, but when I adjust to 4 disk raid 5, it read still more fast but write become like a usually disk very slowly, in the end, I found the problem:
I occasionally click the read/write buffer setup, it 100% in read and 0% in write, that's the problem, just 50% to 50% or 60 to 40%, it fast again.
the configuration is in HP Stmart Storage Administrator


.hover JQuery not working, but other JS functions are working

Question: I am trying to use a .hover function that will change the size of a div from 50px to 150px, however every different script I've found online doesn't work in my current file.
I think this script works because I've used it before in different projects.
Here's my Code:

//sidebar hover animation

$(document).ready(function() {

  $("#Box1").hover(function(event) {
    event.preventDefault();
    if ($('#Box1').hasClass('unpressed')) {
      $('#Box1').css('width', '50px');
      $('#Box1').removeClass('unpressed');
    } else {
      $('#Box1').css('width', '150px');
      $('#Box1').addClass('unpressed');
    }
  });

});
#sidebarBoxes {
  width: 50px;
  position: absolute;
  z-index: 108;
  padding-top: 50px;
}
.sidebarBox {
  height: 51px;
  position: relative;
  background-color: #c1c1c2;
  color: white;
  font-family: 'texgyreadventorregular';
  font-size: 15px;
  line-height: 50px;
}
#Box1 {
  width: 50px;
}

    art

    art

    art

    art

    art

    art

    art

    art

    art

I've loaded the javascript on a .js file, which is running other scripts just fine, except this one. Anyone have any idea what I might be doing wrong?
Comment: Use this code: `$(".sidebarBox").hover(function (event) {
    event.preventDefault();
    if ($(this).hasClass('unpressed')) {
        $(this).css('width', '50px').removeClass('unpressed');
    } else {
        $(this).css('width', '150px').addClass('unpressed');
    }
});`
Comment: Works on chrome as is.
Comment: I see that, dang. Weird, cuz I'm using Chrome as well and the results aren't at all the same. Tushar, I'm sure that code is right, but now that I see this I think the problem may lie elsewhere.. You guys have any idea where I should look?
Comment: @Tushar has the right answer.
Comment: but you want it for all, right?
Comment: check this fiddle, which is @Tushar's code: http://jsfiddle.net/alexwcoleman/8j2m4qfz/
Comment: well I want it to hover over each div individually and make them change individually.
Comment: you need this as jQuery? there's a pure CSS answer below.
Comment: so Tushar's code works on the jsfiddle, my code works in the "run snippet" on here, and so does the answer below. However, It doesn't work when i plug it in to the actual files. It doesn't list any errors either.
Comment: well, you've got other issues then. run your HTML through a validator perhaps.
Comment: figured it out. In the rest of the code I have an invisible div over everything, which apparently prevents you from hovering over lower elements. Live and learn! Thanks guys, and thanks Tushar for the code.
Answer: You don't need JavaScript to do this. You can use CSS :hover selector and describe any rules which should be applied to the elements on hover:

#sidebarBoxes {
  width: 50px;
  position: absolute;
  z-index: 108;
  padding-top: 50px;
}
.sidebarBox {
  height: 51px;
  position: relative;
  background-color: #c1c1c2;
  color: white;
  font-family: 'texgyreadventorregular';
  font-size: 15px;
  line-height: 50px;
}

.sidebarBox:hover {
  width: 150px;
  background-color: #999999;
}

    art

    art

    art

    art

    art

    art

    art

    art

    art


How to use PHP cookies to identify unregistered online shoppers?

Question: I'm used to work with php sessions when users login. I'm trying to figure out how to identify shopping carts of visitors (unregistered users) by creating a random user_id and storing it in their cart but I'm not understanding the logic of cookies. I'm generating a cookie_value, a random number with rand(). Do I need to add cookie.php to every single page like I would with session.php?
cookie.php
<?php
$cookie_value =rand(10,100);
$cookie_name='new_user'.$cookie_value;
setcookie($cookie_name,$cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
$user_id=$cookie_value;

product.php
    if(!isset($_SESSION['login_user'])){
    include 'includes/cookie.php';
    }elseif(isset($_SESSION['login_user'])){
    include 'includes/session.php';
    }

    if(!empty($_POST)){
    if(isset($_POST['addCart'])){
    //insert product
    $product_id = $_POST['product_id'];
    $user_id = $_POST['user_id'];
    $quantity=$_POST['quantity'];
    $product_price=$_POST['product_price'];

     // prepare and bind
    $cart = $db->prepare("INSERT INTO shopping_cart
   (user_id,product_id,quantity,amount) VALUES (?,?,?,?)");
    $cart->bind_param("iiis", $user_id,$product_id,$quantity,$product_price);
    $cart->execute();

    if($cart){
      header('Location: cart.php');
      exit;
    }
    $cart->close();
    $db->close();

   } }

Comment: In your user_id column, are you storing both the logged in user's id and the randomly generated id from your cookies to identify and retrieve carts?
Comment: @Yolo: No I dont. I just want to display a visitors cart.
Answer: To answer your question if you need to include cookies.php on every page, yes. Your cookie setting is going to cause trouble through, or at least if you use more that one cookie (maybe even those you are unaware of). If your cookie name is random, how are you going to retrieve it easily?
You should not concatenate the random value to form the cookie name. So the lines should be changed like so:
$cookie_value =rand(10,100); // sure about only 90 users??
$cookie_name='tmp_user_id'; // maybe temporary user is a more appropriate naming
if(!isset($_COOKIE['tmp_user_id']) && !isset($_SESSION['login_user'])) {
    setcookie($cookie_name,$cookie_value, time() + (86400 * 30), "/");
}

That way you can retrieve it in your scripts like so:
if(isset($_COOKIE['tmp_user_id'])) {
    $user_id = $_COOKIE['tmp_user_id'];
}

EDIT
As Sebastian pointed out in the comment, you should check obviously if the cookie is set. So if cookie and user session is not set, set cookie. If your session setting procedure should reside in session.php include cookie.php thereafter.
Comment: By including cookie.php on every page, doesn't it create a new random number every time?
Comment: On cart.php I'm using this query to get visitors cart : SELECT * FROM shopping_cart WHERE user_id='$user_id' but the problem is the cookie is randomized... The number changes and I cant retrieve the cart. But I cant set same cookie for every visitor if I want to identify which cart belongs to which visitors. Does it make sense?
Comment: @SebastianFarham thanks for pointing that out. I adapted my answer.
Answer: You are over-complicating thing a lot. PHP Sessions already do what you want. In fact they are meant specifically to solve this problem.
By default PHP Sessions use cookies to maintain state between requests and assign each user a unique SESSION_ID that you can read from your script. So there is no need for you to set an additional cookie.  Your code could be as simple as:
if(isset($_SESSION['logged_user'])) $user_id = $_SESSION['logged_user'];
else $user_id = session_id();// id sticks because it was stored in a cookie by PHP

Now you can use this $user_id to store or retrieve cart data from the DB. In fact, if you're dealing with a user who has not logged in, you could even just store the cart data in $_SESSION, so you won't bloat your DB with non-member data.
See the docs: session_id


MySQL Order By in Subquery

Question: I'm trying to solve this problem on Hacker Rank:
Input (Projects table)

Output:
2015-10-28 2015-10-29
2015-10-30 2015-10-31
2015-10-13 2015-10-15
2015-10-01 2015-10-04
So what the problem is asking for is to treat consecutive end dates as part of one project and return the start and end dates of projects ordered by the date differences in ascending order. As you can see from the above example, tasks 1,2,3 are the in the same project, tasks 4,5 are in the same project and tasks 7 and 8 are their own projects.
This is one of the solutions I found:
set @sdate = null;
set @nextdate = null;

select sd, max(ed) ed2
from (
    select if(@nextdate = start_date,  @sdate, @sdate := start_date) as sd,
           @nextdate := end_date as ed
    from Projects
    order by start_date
) tmp
group by sd
order by datediff(max(ed), sd)

It is using variables to store the previous end date and compare it to the current row, but I'm confused by the order by clause in the subquery:

If I take out the 'order by start_date' in the subquery, the result it returns will be wrong -- I was under the impression that in MySQL the ordering of subqueries is ignored?
My understanding was that order by is executed after the select so here it would be ordering the results from select in the subquery, but it seems like it's actually ordering the source table (Properties) before the select statement -- am I correct?

Could someone help me understand why this is the case? Thanks
Answer: The ORDER BY in the subquery is necessary for the variable assignment to work. This is similar to the idea of assigning row numbers in older MySQL version. When you run:
SELECT *
    FROM Projects;

Without the ORDER BY, you'll get almost every Start_date value in ascending order except for the Start_date of 2015-11-04 until 2015-11-07 which gives you result in this order:
...
ID  Start_date  End_date
16  2015-11-04  2015-11-05
10  2015-11-07  2015-11-08
15  2015-11-06  2015-11-07
11  2015-11-05  2015-11-06
...

It start from 4 but then the next one is 7,6 then 5. This breaks the variable assignment. If you run the query like this:
 SELECT *,IF(@nextdate = start_date,  @sdate, @sdate := start_date) AS sd,
           @nextdate := end_date AS ed
    FROM Projects;

You can see the difference in the results where the Start_date is in the correct order vs with the incorrect order:
+-----+------------+------------+------------+------------+
| ID  | Start_date |  End_date  |     sd     |     ed     |
+-----+------------+------------+------------+------------+
|   1 | 2015-10-01 | 2015-10-02 | 2015-10-01 | 2015-10-02 |
|  24 | 2015-10-02 | 2015-10-03 | 2015-10-01 | 2015-10-03 |
|   2 | 2015-10-03 | 2015-10-04 | 2015-10-01 | 2015-10-04 |
|  23 | 2015-10-04 | 2015-10-05 | 2015-10-01 | 2015-10-05 |
   .......
|   3 | 2015-10-11 | 2015-10-12 | 2015-10-11 | 2015-10-12 |
|  22 | 2015-10-12 | 2015-10-13 | 2015-10-11 | 2015-10-13 |
   .......
|  16 | 2015-11-04 | 2015-11-05 | 2015-11-04 | 2015-11-05 |
|  10 | 2015-11-07 | 2015-11-08 | 2015-11-07 | 2015-11-08 |
|  15 | 2015-11-06 | 2015-11-07 | 2015-11-06 | 2015-11-07 |
|  11 | 2015-11-05 | 2015-11-06 | 2015-11-05 | 2015-11-06 |
+-----+------------+------------+------------+------------+

With the subquery returning the result like above, whereby 3 of the rows should actually generate sd=2015-11-04 but instead have different value, the outer query GROUP BY will then gave 14 rows of results. By adding the ORDER BY Start_date in the subquery, you'll get the result for 2015-11-04 until 2015-11-07 like this instead:
+----+------------+------------+------------+------------+
| ID | Start_date |  End_date  |     sd     |     ed     |
+----+------------+------------+------------+------------+
| 16 | 2015-11-04 | 2015-11-05 | 2015-11-04 | 2015-11-05 |
| 11 | 2015-11-05 | 2015-11-06 | 2015-11-04 | 2015-11-06 |
| 15 | 2015-11-06 | 2015-11-07 | 2015-11-04 | 2015-11-07 |
| 10 | 2015-11-07 | 2015-11-08 | 2015-11-04 | 2015-11-08 |
+----+------------+------------+------------+------------+

So, it's not actually the ordering that makes the answer wrong but it's the extra rows in the end result.
Here's a fiddle to play around
Comment: thank you for the answer, so my understand is that `order by` makes the input data in order so that the next row will either be a consecutive day or it won't, which makes the variable assignment depending on this condition work -- is that the right idea? Because the source table might not be in that order. if yes, then order by is executed before the select (the one in the subquery, which does the variable assignment) so it actually orders the Projects table first and then the select is run on top of that?
Comment: Yes, that's the idea and yes `order by` is executed before `select`.

MySQL Order By in Subquery


ASP.NET MVC Lifecycle - Do Some Work Once Per Page Request

Question: I'd like to perform some work per web request to a .NET MVC Web Application.  Specifically, I'd like to make a log entry into a DB for each page load.
Performing this work in an overridden Controller class Controller.Initialize() method doesn't work, because a new controller is created with every call to @Html.Action().  Thus, if a child action is called from a view, then I end up double logging--which isn't what I want.
How can I insert some work into the MVC Lifecycle, such that it executes once per page request?
Comment: Try `BeginRequest` event in global.asax
Comment: @VsevolodGoloviznin `Try BeginRequest event in global.asax` **BeginRequest** event is also called multiple times in a single  page load.
Comment: Vsevolod, do you mean Application_BeginRequest?  I just tried it.  No, that method isn't called per web request.
Comment: Do keep in mind that there's no such thing as pages in MVC. You should reformulate your requirement in terms of controller actions. You'll then have to get clear on which controller actions you want to log and which you do not.
Comment: @JohnSaunders, Yes the title might be, "Do Some Work Once Per _Web_ Request".
Comment: What do you consider to be a web request? It's really not a simple question.
Answer: You can use either OnActionExecuting or OnActionExecuted.
For example,
public class HomeController : Controller
{
    [LogActionFilter]
    public ActionResult Index()
    {
        return View();
    }
}

public class LogActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // If you register globally, you need this check.
        if (!filterContext.IsChildAction)
        {
           Log("OnActionExecuting", filterContext.RouteData);
        }
        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // If you register globally, you need this check.
        if (!filterContext.IsChildAction)
        {
           Log("OnActionExecuted", filterContext.RouteData);
        }
        base.OnActionExecuted(filterContext);
    }

    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
        Debug.WriteLine(message, "Action Filter Log");
    }
}

Comment: Hi @Win, that may work; I had considered creating a new ActionFilterAttribute.  But I believe I'd have to decorate (apply this new attribute) to numerous existing controller actions.  Is this right?
Comment: Yes. Ideally, you just add LogActionFilter to important Action methods only. In other words, you do not want to log each and every action methods, because logging is expensive.
Comment: @Michael, you don't have to apply the attribute to every controller, you can register it globally.
Comment: @Michael Craig is correct. If you register globally, make sure you check **IsChildAction**. I updated the answer.
Comment: @Win, Creating a new `ActionFilterAttribute` looks like a good solution as well. :) @Craig W. I didn't know that I could register it globally. Thanks for your help!
Answer: You can check in the Initialize if the action is a Child Action.
ControllerContext.IsChildAction

Comment: Attempting that `if (!ControllerContext.IsChildAction) { }` snippet in `protected override void Initialize()` doesn't work because ControllerContext is null.
Comment: Romias, I explored your suggestion again.  I noticed that `ControllerContext.IsChildAction` _is_ available in `protected override void OnActionExecuted()`.
Comment: Instead of doing it in Initialize... create a GlobalFilter, and register it in Global.asax
Comment: OnActionExecuted is triggered just before start rendering the view, and after you passed the Model to the View(model). So in that moment you can log info of the model itself (serialize it for example).
Comment: Thanks.  Using `ControllerContext.IsChildAction` in `protected override void OnActionExecuted()` is working for me.
Comment: Of course, it also fires for actions which are not rendering views.


Entity Framework - Model Self-Referencing Dependencies Not Cascading Delete

Question: I have a Group model/table:
namespace Project
{
    #region Usings

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    #endregion

    [Table("Groups")]
    public class Group
    {

    public Group()
    {
        this.Pk = Guid.NewGuid();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Key]
    [Required]
    public Guid Pk
    {
        get;
        set;
    }

    public virtual ICollection<Group> Parents
    {
        get;
        set;
    }

    public virtual ICollection<Group> Children
    {
        get;
        set;
    }

    public virtual ICollection<Document> Documents
    {
        get;
        set;
    }

    ...
}

A group can have many groups as either a child or parent, as well as many documents.
I have the relationships wired up in Fluent API as so:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<Group>()
                    .HasMany(e => e.Parents)
                    .WithMany(e => e.Children)
                    .Map(e =>
                         {
                             e.MapLeftKey("ParentPk");
                             e.MapRightKey("ChildPk");
                             e.ToTable("GroupMappings");
                         });

        modelBuilder.Entity<Group>()
                    .HasMany(e => e.Documents)
                    .WithMany(e => e.Groups)
                    .Map(e =>
                         {
                             e.MapLeftKey("DocumentPk");
                             e.MapRightKey("GroupPk");
                             e.ToTable("DocumentMappings");
                         });
 }

When I generate the SQL for these models, the relationship between Groups and Documents (DocumentMappings) has ON DELETE CASCASDE:
ALTER TABLE [dbo].[DocumentMappings] ADD CONSTRAINT [FK_dbo.DocumentMappings_dbo.Documents_GroupPk] FOREIGN KEY ([GroupPk]) REFERENCES [dbo].[Documents] ([Pk]) ON DELETE CASCADE

But the GroupMappings does not:
ALTER TABLE [dbo].[GroupMappings] ADD CONSTRAINT [FK_dbo.GroupMappings_dbo.Groups_ParentPk] FOREIGN KEY ([ParentPk]) REFERENCES [dbo].[Groups] ([Pk])
ALTER TABLE [dbo].[GroupMappings] ADD CONSTRAINT [FK_dbo.GroupMappings_dbo.Groups_ChildPk] FOREIGN KEY ([ChildPk]) REFERENCES [dbo].[Groups] ([Pk])

Visual representation of the tables:

What could be wrong with my mappings for Group (Parent/Children) that is causing ON DELETE CASCADE to not be "enabled"? Is it related to it being a reference on the same type?
Disclaimer: I have seen a few posts saying this can not be done because you "can't use CASCADE DELETE on self referencing table in SQL SERVER." (Entity Framework 6 Code-First cascade delete on self referencing entity). I am using a mapping table in this case, so this should not be the situation.
Answer:
Is it related to it being a reference on the same type?

Yes it is. The GroupMappings table has two foreign keys. If you try to set them bot to cascading delete you will get this exception:

Introducing FOREIGN KEY constraint 'contraintName' on table 'GroupMappings' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

With two foreign keys, if you delete a Group there would multiple cascade paths to deleting GroupMappings. Sql Server has this restriction that it doesn't allow this, even when the paths end up at the same table.
EF has knowledge of this restriction and doesn't want to choose for you which FK it equips with cascaded delete. It can't do both.
Comment: Would it be a valid solution to set both FKs to ON CASCADE DELETE after the schema has been created, then? After doing this in test database it _appears_ to be working.
Comment: Well, I can't make both FKs cascading. Sql Server disallows it. But one would be enough, and yes, it would be a viable solution.


AWS ELB Redirect HTTP to HTTPS without index.php

Question: I am using AWS Elastic Beanstalk to host my website with Load Balancer over some EC2 instances.
I am using OctoberCMS (a flavour of laravel as a framework)
I have setup SSL Certificate over my ELB via AWS Certificate Manager and all is working fine.
But there is a problem.
I want to redirect HTTP to HTTPS.
According to AWS, I got a small .htaccess snippet to do the job:
Redirect to HTTPS
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

However, when a user gets to http://mywebsitesite.com it takes them to https://mywebsitesite.com/index.php hence they start browsing in the manner of https://mywebsitesite.com/index.php/someresource.
Also if you go to http://mywebsitesite.com/someresource, you are redirected back to https://mywebsitesite.com/index.php.
This is not a good experience and I know someone must have encountered this before and is able to redirect to resource properly and remove the index.php
My ELB listener is configured by default to 80 --> 80 and 443 --> 80
Note: I am not encountering a redirect loop.
Answer: I'll preface this answer with saying that this is code from the Tomcat Elastic Beanstalk but I believe that it should still work.
I had in my configuration code file:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R,L]

This was part of a .ebextensions file that configured the Apache proxy which, in my case, was in front of Tomcat.
Answer: You can add the following line in .htaccess to hide the index.php from the url after the redirect configuration.
RewriteRule ^(.*)$ /index.php?/$1 [L]


How do you play a slur for the same note?

Question: I am learning a new piece on piano and there's a slur between the same note like this:

Am I supposed to strike the key twice and use the sustain pedal in between?
Comment: @Pete_Becker Please post answers as answers (not as comments).
Comment: When it's the same note it's a. **tie**, not a slur. Just hold the note for the duration of both notes.
Answer: A slur to the same note is called a 'tie'.   Play it as one extended note.
Comment: Just give the OP a simple answer.  This question will be taken down as a duplicate pretty soon anyway.
Comment: Technically slurs and ties are two different things and should look slightly different. Also there is a lot of wind and brass music with slurs over repeated notes, so the question of what to do when you see a slur over repeated notes is still valid. I agree that the image in question looks like a tie, not a slur.
Comment: Might be worth explaining the "why": in this 2-beat time signature, it's the only way to get a 4-beat note.