jQuery drop down menu closing by clicking outside

Question: I am developing a simple dropdown menu with jQuery . When a user press on a trigger area, it will toggle the dropdown area. My question is how to have a click event outside of the dropdown menu so that it close the dropdown menu ?
Answer: You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.
/* Anything that gets to the document
   will hide the dropdown */
$(document).click(function(){
  $("#dropdown").hide();
});

/* Clicks within the dropdown won't make
   it past the dropdown itself */
$("#dropdown").click(function(e){
  e.stopPropagation();
});

Demo: http://jsbin.com/umubad/2/edit
Comment: If there are other elements on the page that have click handlers they could prevent the click event from bubbling down to the document.
Comment: This doesn't work if you have two dropdowns as you'll be stopping the event from triggering up to the document.
Comment: This solution is not universal. It actually blocks the dropdown from showing in some cases.
Comment: @jacob.toy Only if they are stopping propagation would they prevent it.
Comment: So, is this why this solutions works well? Due to your comments, @JonathanSampson and @jacob.toye?
Answer: how to have a click event outside of the dropdown menu so that it close the dropdown menu ?
Heres the code
$(document).click(function (e) {
    e.stopPropagation();
    var container = $(".dropDown");

    //check if the clicked area is dropDown or not
    if (container.has(e.target).length === 0) {
        $('.subMenu').hide();
    }
})

Comment: My favorite solution of the bunch because it allows for events on child elements to propagate properly.
Comment: Nice! This works really well. So, essentially, this line of logic, `container.has(e.target).length === 0`, checks if the event target is a `$('.dropDown')`, and if not, hide the `subMenu`?
Comment: The best solution, but `e.stopPropagation();` doesn't really make sense because `document` is already one of the highest (last) levels in the DOM
Answer: Stopping Event Propagation in some particular elements ma y become dangerous as it may prevent other some scripts from running. So check whether the triggering is from the excluded area from inside the function.
$(document).on('click', function(event) {
  if (!$(event.target).closest('#menucontainer').length) {
    // Hide the menus.
  }
});

Here function is initiated when clicking on document, but it excludes triggering from #menucontainer.
For details https://css-tricks.com/dangers-stopping-event-propagation/
Comment: Great unobtrusive implementation!
Comment: To use `if (container.has(e.target).length === 0)` is much better performance...
Answer: You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.
One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

$('#clickCatcher').click(function () {
  $('#dropContainer').hide();
  $(this).hide();
});
#dropContainer { z-index: 101; ... }
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }

Comment: +1 Neat method. Definitely worth giving a shot. It's worth noting that you don't need to attach click events to all other elements though; a single handler at the document level would be sufficient in most cases.
Answer: Another multiple dropdown example that works  https://jsfiddle.net/vgjddv6u/

$('.moderate .button').on('click', (event) => {
  $(event.target).siblings('.dropdown')
    .toggleClass('is-open');
});

$(document).click(function(e) {
  $('.moderate')
    .not($('.moderate').has($(e.target)))
    .children('.dropdown')
    .removeClass('is-open');
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" rel="stylesheet" />

  <button class="button is-small" type="button">
        moderate
      </button>

edit

delete

block user

  <button class="button is-small" type="button">
        moderate
      </button>

edit

delete

block user

Answer: Selected answer works for one drop down menu only.
For multiple solution would be:
$('body').click(function(event){
   $dropdowns.not($dropdowns.has(event.target)).hide();
});

Answer: There is a tricky way to do this. You can manipulate blur event by adding tabIndex.

$('.click').click(function (e) {
    $(this).siblings('.dropdown').fadeToggle(100);
});

$('.container').blur(function (e) {
    $('.dropdown').fadeOut(100);
});
.container{
  position: relative;
  display: inline-block;
}

.click{
  cursor: pointer;
  user-select: none;
  z-index: 1;
}

.dropdown{
  position: absolute;
  left: 0;
  top: 100%;
  display: none;
  background: #eee;
  padding: 1rem;
  z-index: 2;
}

click this

    dropdown menu here

click this

    dropdown menu here


Python Pandas.to_csv unable to export columns with semicolon(;) as one column

Question: I have a dataframe with 3 columns, but 1 of the columns contain data that is separated by a semicolon(;) during export. I am trying to export a dataframe into a csv but my csv output data keeps getting separated into the following format when opening in excel:

import pandas as pd

my_dict = { 'name' : ["a", "b"],
            'age' : [20,27],
            'tag': ["Login Location;Visit Location;Appointment Location", "Login Location;Visit Location;Appointment Location"]}

df=pd.DataFrame(my_dict)

df.to_csv('output.csv',index=False)
print('done')

I would like to have the output in excel to be:

where the data in the tag column is intact. I've tried adding sep=',' or delimiter=',' but it still gives me the same output.
Thank you in advance,
John
Comment: How are you importing your CSV into excel? It looks like you are splitting on `;` not `,` in excel.
Comment: You should open `output.csv` in notepad or another text editor to see what `pandas` is outputting. The issue you are seeing looks like an error with how you are inspecting the data in excel.
Comment: Take a look at the [`to_csv` docs](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html). There is a `quoting` parameter that you can use. The issue you are seeing is still that your excel is configured to use `;` as a delimiter.
Comment: It's not coming from anywhere. I am adding the tag column manually and will need to have it in the format shown: Login Location; Visit Location; Appointment Location  so I can load it in another system already pre-formatted. Thanks
Comment: Hi Alex, thank you for looking into it. Here's the output in excel

`name,age,tag
a,20,Login Location;Visit Location;Appointment Location
b,27,Login Location;Visit Location;Appointment Location`
it contains the ; so it looks correct. But another issue I have is that I have other columns that comes after the 'tag' column.

How do I put the contents of the tag column in quotes? single or double.
Comment: @Alex, thank you for the link to the documentation. I'll try to see how I can configure excel to default to `,` rather than `;`. Thanks again.
Answer: Excel does some stuff based on the fact that your file has a .csvsuffix, probably using ; as a default delimiter, as suggested in the comments.
One workaround is to use the .txt suffix instead:
df.to_csv('output.txt',index=False)

then open the file in Excel, and in the Text Import Wizard specify "Delimited" and comma as separator.
Do not pick the file in the list of previously opened files, if it's there, that won't work, you really need to do File/Open then browse the directory to find your .txt file.
Comment: Hi @joao, THanks for the guidance. The output in excel is exactly how I want it! Now the issue is that I need to save the file in `csv-utf8` format. Do you have any suggestions on how to convert it to that file format? thanks again.
Comment: When you do `Save As` in Excel just pick CSV UTF-8, it's in the list.
Answer: Thank you @Alex and @joao for your inputs, this guided me to the right direction. I was able to get the output I needed by forcing excel to use , as the separator. By default, Excel was using tab as the delimiter, that's why it was showing me an incorrect format. Here's the link to forcing excel to use comma as a list separator: https://superuser.com/questions/606272/how-to-get-excel-to-interpret-the-comma-as-a-default-delimiter-in-csv-files


aggregate irregular data to monthly averages weighing for days in months,using python

Question: I am struggling to average my data into monthly mean taking into account that the data can represent two months (and years), and there are empty periods. Thus a need to weigh the samples accordantly, i.e. a sample with 2 days in one month and 5 in the next should have 2/7 and 5/7 weight, respectively. I have tried to first reindex to daily data and then resample, but problems with empty periods (do not want to fill these) and irregular sampling periods. Surly I can calculate the duration for each periods (end-start), but not sure if that helps because also need to know the split between months.
Here is part of the data:
start               end                 conc
26.12.2019 07:00    03.01.2020 07:00    0.235
03.01.2020 07:00    14.01.2020 07:00    nan
14.01.2020 07:00    20.01.2020 07:00    0.032
21.01.2020 07:00    29.01.2020 07:00    1.601
29.01.2020 07:00    06.02.2020 07:00    0.815
06.02.2020 07:00    10.02.2020 07:00    nan
10.02.2020 07:00    20.02.2020 07:00    3.029
20.02.2020 07:00    28.02.2020 07:00    2.158
28.02.2020 07:00    09.03.2020 07:00    0.784
09.03.2020 07:00    18.03.2020 07:00    0.304

The results should be:
jan.2020    0.829
feb.2020    2.128

Answer: From a software design prospective, it looks like you need to do some data cleaning before trying to interact with the data.

You need to define what you want to do. Do you want to get rid of all the nan values, or treat them as 0? What if an event starts in one month but ends in another? Once you have these questions, you can start thinking about what to code. Below would be the approach I would take (But I don't know exactly what you want to do with the data):

Deal with the NaNs
decide what month each data point is in, and add a column with that information (heres an example of how to get the month from python datatimes).
use start and end date columns to create a new "duration" column

start               end                Duration    month   conc
26.12.2019 07:00    03.01.2020 07:00     x sec      Dec    0.235
03.01.2020 07:00    14.01.2020 07:00     y sec      Jan    nan
14.01.2020 07:00    20.01.2020 07:00     z sec      Jan    0.032

Aggrigate the data by month. Add up all the durations in a month. Add up all the conc data in a month. avg = tot_conc / tot_duration. Then add this value to a new table:

 | month | avg_conc |
 |  Feb. |  2.218.  |

Comment: Thanks for commenting! I know what I want to do, I want to calculate a monthly average excluding the NaN. I guess my question is how to calculate the duration in each months when the event cover two different months. No problem to calculate the average if the samples are in same month.
Comment: That's a hard question, and It depends on what you are measuring. imagine some data that along the lines of:

```
start    | end   | val
jan 25 | feb 2 | 6
```
It might be reasonable to spilt this into 2 data points:

```
start    |  end   | val
jan 25 | jan 31 | 6
feb 1 | feb 2  | 6
```

or:

```
start    |  end   | val
jan 25 | jan 31 | 5
feb 1 | feb 2  | 1
```

sorry about the formating, Comments dont allow new lines.


How do I call Graphics Method inside KeyListener?

Question: Ahead of time, I would like to say there have been many posts similar to this, however, none of them apply to me or none of them actually have any answer at all, and are outdated, meaning there could be new java features that could help me solve my problem.
Anyway, I wanted to make a game where there is tennis rackets. Of course, they would have to rotate. In order to rotate, I must call my Graphics2D method inside my KeyListener. How would I do this WITHOUT adding a new Graphics2D variable inside my key listener method?
Here is all the methods I have that involve accomplishing this goal:
        public void draw(Graphics2D g2d) {
            g2d.drawImage(getPaddleImg(), x, y, null);
        }

        public static Image getPaddleImg() {
            ImageIcon ic = new ImageIcon("C:/Users/Elliot/Desktop/Eclipse Game Tennis/paddle.png");
            return ic.getImage();
        }

        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            if(key==KeyEvent.VK_W){
                g2d.rotate(Math.toRadians(5));
            } else if(key==KeyEvent.VK_W) {
                g2d.rotate(Math.toRadians(-5));
            }

        public void keyReleased(KeyEvent e) {
            int key = e.getKeyCode();

            if(key==KeyEvent.VK_W){
                g2d.rotate(Math.toRadians(0));
            } else if(key==KeyEvent.VK_W) {
                g2d.rotate(Math.toRadians(0));
            }
        }

I know, this code would give me an error because of the g2d inside of the KeyPressed() and KeyReleased() method. How would I call the g2d inside these two methods? Or how would I do the same thing inside the draw() method?
Answer: The wrong way: You can use Component.getGraphics() to get the graphics object.
The right way: All painting should be done inside the paint(Component) method. This is because a user could resize/open/close the window at any time. In your KeyListener (also research keybindings) you should update a setting on how the player/ racket should be drawn, and then call repaint()
Comment: I know that, but how do I access the `g2d` variable? I appreciate your help with that, but that won't help solve me getting the variable in my method, unless I use the "wrong" way
Comment: All (in my experience) Graphics objects can be cast to Graphics2D
Comment: do you mean `(Graphics2D) g` where `g` is a `Graphics` variable?
Comment: Yes that's what I mean
Comment: I actually have used that in my code before, but how does that help when I already have a `Graphics2D` variable
Comment: What I want to know is how to get `g2d` in my `KeyPressed()` method
Comment: You can use KeyEvent.getComponent() to get the component. Then review my answer
Answer: OK! I actually figured it out by myself! What I did is called the g2d.rotate(.....) inside my draw() method. What I did is created variables that check for rotation, and set them true or false inside of my KeyPressed() method. Here is the code I used inside the draw() method:
 if(isRotatingPositive == true) {
    g2d.rotate(Math.toRadians(speed));
 } else if(isRotatingNegative == true) {
    g2d.rotate(Math.toRadians(-speed));
 }


Loading pictures from mounted drives in laravel

Question: I'm looking for a way to display images, which are stored on mounted drives, in a laravel application we are building. As these drives are outside the laravel folder itself I so far have been unable to find a solution as storage doesn't seem to provide such features.
Did anyone already came across this problem or has an idea how this could best be solved?
Comment: You can use a CDN or just have the images able to be accessed in public folder.
Comment: You could symlink it into your laravel directory
Answer: As Andrea said a symlink is working like a charm, that way I can create symbolic links to every folder created on these mounted drives.
More info about symlinks can be found here:
http://www.cyberciti.biz/faq/creating-soft-link-or-symbolic-link/


How does Action Script 3 handle Asynchronous callbacks?

Question: I have a piece of code in my game which looks a lot like this:
MultiplayerAPI.createGameRoom(function(){ successFunction(new Object()); });

Basically, the createGameRoom is performed and, upon success, the function I passed is run.
However I've been running into some strange bugs recently and I'm wondering, is the instance of "new Object();" the same each time the callback function is run?
It needs to be a different, fresh instance of Object each time, but I'm having some garbage collection issues which make me think it's passing the same object each time that event callback is fired,
Anyone have any idea how Flash handles this?
Comment: Please give us more code and information about object, which is being passed to your successFunction.
Comment: I imagine it's largely irrelevant as flash will either instantiate a new one or it won't, surely? The object is just a display object, the success function swaps the old object which was being displayed with the new one.
Answer: in your example you call the method successFunction within the definition and not when the code should be executed. You have to pass a reference to the method instead of invoking it. Take a look at the following examples. If you use the apply method you can pass the arguments as Array.
*Nicholas
Function Reference & Function Call
function myFunction(parameter:String):String
{
    return 'hello '+parameter;
}

var myFunctionReference:Function = myFunction;
trace(myFunctionReference); // function Function() {}

trace(myFunctionReference('world')); // 'hello world'

var myFunctionReturnValue:String = myFunction('moon');
trace(myFunctionReturnValue); // 'hello moon'

Working Example
package
{
    import flash.display.Sprite;

    public class MethodTest extends Sprite
    {
        public function MethodTest()
        {
            trace('MethodTest Constructor');
            trace('---');
            invoke(successFunction,'first',{id:123,type:'foo'});
            trace('---');
            invokeByApply(successFunction,'second',{id:456,type:'bar'});
        }

        public function invoke(method:Function,someName:String, someObject:Object):void{
            trace('MethodTest invoke');
            method(someName,someObject);
        }

        public function invokeByApply(method:Function,...arguments):void{
            trace('MethodTest invokeByApply');
            method.apply(null,arguments);
        }

        public function successFunction(someName:String, someObject:Object):void{
            trace('MethodTest successFunction');
            trace('someName: '+someName);
            for(var key:String in someObject)trace(key+': '+someObject[key]);

        }
    }
}

Answer: Writing AS3 code as in the example you gave (defining new functions from within the calls to other methods), as is done in JavaScript, you will find it very difficult to debug.
I suggest checking out "OOP with ActionScript" by Hall/Wan and taking advantage of object orientated programming design principles, as it may make your life easier in the long term:
http://www.amazon.com/Object-Oriented-Programming-ActionScript-Branden-Hall/dp/0735711836


Unchecked Cast warning in Java?

Question: In this code I am making an implementation of a generic linkedlist in java.
public class LL<Item extends Comparable<Item>> {

My Node class is defined like
private class Node{
private Item data;
private Node next;
public Node(Item data){
    this.data = data;
    next = null;
}
}

Now my doubt is, I keep getting warnings when coding
 Node x = head, y = (Node) b.head;
Type safety: Unchecked cast from LL.Node to LL<Item>.Node

Should I ignore this, why does the compiler generate that. And is there a workaround it ?
EDIT :
b is of type LL, the function signature looks like
public void mergeAlternate(LL b){

And head is a private instance variable of LL class
private Node head;

Comment: @TheNewIdiot He should understand **why** the warning occurs, not just blindly suppress it. If this was an answer it'd be an immediate -1 from me.
Comment: What is the type of `b` and `b.head`?
Comment: `@SuppressWarnings("unchecked")`
Comment: Can you show the declaration of `b`?
Comment: @TomG I agree. hershey92, can you please post where the head is defined.
Comment: hershey92, we'd need to know what `head` is, what `b` is, how the `.head` method is declared...
Comment: @Tom G I missed that, actually "b" is of type LL("the linkedlist class")
Comment: I have made some edits, let me know if more clarifications is needed?
Answer: If you are creating a generic implementation then it should be generic internally as well.
You are missing the type parameter for your Node class. It should be generic like this:
private class Node<T extends Comparable<T>> {
    private T data;
    private Node<T> next;
    public Node(T data){
        this.data = data;
        next = null;
    }

}

And where you are using that class you can do something like this:
new Node<Item> // ...
And your code will look like this:
Node<Item> x = head, y = b.head;

and you won't get warnings that way.
My spider sense however tells me that there is some architectural problem there. Since you did not show us all your code we can't help you any further.
Comment: `T extends Comparable`?
Comment: If you understand the code, looks like `Node` is an inner class inside `LL` class, to in order to make it work you should mark it as `static` and just have `Node`. Having this, you just have to declare `Node node;` variables with no problem.
Comment: It should not be `static` since he won't use it without an instance of `LL`. I used `T` instead of `Item`. I could've used `ITEM` as well but using `Item` for a type parameter name confuses it with an actual type name.
Comment: I can understand why you used `T`, but just note that OP already uses `Item`, so your solution must be adapted to current OP's code and you can suggest using `T` instead of `Item` for readability purposes. By the way, I still think it should be a `static` class since you could pass an array as constructor param to initialize the data for the linked list thus no need to have an instance of `LL` to start creating `Node` instances :) (of course, this is a design matter but not focused on the main problem, just an improvement).

Unchecked Cast warning in Java?


How to run my view function without reload page?

Question: How to run my view function without reload page?
views:
def set_prio(request, id):
    obj = Object.objects.get(id=id)
    obj.prio = True
    obj.save()
    #return HttpResponseRedirect('/')

templates:

Comment: -1: Then that should be your question. Be explicit about you are asking and don't just put a bunch of code.
Comment: What? a page redirect without a reload ?
Comment: Ajax! Are you asking how to use Ajax with jQuery?
Comment: Please show us jquery code
Comment: @minitech yes, I'm asking how to use ajax with django
Comment: If you are looking for a redirect, you might aswell have a simple form submit. You are not doing anything fancy here
Comment: @karthikr: Sorry, `HttpResponseRedirect` can be deleted. I need to change the value to `True` only.
Answer: Run it using an ajax request and apply the result of your request using javascript.
Here is an example: http://api.jquery.com/jQuery.ajax/
And yes, your quesion should be much more explicit!


Usar comandos de cmd em scripts feitos para rodar em shell - cakephp 3.0

Question: Eu queria saber se tem como usar comandos nativos do CMD do windows, apartir de scripts feitos para rodar no shell do cakephp.
Já executo tarefas que rodam no cmd, mas com os comandos do próprio framework mas gostaria de usar outros comandos.
Answer: Não entendi bem a duvida, suponho que queira criar um Shell no cakephp, tal como:
namespace App\Shell;

use Cake\Console\Shell;

class HelloShell extends Shell
{
    public function main()
    {
        $this->out('Hello world.');
    }
}

Mas que ele execute comandos que existem na maquina.

Entenda que os comandos que rodam no CMD são em sua maioria executáveis globais.

Para rodar comando do Windows você precisará obviamente estar em um servidor Windows e não necessáriamente irá precisar do cakephp, mas somente do php, no caso temos 3 funções:

exec - retorna a reposta do programa em uma referencia do tipo array (segundo parâmetro)
system - retorna a resposta diretamente no output, ou se for HTTP já imprime como se fosse usado o echo, também é possível pegar a ultima linha do output e a resposta de retorno do aplicativo (geralmente é um numero)
shell_exec - Executa um comando via "shell" e retorna o resultado um string

É importante notar que se for usar argumentos nos comandos é necessário usar o escapeshellarg ou escapeshellcmd

namespace App\Shell;

use Cake\Console\Shell;

class HelloShell extends Shell
{
    public function main()
    {
        $resposta = shell_exec('dir');

        $this->out($resposta);
    }

    public function raiz()
    {
        $resposta = shell_exec('dir \\');

        $this->out($resposta);
    }

    public function foo($pasta)
    {
        $resposta = shell_exec('dir ' . $pasta);

        $this->out($resposta);
    }
}

Depois de salvar o arquivo, você deve ser capaz de executar os seguintes comandos:

Exibe o conteúdo da pasta atual, geralmente a que chamou o script principal o variando do apontamento da aplicação maior (por exemplo apache):
bin/cake hello

Exibe o conteúdo da pasta raiz:
bin/cake hello raiz

Exibe o conteúdo de uma pasta que determinar:
bin/cake hello foo /a/b/c

Eles irão mostrar algo como:
O volume na unidade C não tem nome.
O Número de Série do Volume é AEE4-3225

Pasta de C:\Users\Guilherme\Exemplo

18/08/2016  23:06    <DIR>          .
18/08/2016  23:06    <DIR>          ..
14/07/2016  23:14    <DIR>          pasta
28/04/2016  21:03                21 .bash_history
               1 arquivo(s)          21 bytes
              3 pasta(s)   267.064.922.112 bytes disponíveis


Questions related to assumptions of OLS regressions

Question: I am conducting a multiple linear regression (OLS) and would like to test the assumptions related to these regressions. My OLS regression involves one dependent variable and 3 independent variables.
All my VIF scores are below 2 so I believe that means that there is no multicollinearity. For the other assumptions I have these pictures below. However I have trouble interpretating them.

I believe that the pp-plot shows violation of linearity? If so, does it mean that I cannot interpret the results of the regression?

Also, what does the scatterplot tell me in regards to the assumptions for OLS?

Thank you very much for your insights.
Comment: Neither plot tells you anything about linearity.  The basic problem is that your response look like it is related to a small count--it is discrete, bounded on one side, and skewed--and would therefore benefit from applying a different model, such as a logistic regression.
Comment: The PP plot tells you that your residuals are pretty close to normal. For the first plot, see @whuber 's comment.

I also noticed that the DV is "Intention" .  How is that measured? From the plot, it looks like it is measured ordinally, probably on a Likert scale.  And, as whuber says it is skewed.  This plot ought to look blobby.
Comment: @whuber Thank you.
Comment: @PeterFlom yes my dependent variable was measured on a Likert scale. Could you tell me whether any of these pictures show violation of assumptions for OLS? Thank you
Answer: Welcome to CV.
In your comment you say that your DV is ordinal and ask if any of the pictures show violation of OLS.
When your DV is ordinal, you don't need pictures. OLS assumes that the DV is continuous.
As Whuber noted, your first plot does show this, but interpreting that plot requires experience and expertise. I also noted that that plot should be blobby. That is, it shouldn't have patterns.
But never mind that. Your DV is ordinal. Maybe a 7 point scale. OLS will make nonsensical predictions. None of the predicted values will be integers (although they might be close) and some might be below 1 or above 7.
You should use ordinal logistic regression, at least as a starting point.
Comment: @PeterFlom The whole level of measurement thing has to do with enforcing symmetries of the actions of certain algebraic structures (usually, and classically, groups). If you don't care about those symmetries for a given analysis, then it is optional whether you limit your operators to respect that structure. The success of word embedding techniques (some of them using least squares in the parameter estimation) in natural language processing show strong counterexamples to the notion that one *must* respect what seems like the *prima facie* 'natural' structure of the data.
Comment: @Sabine For a [weird flex](https://www.dictionary.com/e/slang/weird-flex-but-okay/), you could treat the three question responses as a single DV but with mixed effects ordinal logistic regression where there are random effects for the question.
Comment: I am unaware of any authority that asserts the response variable must be continuous.  Maybe you meant to use a different term than "continuous"?
Comment: @Sabine All that disagreement notwithstanding, if you are doing a frequentist analysis I suggest [lavaan](https://lavaan.ugent.be/) for R and [semopy](https://semopy.com/) for Python. Similarly, if you do a Bayesian analysis, you can use [RStan](https://cran.r-project.org/web/packages/rstan/index.html) for R and [PyStan](https://pystan.readthedocs.io/en/latest/) for Python.
Comment: @PeterFlom TBH I miss your blog. But yes, I think we agree that something using ordinal regression alongside other techniques (e.g. SEM) would be useful to Sabine.
Comment: Thank you, I am very new to Statistics so your comments are helping me a lot. Maybe I should clarify that my DV was formed based on 3 questions, each measured on a likert scale (1-5). I then added and averaged out these 3 questions to construct my DV. Does that change anything to your recommendations to conduct a logistic regression? (My professor advised to conduct ols, therefore I am confused). Again, thank you very much
Comment: @Sabine I think you have three DVs, one for each question. I suggest using a structural equation model which can be combined with ordinal logistic regression. I find that this tends to work no-worse, and sometimes better, than doing three separate ordinal logistic regression models.
Comment: Yes, that does change things.  If you average three five point scales, you can get any of 15 answers. But I am betting you don't get all 15 different possibilities.

I'm kind of torn here. I think the *right* solution to your problem is probably complex. Galen's idea of an SEM is fine. I would have suggested an exploratory factor analysis.  EFA would give you more different answers and get rid of the problems I stated in my answer.

But ... Maybe you've never even heard of those.

Your first plot, though, does show violations.
Comment: @whuber Maybe "assumption" was the wrong term. But see e.g. Ben's answer on this thread https://stats.stackexchange.com/questions/143167/ols-with-ordinal-dependent-variable-do-the-coefficients-mean-anything
Comment: I think "continuous" was not the term you intended.  The underlying issue is of the *measurement level* of the response, which is separate from applicability of OLS.  Moreover, there is at best a loose and not very direct link between "continuity" (whatever that might mean--it's an overloaded term in this context) and measurement level.
Comment: @Galen OK, I even wrote a blog post about the problems with Stevens' categories, especially when they get used as a straitjacket instead of as guidelines. But, in trying to answer Sabine's question .... Well, as I said earlier, I'm torn. She is just starting! And her professor seems to be giving bad advice (I'm betting that the prof is not a statistician).


Where to put HttpClient request and response converter functions

Question: In our angular application we are converting every api request and response types to our app specific type so it is easier to implement a property change in a big application.
At the moment we are doing that directly in the Service with a map on the HttpClient observable. But this is a little bit cumbersome, especially for requests that return the same entity (e.g. get and post both returning an entity).
@Injectable()
export class TodoService {
  constructor(private httpClient: HttpClient) {
  }

  public getTodos(): Observable<Todo[]> {
    return this.httpClient.get<any>('/path/to/todos').pipe(
      map((res: any) => res.map((item) => ({
        id: res.id,
        name: res.specialProperty
      })))
    );
  }

  public getTodoById(id: string): Observable<Todo> {
    return this.httpClient.get<any>('/path/to/todos/' + id).pipe(
      map((res: any) => ({
        id: res.id,
        name: res.specialProperty
      }))
    );
  }
}

Now I have found a cool article describing the Implementation of an adapter to keep your code more DRY. See. https://florimond.dev/en/posts/2018/09/consuming-apis-in-angular-the-model-adapter-pattern/
My Problem with that approach is that for a big backend service we have to create a lot of AdapterClasses, where maybe a module with a couple of exported functions would do the trick.
Now my question: Do you have any experience with adapting requests and responses in an Angular Application on a large scale and where do you keep your "mapping" functions?
Comment: To be perfectly honest, this `adapter` approach is just a fancy factory method. As you said. This can easily be achieved by using a "dumb" function that takes a given set of data and maps it to whatever object you want (essentially what the adapter does). We split our app in 3 levels. `Component <-> "data"Service <-> GatewayService`. `"data"Service` is domain-driven. The gateway implements the actual call to the backend (and was generated from JSON schema). The `dataService` mapped the requests/responses accordingly and populated it further.
Comment: We do it exactly the same way but we do the mapping already in the GatewayService. My Thinking was where to put these dumb functions. At the moment we use private functions, but then the unit testing can not be done in an isolated manner.
Comment: I disagree Pascal. You can very well unit test each gateway function. You mock the HttpResponse and expect a certain outcome (interface/class) that needs to be fulfilled :) - That way changes in either the mocked response or build-method would result in a failed test.
Comment: Yes of course, but at the same time I always also have an `httpTestingController.expectOne()` as an additional expect block and I really wanted to keep testing of the mapping and testing of the REST implementation separated. But maybe this is a little bit too excessive. I just really like the idea of testing these pure functions in isolation.
Comment: Nothing stops you from moving these files in a separate `model.ts` file which holds the interface along with a possible `build` method ;)
Comment: Yes true but then again an argument could be made that the mapping method belongs in the `GatewayService` to honour the principle of separation of concerns as the mapping input (response from the API) should only be known to the method that calls the backend and probably not be exported either as we do want our app to only work with its own model everywhere else. You can see why I am a little bit indecisive as everything has its own pros and cons.
Answer: I assume you could have a bunch of model classes, and theoreticaly you can then map response to a class, depending on your custom logic.
as an example you could have classes like these:
export class Model1 {
  static type = 'model1';
  id: number;
  name: string;
  ...;
}

response from backend example:
{
  size: 1,
  itemType: 'model1',
  items: [{name: 'abc', id: 1}]
}

and interceptor logic which will map items to corresponding models
mapResponse(response: MyTypicalResponce) {
  const model = allModels.find(({type}) => type == response.itemType);
  return {
     ...response,
     items: model ? response.items.map(item => new Model(item)) : response.items;
  }

}

Comment: This looks way too complex
Comment: maybe, but no additional code would be required to map these models. every time you are using angular http, models will be already wrapped in classes
Comment: Like @BojanKogoj said, this is a little bit complicated. I do not have a problem with using pure functions, I even prefer it. It is more a scaffolding question for where to put these functions.
Comment: That's not the only problem. This way you can't nest these functions, which is an important part if you have nested objects in response.


Subtract int from char : possible lossy conversion int to char

Question: I am trying to subtract int from char in a typical cryptography key question but I am running into the above mentioned error in the following statements:
char ch = (int)encrypted_message.charAt(i) + key[index];
if (ch > 122)
    ch = (int)ch - 26;

key[] array holds digits of the key and is of type int.
How do rotate the char successfully?
Please help!
Comment: What is your question? If you try to fit a 32-bit datatype into a 16-bit datatype, there is the risk of lost information. Note that all arithmeitc operations in Java will always yield at least an `int` since there are no primitives for `boolean`, `byte`, `char` and `short` in the JVM.
Answer: int is bigger than char, but the result of your operation is typed int (which you're then storing in a char). So the compiler is warning you you might lose information storing an int value into a char variable.
Instead, ensure the result is a char, which is a bit of a pain because + and - with char values results in an int, so we have to cast:
char ch = (char)(encrypted_message.charAt(i) + key[index]);
if (ch > 122)
    ch = (char)(ch - 26);


Segmentation fault on the second call of the function?

Question: Edit (solution)
I've followed the advice of debugging with -fsanitize=address & valgrind. I only used -fsanitize (which I never heard of before) and found out what was the problem, there was a left over call for a destructor in another function and the object was being destroyed twice. The memory was completely jeopardised at this point.
Thanks a lot for the help and the other recommendations too.

I'm writing a code in C++ to talk with CouchDB using sockets (CouchDB is a Database by Apache that has an HTTP API). I've created a whole class to deal with it and it's basically a socket client that connects and closes.
One of my functions is to send an HTTP request and then read the response and work with it, it works fine on the first call, but fails when I call it a second time.
But it's inconsistent where it fails, sometimes it's a SEGFAULT inside of it in one of the string functions, other times it's a SIGABORT in the return. I've signalled the lines where it crashed with ->
And the worst part is that it only fails when it runs for the "second" time, which is actually the 10th time. Explanation: When the class is instantiated a socket is created, sendRequest is called 8 times (all work, always), I close the socket. Then I have another class that controls a socket server, which receives commands and creates a remote user object that executes the command, the remote user command then calls the CouchDB class to manipulate the DB. The first time a command is requested works, but the second fails and crashes the program.
Extra info: In the short int httpcode line, gdb trace shows it's a crash on substr, on the SIGABORT crash trace shows a problem on free().
I've already debugged many times, made some changes as to where and how to instantiate the string and the buffer and I'm lost. Anyone knows why it would work fine many times but crash on a subsequent call?
CouchDB::response CouchDB::sendRequest(std::string req_method, std::string req_doc, std::string msg)
{
    std::string responseBody;
    char buffer[1024];
    // zero message buffer
    memset(buffer, 0, sizeof(buffer));

    std::ostringstream smsg;
    smsg << req_method << " /" << req_doc << " HTTP/1.1\r\n"
         << "Host: " << user_agent << "\r\n"
         << "Accept: application/json\r\n"
         << "Content-Length: " << msg.size() << "\r\n"
         << (msg.size() > 0 ? "Content-Type: application/json\r\n" : "")
         << "\r\n"
         << msg;

    /*std::cout << "========== Request ==========\n"
              << smsg.str() << std::endl;*/

    if (sendData((void*)smsg.str().c_str(), smsg.str().size())) {
        perror("@CouchDB::sendRequest, Error writing to socket");
        std::cerr << "@CouchDB::sendRequest, Make sure CouchDB is running in " << user_agent << std::endl;
        return {-1, "ERROR"};
    }

    // response
    int len = recv(socketfd, buffer, sizeof(buffer), 0);

    if (len < 0) {
        perror("@CouchDB::sendRequest, Error reading socket");
        return {-1, "ERROR"};
    }
    else if (len == 0) {
        std::cerr << "@CouchDB::sendRequest, Connection closed by server\n";
        return {-1, "ERROR"};
    }

    responseBody.assign(buffer);
    // HTTP code is the second thing after the protocol name and version
->  short int httpcode = std::stoi(responseBody.substr(responseBody.find(" ") + 1));

    bool chunked = responseBody.find("Transfer-Encoding: chunked") != std::string::npos;
    /*std::cout << "========= Response =========\n"
              << responseBody << std::endl;*/
    // body starts after two CRLF
    responseBody = responseBody.substr(responseBody.find("\r\n\r\n") + 4);

    // chunked means that the response comes in multiple packets
    // we must keep reading the socket until the server tells us it's over, or an error happen
    if (chunked) {
        std::string chunkBody;
        unsigned long size = 1;

        while (size > 0) {
            while (responseBody.length() > 0) {
                // chunked requests start with the size of the chunk in HEX
                size = std::stoi(responseBody, 0, 16);
                // the chunk is on the next line
                size_t chunkStart = responseBody.find("\r\n") + 2;
                chunkBody += responseBody.substr(chunkStart, size);
                // next chunk might be in this same request, if so, there must have something after the next CRLF
                responseBody = responseBody.substr(chunkStart + size + 2);
            }

            if (size > 0) {
                len = recv(socketfd, buffer, sizeof(buffer), 0);

                if (len < 0) {
                    perror("@CouchDB::sendRequest:chunked, Error reading socket");
                    return {-1, "ERROR"};
                }
                else if (len == 0) {
                    std::cerr << "@CouchDB::sendRequest:chunked, Connection closed by server\n";
                    return {-1, "ERROR"};
                }

                responseBody.assign(buffer);
            }
        }
        // move created body from chunks to responseBody
->      responseBody = chunkBody;
    }
    return {httpcode, responseBody};
}

The function that calls the above and that sometimes SIGABORT
bool CouchDB::find(Database::db db_type, std::string keyValue, std::string &value)
{
    if (!createSocket()) {
        return false;
    }
    std::ostringstream doc;
    std::ostringstream json;
    doc << db_name << db_names[db_type] << "/_find";
    json << "{\"selector\":{" << keyValue << "},\"limit\":1,\"use_index\":\"index\"}";
->  CouchDB::response status = sendRequest("POST", doc.str(), json.str());
    close(socketfd);

    if (status.httpcode == 200) {
        value = status.body;
        return true;
    }
    return false;
}

Some bits that you might have questions about:

CouchDB::response is a struct {httpcode: int, body: std::string}
CouchDB::db is an enum to choose different databases
sendData only sends anything as bytes until all bytes are sent
Comment: There is also no guarantee whatsoever that your entire message will be read with a single call to `recv`, *even if* its size is no greater than the number of characters requested.
Comment: How do you know that the error isn't somewhere else entirely, for example  corrupting memory in such a way that the program crashes half an hour later?
Comment: @user4581301 I did not think about this. I would need to make some changes in one of the classes that might be the problem to see if it's something there. If you have any advice on how I could find this do tell.
Comment: To be honest that was mostly me being snarky because you gave two snippets of code and we out here have no way of knowing that the program is sane when entering the provided code. Currently my suspicion is more along the lines of the `recv` calls not returning as much data as you think they are. A recv that does not fail or disconnect can return any amount from 0 to `sizeof(buffer)`, so the first recv could contain too little for you to find and read a valid integer or the chunked tag. It could also contain data you expect to find in the next `recv`.
Comment: `recv` when successful returns the number of characters received, this number is essential, use it. There is no automatic null termination of buffers.
Comment: @n.m. - It looked like he might be trying to read more of the message in a loop, but I didn't read really carefully to figure that out. Yeah, I just looked. He's expecting the entire header to always fit in the first 1024 bytes. :-/ That's no guarantee. Nor is it a guarantee that if he reads less than 1024 bytes that he's got the entire header. His entire parser logic is totally messed up. But, that's likely not the source of the problem he's complaining about.
Comment: @Omnifarious yes but chunks or HTTP headers or any other kinds of logical unit of the message are not guaranteed to arrive unbroken either.
Comment: @n.m. - Yep, I know. I put all that in my answer. :-)
Comment: @n.m. As I wrote for Omnifarious I did use before and the snippet is with this change, I'll add them back in the snippet as the segfault is still there with them.
Answer: Make it int len = recv(socketfd, buffer, sizeof(buffer), 0); might be overwriting the last '\0' in your buffer. One might be tempted to use sizeof(buffer) - 1 but this would be wrong as you might be getting null bytes in your stream. So, do this instead: responseBody.assign(buffer, len);. Only do this of course after you've made sure len >= 0, which you do in your error checks.
You have to do that every place where you call recv. Though, why you're using recv instead of read is beyond me, since you aren't using any of the flags.
Also, your buffer memset is pointless if you do it my way. You should also declare your buffer right before you use it. I had to read through half your function to figure out if you did anything with it. Though, of course, you do end up using it a second time.
Heck, since your error handling is basically identical in both cases, I would just make a function that did it. Don't repeat yourself.
Lastly, you play fast and loose with the result of find. You might not actually find what you're looking for and might get string::npos back instead, and that'd also cause you interesting problems.
Another thing, try -fsanitize=address (or some of the other sanitize options documented there) if you're using gcc or clang. And/or run it under valgrind. Your memory error may be far from the code that's crashing. Those might help you get close to it.
And, a very last note. Your logic is totally messed up. You have to separate out your reading data and your parsing and keep a different state machine for each. There is no guarantee that your first read gets the entire HTTP header, no matter how big that read is. And there is no guarantee that your header is less than a certain size either.
You have to keep reading until you've either read more than you're willing to for the header and consider it an error, or until you get the CR LN CR LN at the end of the header.
Those last bits won't cause your code to crash, but will cause you to get spurious errors, especially in certain traffic scenarios, which means that they will likely not show up in testing.


use ssh connection with a linux service

Question: I created my 1st service and the main executable is a shell script A which invokes another script B that I don't have any control.
Merely run my script A, it's calling B and everything is OK.
while before that I copied my ssh key to some server C for which script B use ssh root@servrC's IP.
But when I set up my service, it's stuck at the ssh root@ip line in script B and returned non-zero exit status 255.
Comment: This is kind of permission problem, will try to add root ssh key along with current one.
Answer: figure it out by myself but I think it's not a perfect one I expect.
Just switch to root as default user for the service instead of a common user though which was set with the service's configuration file.
Expect more solutions.

use ssh connection with a linux service


Sub-select as a column with join (attaching extra attribute to the statement)

Question: I have two sqls that I want to combine into one (join both to get additional attribute column):
1.Master data: this part shows companys' detail info.
SELECT
  dim.firm_sys_no "firm_sys_no",
  firm_global_id "Firm Global ID"

FROM
  FIRM_DETAILS_DIM LEFT OUTER JOIN ACTIVITIES_FACT ON
  ( FIRM_DETAILS_DIM.FIRM_SYS_NO=AACTIVITIES_FACT.FIRM_SYS_NO  )

  LEFT OUTER JOIN REPORTING_SALES_ORG_DIM ON
  (REPORTING_SALES_ORG_DIM.ORG_SYS_NO=ACTIVITIES_FACT.SALES_ORG_SYS_NO  )

  INNER JOIN
  (select * from REPORTING_SALES_ORG_DIM where EFFECTIVE_END_DATE is null) SALES_ORG_LATEST ON
  (REPORTING_SALES_ORG_DIM.SALES_OFFICE_ID=SALES_ORG_LATEST.SALES_OFFICE_ID )

WHERE
(ACTIVITIES_FACT.EFFECTIVE_END_DATE is null )
  AND  ( FIRM_DETAILS_DIM.FIRM_GLOBAL_ID  <>  '-1')
  AND  ( SALES_ORG_LATEST.GLOBAL_REGION_NAME  IS NOT Null )
  AND  ( SALES_ORG_LATEST.global_region_name IS NOT NULL )

GROUP BY
  firm_details_dim.firm_sys_no,
  firm_details_dim.firm_global_id
ORDER BY
  firm_details_dim.firm_global_id,
  firm_details_dim.firm_sys_no

2.Lookup/sub-select: returns info on transaction count per company global id.
SELECT
  firm_details_dim.firm_global_id,
  (CASE
    WHEN round(months_between(current_date, SLS_MONTHLY_TRANS_F.transaction_date),0)>4
    THEN 0
    ELSE 1
  END) "Trs"

FROM SLS_MONTHLY_TRANS_F
  INNER JOIN firm_details_dim ON
  ( firm_details_dim.firm_sys_no=SLS_MONTHLY_TRANS_F.firm_sys_no )

WHERE SLS_MONTHLY_TRANS_F.transaction_amount_usd<>0

GROUP BY
  firm_details_dim.firm_global_id,
  (CASE
    WHEN round(months_between(current_date, SLS_MONTHLY_TRANS_F.transaction_date),0)>4
    THEN 0
    ELSE 1
  END)

SQL I need to get: combine both above queries so that master sql will have additional column from the second one (Trs4m). What I'm aiming at is to see which company from master had transaction count 0 or 1.
Comment: Please have a look at [mcve]
Answer: Hm, obvious option is to (outer?) JOIN additional tables (from the second query) to the first query in order to produce the result.
If, for some reason, that can't be done, you could create a function (based on the second query) and call it from the first one, passing required parameters. That would probably be (much?) slower than the first option (hint: SQL - PL/SQL context switching).
Comment: Unfortunately I don't have PL SQL rights on my system to run scripts. The join option you proposed also worked.
Comment: OK; I'm glad if it helped.
Answer: Ok, I moved the sub query to the from clause part, joined with other tables and brought one of two columns to the select part. That why I didn't have to limit the sub query to one attribute while it was in select.


Light measuring in android

Question: I'm trying to get a uniformed value that indicates a light level from the Android back (main) camera.
I'm using several Android devices and the object captured is absolutely static (same object in the same light condition, in the same angle and the same position) and I get deferent value results.
My calculation is based on Aperture, ISO, exposure time and exposure compensation.
I tried to do:
EV = AV + TV = log(Aperture^2,2) + log(1/exposure_time,2).

I also tried some other methods from the following article: http://dougkerr.net/pumpkin/articles/APEX.pdf
Anyhow… the results I get differ from device to device…
Does anyone know how to solve it? Maybe there are more values that I'm ignoring?
Thanks.
Comment: In photography, you would use a light calibration card. The calibration card normalizes the light measurement against a known standard. [link](http://www.lastoliteschoolofphotography.com/stills/Calibration-Greycards-VT1.jpg)
Comment: Thanks Fred, what is the known standard?
Comment: The calibration card is the known standard. When a camera looks at a room, it is measuring reflected light. The amount of light viewed will vary based on the surface the light reflects off of. The calibration card will reflect (without glare) a specific percentage of light, the reflection will be perfectly gray and smooth. To calibrate a camera, the card can be viewed under fixed lighting situation such as direct sunlight, then have other light situations measured against the known constant.
Comment: Another method of light metering that light meters have frosteddomes over the sensor. The frosted dome causes the light to smooth and scatter to allow direct measurement of light. Since you are using a camera, my first thought was calibrating a camera. I'm not sure for a camera what would make a good choice to act as the frosted dome. Again, the baseline measurement would need a known light source, such as sunlight. http://img.wonderhowto.com/img/38/14/63475358911345/0/use-external-hand-held-light-meter.300x140.jpg
Comment: I need a simpler method... a more mathematical method.
Comment: Have you ever heard the expression, "how long is a piece of string?" Without more information, the question is unanswerable, much like yours. If you were in a room, with the walls painted perfectly black, no matter how much light is in the room, when the camera looks at the wall it would say that the room had no light. Conversely if the room was covered in mirrors, and the camera looked at the reflection of a light bulb, it would say the room was very bright, even if the light was just one small LED.
Comment: Given one room with walls painted gray and a single 60 watt bulb in the center of the room and taking a picture of the wall standing directly below the bulb. Given 2 different camera set with the same exposure settings, the resulting images will very based on the lens and the cmos/ccd chip used by the different cameras. Somehow you need to neutralize these parameters.
Comment: thanks for the replay Fred. to be more specific, im shooting a LED light in a completely Dark box. i want to do that with two different camera phones and get the same EXIF parameters.
Answer: I'm not sure how much you proceeded with this but I thought some answers might help you come to some conclusion.
With many Android devices, the Image Signal Processing chain can vary from one model to another, depending of course on who the makes the ISP and even the tunings that are done for the device. Some models may have tuned their devices successfully so you get some certain level of expected results, but others may not.
Other factors include unknown tone curves and other post-processing blocks which are hard to find out exactly unless you've been working in developing the device.

Light measuring in android


For each positive integer n, define s(n) to equal the sum of the digits of n. The number of integers n with 100 ≤ n ≤ 999 and 7 ≤ s(n) ≤ 11 is S.

Question: So we have a question that goes
For each positive integer n, define s(n) to equal the sum of the digits of n. For
example, s(2023) = 2 + 0 + 2 + 3. The number of integers n with 100 ≤ n ≤ 999 and
7 ≤ s(n) ≤ 11 is S. What is the integer formed by the rightmost two digits of S?
Do we use a generating function to solve this and on a related note how does one find out a generating function for any given problem. If I see that I want to find lets say the number of sets divisible by 5 and there is a generating function to solve it how do I find it for any arbitrary  problem. Is it by chance or what.
Comment: How familiar are you with generating functions? With a passing familiarity, you should be able to start writing something for the first part. EG What is the function for what you described (removing conditions as needed)? What exponents are you interested in? What are their coefficients? $\quad$ For the second part, use the roots of unity to find the sum of coefficients that are 0 mod 5. If this is the first time you're dealing with it, think about how to find the sum for even/odd exponents first.
Comment: My first instinct looking at this is to treat it as a stars-and-bars question.  Just remember that the largest digit is $9$ and so we can't allow for scenarios where one of the digits is ten nor where one of the digits is eleven.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: @Jochen Your solution would be the GF approach that I think OP is asking about. Not sure why you deleted it.
Answer: Break into cases based on the specific sum.  Apply stars-and-bars and temporarily ignore that ten and eleven are not valid digits.  We will subtract the bad cases later.
To have a diophantine sum $x_1+x_2+x_3=n$ with $x_1\geq 1$ and $x_2,x_3\geq 0$, this is solved with stars-and-bars.  First, make a change of variable $y_1=x_1-1$ and consider $y_1+x_2+x_3$ instead.  There will be a total of $\binom{(n-1)+3-1}{3-1}$ valid outcomes.
We would have then $\binom{8}{2}+\binom{9}{2}+\binom{10}{2}+\binom{11}{2}+\binom{12}{2}$ but we will have included a few incorrect outcomes which can be easily counted by hand.
Letting $A$ represent the digit for ten and $B$ the digit for eleven, we will have accidentally counted $A00,~B00,~A10,~A01,~1A0,$ and $10A$ so we need to remove six from our answer to get a final total of:
$$\binom{8}{2}+\binom{9}{2}+\binom{10}{2}+\binom{11}{2}+\binom{12}{2}-6=224$$


Squash in git rebase with "git merge --squash" style commit message?

Question: When using git merge --squash, the commit messages will be pre-populated with a full git log of the merged commits; When using git rebase -i to squash commits, the commit message doesn't contain as much information.
Is it possible to get the same prepopulated commit message when rebasing?
Comment: That description seems to me to be backwards: when you use `squash` in interactive rebase, the editor comes up on a file containing *all* the information, and when you use `git merge --squash`, the editor comes up on a file containing less information. The actual information depends on `merge.log`; if it's set to, say, 10, you'll get up to ten `git log --oneline` subject lines.
Comment: (Other than that, your answer covers a perfectly sensible way to do what you want.)
Comment: @torek It is strange then. For me, `git merge --squash` has always yielded verbose messages and `git rebase -i` squashing the reduced one. I'll have to check if it is a matter of project configuration as made by the source repository I guess...
Answer: Instead of using the squash operator in the git rebase -i interface, we can use exec git merge --squash to get the intended effect. For example, instead of
pick 31988313 master
pick 42983473 first commit of squash
squash 231adf41 second commit of squash
...
squash e32b1fa4 last commit of squash
pick 1ad9e130 more commits

We can use
pick 31988313 master
drop 42983473 first commit of squash
drop 231adf41 second commit of squash
...
drop e32b1fa4 last commit of squash
exec git merge --squash e32b1fa4
pick 1ad9e130 more commits

The downside is that additional care has to be taken to not accidentally drop too many commits.


StackExchange-Driven-Development

Question: Is there anything at all that can be done to curb the #lazyweb culture of StackExchange? I'm starting to notice some repeat offenders questioners crop up who (quite obviously) are freelancers supporting nearly every site they run by asking questions here.
The questions are broad, from analytics to email delivery issues... and I've become curious if there is a policy surrounding this -- or how we can encourage better behavior, more contribution back to the community instead of constant consumption.
Now, I'm not an idiot, and I understand that most every person on this site is making a living on Magento somehow. But there are outliers in every community and I'm only asking how we can curtail the rapid-fire question-asking development support for 1 or 2 people.
Answer: Well, feel free to flag early & flag often! Also, look at the user history and contact the mods directly (you got my number) to bring special attention. As mods I believe that we can & should kibosh overly-broad/repeat questions. StackExchange's recent update to put questions "on hold" is intended to curb this behavior & introduce users to the SE way of asking/doing things.
Ideally, we can educate as we moderate ;-)
Answer: Also questions are a contribution. But if the question is of low quality, downvote, comment, or flag if it is offtopic.
Also keep in mind that there will always more "consumers" than "producers".
I think lots of developers (including myself) are lazy in some way. But this does not excuse ignorance.
So from my point of view it is always okay to ask - but the questions must have a certain quality (especially appreciating comments).
And I refuse to answer any questions as long as the quality is not good and the question is not generally understandable and so useful for this Q&A style page.
Comment: Touché. Questions are contributing. 5 of the same question with increasingly deperate-sounding descriptions like "my client is getting really upset" are not a positive contribution, IMHO.
Comment: Good example. That is SPAM / abuse - sure. I would edit-out this noise. Or downvote/flag to close and ask the OP to edit this out.
Answer: My opinion is that we can post answers with links to resources they can read/should have read about what they want to do.
This way people will be encouraged to post questions and they won't be drawn away.
Then, in time, questions will just be duplicates and can be marked/flagged accordingly.

StackExchange-Driven-Development


Why do we have $Pr(U_1>u_1|U_2>u_2)=1/Pr(U_2>u_2) \int^\infty_{u_2}Pr(U_1>u_1|U_2=u_2)\phi(u_2)du_2$?

Question: I encountered the following derivation:
$$Pr(U_1>u_1|U_2>u_2)=1/Pr(U_2>u_2) \int^\infty_{u_2}Pr(U_1>u_1|U_2=u_2)\phi(u_2)du_2$$
for bivariate normally distributed  $(U_1,U_2)$. I wonder why this equality holds. Does this have anything to do with the law of total probability? I don't think the law directly applies to this case.
Comment: Please clarify what does $\phi(\cdot)$ mean. Is the integral supposed to be in the numerator or denominator? I believe that what you're looking at is just the definition of conditional probability $P(A|B) = \frac{P(A \cap B)}{P(B)}$.
Comment: $\phi$ is the pdf of a standard normal random variable, and the integral is in the numerator.
Answer: Assuming $\phi(u_2)$ is the distribution function of $u_2$, we have:
Let $A$ be the event that $U_1>u_1$ and B the event that $U_2>u_2$. Than we have, by your image
$$P(A|B)=\frac{P(A,B)}{P(B)}$$
Now, we have
$$P(A,B)=P(U_2>u_2,U_1>u_1)=\int_{u_2}^\infty\int_{u_1}^\infty p(U_1=u_1,U_2=u_2)du_1du_2$$
Because there seems to be a precomputed $P(U_1>u_1|U_2=u_2)$ this simplyfies to
$$P(A,B)=\int_{u_2}^\infty P(U_1>u_1|U_2=u_2)p(U_2=u_2)du_2$$
which is, given that $p(U_2=u_2)=\phi(u_2)$, equal to
$$P(A,B)=\int_{u_2}^\infty P(U_1>u_1|U_2=u_2)\phi(u_2)du_2$$
And because $P(B)=P(U_2>u_2)$
$$P(U_1>u_1|U_2>u_2)=\frac{\int_{u_2}^\infty P(U_1>u_1|U_2=u_2)\phi(u_2)du_2}{P(U_2>u_2)}$$
Comment: Why do we have $\displaystyle \int_{u_1}^\infty p(U_1=u_1,U_2=u_2)du_1=P(U_1>u_1|U_2=u_2)p(U_2=u_2)$?
Comment: $$\int_{u_1}^\infty p(U_1=u_1|U_2=u_2)p(U_2=u_2)du_1=P(U_1>u_1|U_2=u_2)p(U_1=u_1)$$
because it simply integrates the probability measure over the event $U_1>u_1$. The expression is a tautology.
Comment: Ok, thanks a lot!


Exchanging $\min$ and expected value

Question: Consider the inequality
$\min \limits_{x} E_{\xi} \{Q(x,\xi)\} \ge E_{\xi} \{\min \limits_{x} Q(x,\xi)\},$
where $x$ is a vector of binaries, $\xi$ is a discrete random variable, and $Q(x,\xi)\ge 0$ for any $x$ and $\xi$. I think that above inequality holds for a simple problem I am working on, but I was wondering whether it holds in general.
Answer: $$Q(y) \ge \min_x Q(x)\qquad\implies\qquad E(Q(y)) \ge E(\min_x Q(x)) \qquad\implies\qquad \min_y E(Q(y)) \ge E(\min_x Q(x))$$
Comment: I've accepted it and will vote up as soon as I can (i.e. when I reach 15 reputation). Cheers!
Comment: No problem. If it helps, upvote it (and accept it when you can). If not, let me know here and I can clarify it.
Comment: Heh, my comment was the wrong way round! Accept it, and upvote when you can :) And thanks.

Exchanging $\min$ and expected value


In Rugby Union, how can players be put back onside after a kick

Question: In rugby union there is often a lot of kicking. To be onside and able to chase the ball, a player must be behind the kicker (or be the kicker himself) when the ball is kicked.
How can other players be put back onside after a kick?
Answer: Law 11 cover all the aspect about it:

Offside and moving forward. When a team-mate of an offside player has
kicked ahead, the offside player must not move towards opponents who
are waiting to play the ball, or move towards the place where the ball
lands, until the player has been put onside.

law 11.2

11.2 Being put onside by the action of a team-mate
In general play, there are three ways by which an offside player can be put onside by
actions of that player or of team mates:
(a) Action by the player.
When the offside player runs behind the team-mate who last kicked,
touched or carried the ball, the player is put onside.
(b) Action by the ball carrier.
When a team-mate carrying the ball
runs in front of the offside player, that player is put onside.
(c) Action by the kicker or other onside player.
When the kicker, or team-mate who was level with or behind the kicker when (or after) the ball was kicked, runs in front of the offside player, the player is put onside. When running forward, the team-mate may be in touch or touch-in-goal, but that team-mate must return to the playing area to put the player onside.

and law 11.3 covers the onside but from the opponent team view

11.3 Being put onside by opponents
In general play, there are three ways by which an offside player can be put onside by an action of the
opposing team. These three ways do not apply to a player who is
offside under the 10-Metre Law.
(a) Runs 5 metres with ball.
When
an opponent carrying the ball runs 5 metres, the offside player is put
onside.
(b) Kicks or passes.
When an opponent kicks or passes the
ball, the offside player is put onside.
(c) Intentionally touches
ball.
When an opponent intentionally touches the ball but does not
catch it, the offside player is put onside.

So to clear it a little, if you are not behind the kicker, you have to wait for the kicker to run past yourself, or wait for the other team to catch the ball and play with it (in the case of a far kick, this is usually what happens)
source: IRB Laws (via the Wayback Machine). As of January 2019, the current offside law is Law 10 which contains essentially the same content but different wording.


Angular 4: Output data from dynamic modal to component

Question: I am using material design and have a dialogService set up for dynamically loading MdDialog. I'm trying to make a search dialog with search filters that when submitted it brings you to a search-results component route. And I can't figure out how to output the search data to the search-results component.
./dialog-service.ts
@Injectable()
    export class DialogService {
    private dynamicModalComponent: DialogComponent;

    public init(dynModal: DialogComponent) {
        this.dynamicModalComponent = dynModal;
    }

    public show(component: Type<any>, configuration?: MdDialogConfig) {
        this.dynamicModalComponent.showModal(component, configuration);
    }

    public hide() {
        this.dynamicModalComponent.hideModal();
    }
}

./modules/search.component.html

Search

<md-input-container class="full-width search">
    <input mdInput placeholder="search" color="primary" />
</md-input-container>

    <md-radio-group class="radio-buttons" [(ngModel)]="searchFilterValue">
        <md-radio-button class="r-button" [value]="sf.value" *ngFor="let sf
of searchFilter">
            {{sf.name}}
        </md-radio-button>
    </md-radio-group>

<md-dialog-actions class="actions">
    <button md-button (click)="hide()">Cancel</button>
    <button md-raised-button (click)="search()"
          color="primary">Search</button>
</md-dialog-actions>

./modules/search.component.ts
import {Component, OnInit} from "@angular/core";
import {DialogService} from "../dialog/dialog.service";
import {Router} from "@angular/router";
@Component({
    selector: 'search',
    templateUrl: './search.component.html',
    styleUrls:['./search.component.scss']
})
export class SearchComponent implements OnInit {
searchFilterValue;
searchFilter = [
    {
        name: 'Groups',
        value: 'groups',
    },
    {
        name: 'People',
        value: 'users',
    },
    {
        name: 'Events',
        value: 'events',
    },
    {
        name: 'Posts',
        value: 'posts',
    }
];
constructor(private _dialogService: DialogService,
            private router: Router){
    this.searchFilterValue = 'groups';
}

ngOnInit(){}

hide() {
    this._dialogService.hide();
}

search() {
    this.hide();
    this.router.navigate(['/search']);
}
}

Answer: You have several options:
1) You could use optional or query routing parameters. Then as part of the router.navigate, you'd also pass along the parameters. This is a great option if you need to pass data from this component directly to another component.
2) Another option is to build a service. The service holds onto the search filter values. The search component sets the values into the service and the component then reads the values from the service.
Do one of these options sound like they could work for you?
Answer: You can define an output event for hide/close event and pass result as event argument.Other components can subscribe such event to handle result.


Is react-tap-event-plugin still needed in 2018?

Question: Is https://github.com/zilverline/react-tap-event-plugin still needed nowadays? Or it has been implemented into React's source directly and tap delay is gone.
Comment: The first paragraph of https://github.com/zilverline/react-tap-event-plugin explains it, doesn't it? These are browsers and not React that address the problem.
Answer: You have the answer inside your own link.
Developers.google.com
To remove the 300-350ms tap delay, all you need is the following in the  of your page:
<code><meta name="viewport" content="width=device-width">
</code>
The usage of the plugin is deprecated because new versions of React removes a lot of internals  this plugin depends on.
Since the problem has been fixed in most browsers by now you should migrate away from this plugin.


Disable user registration for certain pattern of: IP address, name, mail

Question: I run a Drupal 7.10 / CentOS 6.2 website (where users can register after confirming their mail by clicking on a link) and there is a person registering at my site every night and then changing his name to obscene words.
First I've added a line to /etc/sysconfig/iptables to block his area:
<code>-A INPUT -s 18.104.22.168/16 -j DROP
</code>
but this has blocked other users from that area (Alma-Ata city).
The pattern of this user is:

His IP address: strpos($_SERVER['REMOTE_ADDR'], '2.132.') === 0
His mail (changing every time): preg_match('/firstname.lastname@example.com/i', $mail)
His name (usually): stripos($name, 'st') !== FALSE

As you see - I have all the components there, I just need to know a good spot to put this code in. Anywhere to make his registration more difficult. An ideal case would be to sent  admin a mail for registration verification, but just bailing out of the registration script (which one is it please?) would be okay too.
Answer: Drupal 6 had the possibility of avoid specific usernames, email addresses, matching an SQL pattern match could be used from users, and avoid those users matching those conditions could log in. There was also a setting for avoiding users could be log in from specific IPs, which is the only part kept in Drupal 7.
The other part has been moved to a third-party module I maintain. Being the maintainer, I can tell you that I didn't recently commit code for User restrictions, which at the moment is not usable because the code needs to be fixed. I count to start committing the code I have developed in the previous months starting from tomorrow, if there is not something else that take me busy.
I actually need it in my website, which is running Drupal 7. I count to make the module as much generic as possible, and allow other modules to integrate with it through hooks; for example, the code I developed allows other modules to add rules that would be used to temporary block users.
For avoiding users would use specific usernames, there is also Ban List.

Banlist allows the administrator to disallow users from using a username from a list of usernames. The list consist of usernames such as: admin, administrator, root, demo, test, superuser, etc.
Although core can handle this, the primary purpose of the module is for people in the community to contribute to the list and make it very easy for everyone else to take advantage.


How to set Dynamically UIScrollView height in Swift 4 IOS?

Question: If the height of scrollview not set. then scrollview will not scrollable.
To make it scrollable. I set height statically in code like this.
scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: 1000)

Is there any way i can set height dynamically??
Comment: @MahendraGP I am not saying you'r wrong, even you are absolutly right but take a case when user adding subviews in scrollview by code work. There are many scenarios where doing UI from programatically is even more easier then by storyboard. Thatsy i said it depends on requirement.
Comment: best wat to use auto layout !!
Comment: can you explain it some more. Thanks
Comment: Using autolayout you need to give constraints to subviews of scrollview so from constraints scrollview content height is automatically calculated...you don't need to set it explicitly.
Comment: @MahendraGP It all depends on requirement.
Comment: It is not dependent on requirement no one is going to complain you that why you have used auto layouts or frames....its up to you what you want to go with....and auto layouts are now widely used than frames...
Comment: I understood..but again its up to the developer that if he is good in auto layout then he can do all the this that can be done by frames.
Comment: You have to pass all subview `height` in `scrollView.contentSize.height`. if There's 3 labels in that than `lbl1.frame.size.height + lbl2.frame.size.height + lbl3.frame.size.height`
Comment: CGRect contentRect = CGRectZero;

for (UIView *view in self.scrollView.subviews) {
    contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;    This will help you to find whole height of scrollview includes it subviews.
Answer: One option using AutoLayout is to make UIStackView a subview of the UIScrollView. Set the constraints (leading, trailing, top, bottom and width) of UIStackView to be equal to UIScrollView. Set the height of the subviews (alternatively make them dynamic to resize depending on their own subviews). Then add the subviews to the UIStackView by using addArrangedSubview and it will handle the constraints for you. The UIScrollView's contentSize will adapt to the UIStackView depending on it's subviews.
Don't forget to change the axis property of UIStackView to vertical.
Here is an example using NSLayoutAnchor:
override func loadView() {
    let view = UIView()
    view.backgroundColor = .white

    let redView = UIView()
    redView.backgroundColor = .red
    redView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        redView.heightAnchor.constraint(equalToConstant: 400.0)
    ])

    let blueView = UIView()
    blueView.backgroundColor = .blue
    blueView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        blueView.heightAnchor.constraint(equalToConstant: 700.0)
    ])

    let scrollView = UIScrollView()
    scrollView.backgroundColor = .black
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(scrollView)
    NSLayoutConstraint.activate([
        scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        scrollView.topAnchor.constraint(equalTo: view.topAnchor),
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ])

    let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.addArrangedSubview(redView)
    stackView.addArrangedSubview(blueView)
    scrollView.addSubview(stackView)
    NSLayoutConstraint.activate([
        stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
        stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
        stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
        stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
        stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
    ])

    self.view = view
}

If you don't want to use UIStackView, just add every subview directly to UIScrollView and set the constraints how they relate to each other.
Answer:
If you wanted to do with storyboard then first go through this.
If you wanted to do by code as you done it code then first you have to calculate the inner content height programatically the use the below code.
scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: contentHeight)

Still have any query then ask.
Comment: Thanks. I am going to do it programmatically. So how to calculate the inner content height programmatically?
Comment: @SajidZeb As i said in comments it depends on your UI design. and code logic what you have done and how you done.


Next.JS rewrite isn't happening

Question: I hope this question is clear, I am somewhat at the end of my mental resources at the moment.
I have some Nginx rewrites happening in production, I need to reproduce this functionality in my nextjs app on the frontend.
So my rewrites rules look like the following
const rewrites = process.env.NODE_ENV === "development" ?
  [{
    source: '/ovp/userdevices',
    destination: 'https://userdevices.backendservices.dk'
  },

  {
    source: '/ovp/userdevices/:path*',
    destination: 'https://userdevices.backendservices.dk/:path*'
  }
  ] : [];

and in my configuration
async rewrites() {
    console.log("Rewrites called");
    return rewrites;
  },

I get the console log, and the array is what it is supposed to be. But my /ovp/userdevices urls never get rewritten, and so we are always running localhost:3000/ovp/userdevices.
I am supposing at the moment that the rewrites never happen because these are supposed to be done on the serverside and maybe everything is being rendered frontend but I don't know how to test this supposition.
My current config looks like
{
  poweredByHeader: false,
  target: 'serverless',
  distDir: 'build',
  basePath: '',
  rewrites: [AsyncFunction: rewrites],
  redirects: [AsyncFunction: redirects],
  pageExtensions: [ 'route.js' ],
  env: {
    SUPPORTED_BROWSERS: 'chrome 84;chrome 83;edge 84;edge 83;firefox 79;firefox 78',
    APP_VERSION: '0.0.1',
    APP_NAME: 'some-app/app-self-service'
  },
  webpack: [Function: webpack]
}

Can anyone point me to a reason why the rewrites would not be happening?
On Edit: I'm not going to delete the question in that maybe someone will find a use for it, but I was wrong, it was being rewritten it's just the url it was going to was failing. I didn't figure out why because I found a simpler hack to solve my problem.
Comment: Does `/ovp/userdevices` exist as a route in your `pages/` folder?
Comment: it's hard to read out what is the actual problem; can you describe expected vs observed outcome more precisely?

yes Next.js rewrites are meant to work in Node.js requests only, i. e. server side.
Answer: You can't use the name rewrites twice. Make next.config.js look like this:
module.exports = {
  async rewrites() {
    console.log("Rewrites called");
    return process.env.NODE_ENV === "development"
      ? [
          {
            source: "/ovp/userdevices",
            destination: "https://userdevices.backendservices.dk",
          },

          {
            source: "/ovp/userdevices/:path*",
            destination: "https://userdevices.backendservices.dk/:path*",
          },
        ]
      : [];
  },
};

Comment: if you using "const rewrites = require('./config/rewrites')", define it directly in the next.config
Answer: In my case, error was fixed after I added .env.local file.
Comment: .env file also seems to work

Next.JS rewrite isn't happening


Problema dataTable e tabelas criadas dinamicamente

Question: Boa tarde Galera,
Estou com problema ao usar o dataTable() em uma tabela criada dinamicamente.
no HTML eu tenho o corpo da tabela.

    ID
    Módulo
    Quantidade OP
    Código
    Quantidade
    Data
    Status
    NF

E no .JS eu acrescento as <tr> e as
Aí vem o problema, como eu acrescento as linhas e colunas após o DOM ser criado?
$("#mytable").dataTable({paging: false});

não reconhece as linhas e colunas da tabela.
Alguém pode me ajudar? muito obrigado.
Comment: Qual função está usando para inserir as linhas ?
Answer: Crie uma função com esse seu código js e chame ela quando a pagina toda for carregada.
Como fazer:
No body inclua o atributo onload, desta maneira:

Dentro do < script > inclua isso:
function suaFunçãoDeCriarTabela(){

   //Seu código aqui (Só será iniciado quando a pagina estiver carregada)
}

Assim adicionará itens à tabela só quando a pagina inteira for carregada
Comment:   está apresentando erro de Uncaught ReferenceError: showAlltable is not defined, mas no meu arquivo js a função já está criada
Comment: Edite sua pergunta adicionando o código da função "showAlltable()". Pode haver algum erro nele.
Comment: Seu código *js* está na Head ou dentro do Body?
Comment: Ele está no head
Answer: Sei que já faz tempo, mas talvez isso ainda seja útil para alguém:
Pelo que entendi, a sua $("#mytable").dataTable({paging: false}); não reconhece as novas linhas incluídas - é desta forma que precisa ser mesmo. Quando vc trabalha com Data Table as alterações são feitas de forma semelhante a um "DataSet", ou seja: vc faz uma cópia dos dados, altera o que precisa nesta cópia e depois salva as suas alterações na tabela definitiva.
Para incluir novas linhas a maneira mais fácil é utilizar um objeto que contenha um atributo para cada coluna da sua tabela. Além disso , sempre que vc adiciona novas linhas será necessário redesenhar a tabela (utilizando o ".draw()" - dataTable.draw()) para que os dados novos sejam renderizados e apareçam na tela.
Exemplo:
Considere uma tabela chamada "myTable" com os campos nome, cpf e estadoCivil. Desta forma crie um objeto cliente com estes atributos:

Para adicionar este objeto na data table temos que utilizar uma função semelhante a esta:

function addRowsDataTable(cliente){
//criando o "data set" - captura todos os dados da DataTable original e inclui eles na variavel dTable (é um array de objetos)
    dTable = $('#myTable').DataTable();
  //incluindo o objeto cliente
  dTable.rows.add(
            [{
                "nome"              : cliente.nome,                 //0
                "cpf"               : cliente.cpf,              //2
                "estadoCivil"   : cliente.estadoCivil
       }]
  );
    //renderizando novamente a dataTable com os novos dados.
    dTable.draw();
}

OBS: lembre-se de que na sua página HTML é necessário incluir as referências da data table:

e também:
<link rel="stylesheet" type="text/css" href="/DataTables/datatables.css">

Como fazer?
Chame a função addRowsDataTable  e passe como parâmetro um objeto cliente com os atributos necessários. A função vai adicionar uma linha com os dados do cliente e renderizar novamente a tabela.


Is GotW #47 halfly wrong?

Question: GotW #47

The Wrong Solution
"Aha," many people -- including many experts -- have said, "let's use uncaught_exception() to figure out whether we can throw or not!" And that's where the code in Question 2 comes from... it's an attempt to solve the illustrated problem:

//  The wrong solution
//
T::~T() {
  if( !std::uncaught_exception() ) {
    // ... code that could throw ...
  } else {
    // ... code that won't throw ...
  }
}

The idea is that "we'll use the path that could throw as long as it's safe to throw." This philosophy is wrong on two counts: first, this code doesn't do that; second (and more importantly), the philosophy itself is in error.
The Wrong Solution: Why the Code Is Unsound
One problem is that the above code won't actually work as expected in some situations. Consider:

//  Why the wrong solution is wrong
//
U::~U() {
  try {
    T t;
    // do work
  } catch( ... ) {
    // clean up
  }
}

If a U object is destroyed due to stack unwinding during to exception propagation, T::~T will fail to use the "code that could throw" path even though it safely could.

I believe that explanation above is completely incorrect, if std::uncaught_exception returns true it is ALWAYS unsafe to let any function including destructor to exit with another exception. Prove

If any function that is called during stack unwinding, after initialization of the exception object and before the start of the exception handler, exits with an exception, std::terminate is called. Such functions include destructors of objects with automatic storage duration whose scopes are exited, and the copy constructor of the exception object that is called (if not elided) to initialize catch-by-value arguments.

Same words in c++ (terminate is called in ~YYY()):
#include <exception>
#include <iostream>

int main(int argc, char* argv[])
{
    struct YYY
    {
        ~YYY()
        {
            std::cout << "during stack unwinding before throwing second exception " << std::uncaught_exception() << std::endl;
            throw std::exception();
        }
    };
    struct XXX
    {
        ~XXX()
        {
            std::cout << "after first exception thrown but not catched " << std::uncaught_exception() << std::endl;
            if (std::uncaught_exception())
            {
                try
                {
                    YYY yyy;
                }
                catch (const std::exception&)
                {
                    std::cout << "in second exception catch block " << std::uncaught_exception() << std::endl;
                }
            }
        }
    };
    try
    {
        XXX xxx;
        std::cout << "before throwing first exception " << std::uncaught_exception() << std::endl;
        throw std::exception();
    }
    catch (const std::exception&)
    {
        std::cout << "in first exception catch block " << std::uncaught_exception() << std::endl;
    }
    std::cout << "after both exceptions catched " << std::uncaught_exception() << std::endl;

    return 0;
}

My question is did I miss something and Herb Sutter is right for some specific case or he is absolutely wrong in this piece of the explanation?
Answer: It is a question of what is meant by "any function that is called during stack unwinding" in the standard text.
I believe the intent was to prevent "any function that is called directly by the stack unwinding mechanism" to terminate with an exception, i.e. to throw another (new) exception into the active stack unwinding session. This requirement is not supposed to apply to any subsequent (nested) functions calls made internally by any function that is called by the original stack unwinding session.
As long as new exceptions are thrown and caught internally, without being allowed to escape into the active stack unwinding session, they are allowed. Herb's explanation is in full agreement with the standard: it is possible to throw new exceptions during stack unwinding as long as they are intercepted and suppressed internally.
Your example calls terminate() for a different reason. You are probably compiling with post-C++11 compiler. In C++11 destructors are noexpect by default, which is why your YYY::~YYY() simply calls terminate() regardless of whether stack unwinding is in progress, or of any other external conditions (GCC will even warn you about exactly that).
Declare it as
~YYY() throw(std::exception) // or `noexcept(false)`
{
  ...

to test the intended behavior of the code. And no, it does not call terminate(): http://coliru.stacked-crooked.com/a/296ffb43b774409e
Herb's outdated code, obviously, suffers from the same problem.
Comment: I do agree with the explanation why ~YYY in my example called terminate. I just don't understand what you mean by "any function that is called directly by the stack unwinding mechanism". Can you provide c++ example what you mean? Other words, I don't understand why it is ok from the standard point of view if I add noexcept(false) to the ~YYY why it does not call terminate?

Is GotW #47 halfly wrong?


Alternativa para o uso do UNION no mysql/php

Question: Bom dia, estou fazendo a soma dos elementos de uma coluna (que chamei de MinhaColuna) em função de outra, chamada "turno". Há três valores para turno, portanto preciso que o código de retorne três valores distintos de soma. Para isso, estou usando a função UNION do mysql. Ele me retorna os valores sem problemas. Contudo, ao fazer a conexão em PHP, o resultado do turno 3 some, sendo devolvido apenas os dois primeiros valores. Seria o UNIONo causador do problema no PHP? Existe alguma alternativa para o uso do mesmo ou solução para este caso?
SELECT sum(MinhaColuna) as 'Soma1' from TabelaX where turno='Um' UNION
SELECT sum(MinhaColuna) as 'Soma2' from TabelaX where turno='Dois' UNION
SELECT sum(MinhaColuna) as 'Soma3' from TabelaX where turno='Três'

Comment: Poste o código de como está gerando a tabela... porque se o seu select está ok, então o problema é no php
Comment: Tendou usar o `UNION ALL` ? Caso valores coincidirem, ele pode não estar trazendo.
Comment: Tentei sim, mas o erro persiste.
Comment: Acredito que o problema está no seu código PHP e não na sua query ou seu banco. Se você acha que o problema é do UNION tenta fazer essa query com GroupBy: SELECT sum(MinhaColuna), turno from TabelaX where turno in ('Um', 'Dois', 'Três') group by turno
Answer: Seu SELECT deve retornar o resultado correto, os dados disponíveis podem causar esse comportamento ou há algo errado no código PHP. Acho que dados disponíveis é que causam o comportamento que você vê, último parágrafo da resposta comenta este caso.
Apesar disso, uma maneira geralmente melhor de fazer seria usar GROUP BY:
SELECT turno, SUM(MinhaColuna) as Soma FROM TabelaX
WHERE turno IN ('Um', 'Dois', 'Três') GROUP BY turno;

O WHERE é para limitar aos turnos desejados, porém não lembro se o "IN" usa índice nas comparações. Se o WHERE for removido, as somas para todos os turnos serão retornadas, talvez seja o resultado desejado.
Esta query vai retornar as somas de cada turno, porém, se não houver nenhum registro em algum turno, ele não aparecerá (mesmo comportamento da outra query neste caso).


In fuzzy sets, why do fraction notation, $\int$, and $+$ have different meanings than usual?

Question: I have just started to learn about fuzzy sets from this website which is written in Persian. Here are some quotations,

If $U$ is a finite set, we usually denote the fuzzy set $A$ as
$$
A=\left\{\frac{\mu(x_1)}{x_1},\frac{\mu(x_2)}{x_2},\frac{\mu(x_3)}{x_3}, \cdots, \frac{\mu(x_n)}{x_n}\right\},
\ x_1,x_2\cdots,x_n \in U
$$
Here the fractions do not mean fraction numbers.
Sometimes we denote fuzzy sets as
$$
A=\dfrac{\mu(x_1)}{x_1}+\dfrac{\mu(x_2)}{x_2}+\dfrac{\mu(x_3)}{x_3}+\cdots+\dfrac{\mu(x_n)}{x_n}
=\sum_{i=1}^n \dfrac{\mu(x_i)}{x_i}
$$ Here the purpose of $+$ is to separate the elements of the set.
If $U$ is an infinite set, we call the fuzzy set "infinite". In this case, we use $\int$ instead of $\sum$. for example if $x$ is between $0$ and $2$, then the fuzzy set $A$ can be denoted with respect to $\mu(x)$ as:
$$A = \int_x \dfrac{\mu_A(x)}{x}$$
As you can see, we don't have $dx$ in above expression since $\int$ doesn't mean integral here.

It is very strange for me that usual mathematics notation is used here with different meaning. Can you explain why this happens in this context and how is it valid? Am I missing some basic concepts?
Edit:
Now I looked up Glossary of mathematical symbols. It seems that the usage of plus sign might be relevant in this context,

$+$

Sometimes used instead of  $\sqcup$  for a disjoint union of sets.

But not sure if it really means disjoint union of sets here.
Answer: There are simply not enough symbols available to have a different symbol for every concept in all of mathematics. It is difficult to invent a new symbol or notation when writing a document electronically (it's easier when handwriting), so in a limited context, it may be convenient to reuse a common symbol or notation with a different meaning, if it is carefully explained so that it cannot be confused (in context) with its standard meaning.


How to compute a measure of distance between sites with continuous variables?

Question: I have a dataframe with each row being a different site (51 sites), and each column being mean values of a different continuous environmental variable (19 variables).
I am trying to calculate a measure of environmental similarity/dissimilarity by using a distance calculation between sites.
I would like to calculate either a standardized Euclidean distance or Mahalanobis distance.
I have managed to get them to work with both the distance function in the package ecodist, and the dist.quant() function in the package ade4 in [R].
E.g.
AusEnvDist <- distance(AusEnvNum, method="euclidean", sprange=NULL)

However my outputs are the same regardless of how the dataframe is organized (i.e., sites being in rows or columns) – I get an output matrix of $19\times19$ instead of $51\times51$ – i.e., it's not calculating the distance between sites, but between variables.
Any ideas on how to fix this?
Or a better method for getting a singular "environmental" value for each site?
Answer: I tried this and got different results (as expected) from the distances of a data frame and its transpose:
library(ade4)
x1 <- rnorm(10, 2, 1)
x2 <- rnorm(10,1,1)
dframe <- cbind(x1,x2)
dist1 <- dist.quant(dframe, 1, diag = TRUE, upper = TRUE)
dist1
dist2 <- dist.quant(t(dframe),1, diag = TRUE, upper = TRUE)
dist2

dist2 gives a single distance (between x1 and x2). dist1 gives a $10\times10$ matrix (since I put upper = TRUE and diagonal = TRUE)
Comment: That helped me work through the problem, thank you. Turns out it didn't want the first column of names in the file, once those were removed it worked perfectly.