What is the significance of the red outline in a failed Coded UI test screenshot?

Question: I'm trying to debug a VS2010 Coded UI test which is supposed to find and select a particular row in a WinTable.  The test passes on my local machine, but fails on our nightly test run (which executes on a remote VM).  The MSTest framework includes a screenshot of the UI at the time of failure with the failure report, which clearly shows that the wrong row of the WinTable was selected.  HOWEVER, in the screenshot the CORRECT control is outlined with a thick red border that is definitely not part of our regular UI.
I tried searching MSDN (and of course this forum) but could not find any explanation of what the red line signifies.  I'm hopeful the answer will help me get to the bottom of my failing test since it consistently outlines the control I believe should be selected.
Answer: As per my knowledge script is finding the table control correctly but does not find related rows/columns to select the record properly. The reason for this could be

If code is searching using row index then record might not be available on same index
Table must be visible but window is not yet idle due to which it might not have allowed script to interact with table properly
Table must be still rendering when script tried to interact with it
Window might have been opened in restored mode and due to which Row/Column which script is looking for might be off-screen

I would suggest to implement wait logic before selecting the row. The wait loop should continue till window gets idle and rendering of table gets completed.
Hope it helps!


Qual é mais eficiente, realizar várias queries ou usar JOIN?

Question: Tenho uma tabela X que possui os dados do meu usuário, e preciso retornar para o cliente os dados relacionados a esse usuário na tabela Y e Z.
Posso fazer isso usando JOIN ou:
SELECT attr1, attr2 FROM Y WHERE X_id = id
SELECT attr1, attr2 FROM Z WHERE X_id = id

Qual é mais eficiente?
Comment: Eu já fiz uma consulta dessas em um cenário muito específico que ficou mais rápido sendo várias seleções. Foi fazendo uma estrutura de dados para otimizar o resgate desejado, não soube passar para a engine de banco as dicas para ele fazer a consulta rapidamente (Litebase à época). Depois de uns 3, 4 anos, mesmo mudando para SQLite estava mais eficiente separado, mas a manutenção estava muito complicada a propensa a bugs. Então uni tudo em uma consulta só.
Answer: Depende do banco de dados, depende dos dados constantes nas tabelas, depende da configuração da tabela, depende de outros fatores específicos.
Pode ser que seja igual, pode ser que o JOIN seja mais rápido porque ele tem mais condições de otimizar, mas pode ser que ele acabe fazendo algumas operações por ter uma relação que não seriam feitas na consulta separada.
Não tem como responder isso a não ser dizer que tem que medir para seu caso específico com os dados atuais. E pode mudar no futuro. Um banco de dados é um mecanismo cheio de otimizações para o caso.
Se eu tiver que chutar eu diria que o JOIN será mais rápido, mas não confio em chutes.
Coloquei no GitHub para referência futura.
Answer: Acho que a melhor solução seria agrupar tudo em uma única consulta:
SELECT Y.*, Z.*
FROM X
JOIN Y on Y.id = X.id
JOIN Z on Z.attr1 = Y.attr1
WHERE X.id = @id

Você poderia remover a tabela X do join e usar de um subselect, mas acredito que a solução acima tem melhor performance, já que não repete selects para a comparação do X.id.
Answer: Cada SQL (select) será executado uma vez, enviado (rede) ao banco de dados, criado um contexto para a query e retornado o resultado(rede de novo).
Pensando nesse fluxo sendo executado milhares de vezes, o JOIN é mais eficiente. Na verdade, um único SQL tende a ser mais eficiente para as consultas pequenas.
Quando o SQL fica muito grande, aí as coisas mudam e pode ser melhor quebrar em pedaços.
Quando o assunto é banco de dados e performance, o caminho é pesquisar, buscar as melhores práticas, mas nada evita os testes. Se tem dois caminhos possíveis, testes os dois e veja os resultados.


How to use CKEditor for basic HTML formatting with webforms automatic emails?

Question: How do I use CKEditor for the 'email template' field when setting an automatically generated email for a webforms submission.
The email template field is found when you go to Content of type 'webform' > Click the Webform Tab > Click the sub-tab Emails > And edit an existing automatic email.
I want to render this textbox as CKEditor and have the email follow through with any bold, underline and heading HTML formatting.
Comment: It's not a good idea to add html to emails, gmail, hotmail, etc... use to delete tags, css, etc...
Comment: All major email clients have HTML formatting. Just need to make sure the header sends the email as HTML rather than plain text.
Answer: I think the main goal is to receive HTML-formatted emails triggered by Webform module, right? This is how I achieved it:

Create and tune a new Text Format, specifically for emails (admin/config/content/formats)
Install Mime Mail module. It enables you to send HTML-formatted emails. Make it use the just-created text format in settings.
Install Mail System module. It provides you the UI for changing mail system globally or per module, if needed. Simply speaking, with this module you can easily configure HTML mail e.g. for Webform, but leave plain-text format for system emails.
You can use HTML tags in Webform > E-mails > Edit > E-mail template textarea. Mails from the website will be HTML-formatted.

Yes, it does not bind CKEditor to E-mail template textarea, but do you really need it? (If yes, I believe it is possible by creating a custom module that overrides the webform-email-edit-form form changing the element type from "textarea" to "text_format", see e.g. this topic).
Upd. I have just found a separate module for doing the latter thing: Webform Email Input Filter.


RecyclerView: No adapter attached; skipping layout - recycleView error

Question: Its giving me "RecyclerView: No adapter attached; skipping layout" error but in my opinion adapter is correctly attached. Please help.
    public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private RecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
        layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        requestJsonObject();
    }

    private void requestJsonObject(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="https://api.myjson.com/bins/2t4j3";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response " + response);
                GsonBuilder builder = new GsonBuilder();
                Gson mGson = builder.create();
                List<ItemObject> posts = new ArrayList<ItemObject>();
                posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
                adapter = new RecyclerViewAdapter(MainActivity.this, posts);
                recyclerView.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error " + error.getMessage());
            }
        });
        queue.add(stringRequest);
    }
}

I was moving my methods, but its not working. I was looking here for answer but there was only problems with wrong implemented adapters. I dont't know whats wrong here.
Comment: post your full code and logcat also
Answer: Try to put this line:
adapter = new RecyclerViewAdapter(MainActivity.this, posts);

After adding a LayoutManager to the RecyclerView. Of course the list will be empty, but just init RecyclerAdapter and assign it to the RecyclerView
Then, when Volley completes it's request, use:
recyclerView.getAdapter().addAll(posts);
recyclerView.getAdapter().notifyDataSetChaged();

The last commands add elements to the RecyclerView's adapter and notify LayoutManager of the change.
Answer: You are calling setAdapter in a delay thread. When the view is created in the main thread, the Recyclerview do not have an adapter.
Put this two lines before setLayoutManager
List<ItemObject> posts = new ArrayList<ItemObject>();
adapter = new RecyclerViewAdapter(MainActivity.this, posts);

In onResponse, you can ethier set a new adpater or update the data in the adapter which depends on your implementation.
Comment: I'm sorry but its not working :/ I was moving adapter in a few different places like before/after layout manager but its not working
Comment: i setAdapter before layoutManager and error dissapear but app is not working, its only showing white space and log cat is clear :/ https://scontent-fra3-1.xx.fbcdn.net/v/t34.0-12/13624505_1107401415965387_789590380_n.png?oh=a78e6331d61e135edd4cd9c757b85698&oe=577F9CFC
Comment: You should either keep the `setAdapter` in onResponse (This means TWO calls) or update your list im the adapter and call notifyDataSetChaged()``


Fazer com que visualização google-charts bar inicie do zero

Question: Tenho um gráfico do google charts no sistema que pode ser que venha zerado, caso venha zerado preciso que inicie do 0, porém não estou conseguindo configurar, tentei usar viewWindow.min porém não funciona.
A documentação não cita nada a respeito.

google.charts.load('current', {
  packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

  var data = google.visualization.arrayToDataTable([
    [
      "",
      "",
      {
        "role": "style"
      },
      {
        "role": "annotation"
      }
    ],
    [
      "A",
      0,
      "#64BBF6",
      "0 | R$ 0,00"
    ],
    [
      "B",
      0,
      "#2A8FD7",
      "0 | R$ 0,00"
    ],
    [
      "C",
      0,
      "#0862A2",
      "0 | R$ 0,00"
    ],
    [
      "D",
      0,
      "#64BBF6",
      "0 | R$ 0,00"
    ]
  ]);

  var options = {
    title: '',
    chartArea: {
      width: '60%'
    },
    height: 100,
    hAxis: {
      title: '',
      viewWindow: {
        min: 0,
      },
    },
    vAxis: {
      title: '',
      viewWindow: {
        min: 0,
      },
    },
    legend: {
      position: "none"
    },
    annotations: {
      textStyle: {
        bold: true
      },
      alwaysOutside: true
    },
    tooltip: {
      trigger: "none"
    }
  };

  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

  chart.draw(data, options);
}

No exemplo acima ele inicia do -1, preciso fazer que comece do 0, mesmo quando não há dados
Answer: Na verdade seu gráfico já começa no 0, ele só gera os negativos quando nenhum dos valores é maior que zero. Não sei dizer o por que isso ocorre, mas você pode contornar usando o hAxis.ticks para substituir essa geração automática.
Mudei as opções do seu hAxis adicionando ele:
hAxis: {
    title: '',
    ticks: [0,1,2,3],
    viewWindow: {
    min: 0,
}

Veja funcionando no seu exemplo abaixo:

google.charts.load('current', {
  packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

  var data = google.visualization.arrayToDataTable([
    [
      "",
      "",
      {
        "role": "style"
      },
      {
        "role": "annotation"
      }
    ],
    [
      "A",
      0,
      "#64BBF6",
      "0 | R$ 0,00"
    ],
    [
      "B",
      0,
      "#2A8FD7",
      "0 | R$ 0,00"
    ],
    [
      "C",
      0,
      "#0862A2",
      "0 | R$ 0,00"
    ],
    [
      "D",
      0,
      "#64BBF6",
      "0 | R$ 0,00"
    ]
  ]);

  var options = {
    title: '',
    chartArea: {
      width: '60%'
    },
    height: 100,
    hAxis: {
      title: '',
      ticks: [0,1,2,3],
      viewWindow: {
        min: 0,
      },
    },
    vAxis: {
      title: '',
      viewWindow: {
        min: 0,
      },
    },
    legend: {
      position: "none"
    },
    annotations: {
      textStyle: {
        bold: true
      },
      alwaysOutside: true
    },
    tooltip: {
      trigger: "none"
    }
  };

  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

  chart.draw(data, options);
}


Htaccess and uploads

Question: .htaccess files are not my strong point.
I have document uploads going to /uploads. The user should be able to view the documents they've just uploaded by clicking on the document link that appears via ajax after uploading is completed.
However, I would like to be able to password protect the /uploads folder BUT still enable the current user to view the clicked document without having a password request appear.
Is this possible to do in .htaccess?
Thanks for any suggestions.
Answer: Unless you are using HTTP auth to authenticate your user before the upload, this probably cannot be simply done with just .htaccess. You need to know file's owner and compare it with current user, which is way beyond the scope of usual web server's capabilities.
If you may use Nginx or Lighttpd, you may use X-Accel-Redirect/X-Sendfile header. There's also a module for Apache2 called mod_xsendfile. Make all request to /uploads transparently pass through your application, verify access then tell web server to send file. While this requires the ability to configure the web server (which is sometimes not possible) this is probably the most correct and universal solution.
Here are some useful links:

PHP and Ruby on Rails examples (and some general information on configuration)
Python/Django code snippet
Answer: You could use cookie based authentication (mod_auth_cookie) to grant access via htaccess for a particular location.
I am not sure if setting the cookie path to the specific file will work, but its worth a try.
You are better off doing this in the app layer though.
EDIT: This may be a better solution
Answer: I don't think this is possible in .htaccess - since .htaccess has no way of knowing which user uploaded which files. Even if it did (e.g. by putting files in uploads/username/), I don't think .htaccess files are the way to go. I think you'll probably want to enforce this at the application level.

Htaccess and uploads


Set only lower axis range in plotly

Question: I want to set the lower value for the range of an axis and let the higher value to be automatic. Is this possible? I tried this:
import plotly.graph_objects as go
import numpy

x = numpy.linspace(0,1,99)

fig = go.Figure()
fig.add_trace(
    go.Scatter(
        x = x,
        y = 1/x,
        mode = 'markers',
    )
)
fig.update_yaxes(type='log', range=[numpy.log10(3),None])
fig.show()

but it does not work.
Comment: Works for me. What doesn't work for you?

Note that numpy.log10(3) = 0.4-ish. So not that much different from 0...
Comment: What about defining `y` as `y = 1 / x`, then for the range set as `range=[numpy.log10(3), max(y)]`?
Comment: @StephanT for me this code is the same as not setting the range at all.
Comment: @S3DEV yes I know, but I want it automatically as I am plotting stuff within a loop and don't want to take care of yet another extra thing. If there is no alternative I will default to that...
Comment: By the way, I have just upgraded to plotly-5.13.1 and its the same.
Answer: Found some weird behavior indeed.
First: change the range to x = numpy.linspace(0.01, 1, 99) to get rid of the dividezero.
Then remove the log from your range, as the type already seems to force it to a Log. Then try fig.update_yaxes(type='log', range=[1,3]) versus fig.update_yaxes(type='log', range=[1,None])

Set only lower axis range in plotly


Proof: For all n > 0, if $0<x<y$, then $x^n<y^n$?

Question: I need to solve this problem without using induction, only with the following properties.
(1) Trichotomy law;
(2) if $a$ and $b$ are in $P$, then $a+b$ is in $P$;
(3) if $a$ and $b$ are in $P$, then $ab$ is in $P$.
Where P is the collection of all Positive Numbers.
My idea is to use the fact that $y^n - x^n = (y - x)(x^{n-1} + yx^{n-2} + ... + xy^{n-2} + y^{n-1})$.
Thus, since $x \in P$, and $y \in P$, I can build, by (2) and (3), the expansion ($x^{n-1} + yx^{n-2} + ... + xy^{n-2} + y^{n-1})\in P$.  How $(y - x)\in P$ (Since x < y), and by (3), $(y - x)(x^{n-1} + yx^{n-2} + ... + xy^{n-2} + y^{n-1}) \in P$, which implies that $y^n - x^n\in P$, so $x^n < y^n$.
I'm in the right way? Thanks in advance.
Comment: Not sure how you get $x^{n-1}+yx^{n-2}+\cdots+xy^{n-2}+y^{n-1}\in P$ without (at least implicitly) using induction.
Comment: For any finite $n$, I think $x^{n-1} + yx^{x-2} + \cdots + y^{n-1}$ can be (brutally) showed to be $>0$ by applying law (2) $n(n-2)$ times and law (1) $n-1$ times to circumvent induction. Maybe you need to make this more explicit, but I believe that is the right way to do this.
Comment: n = -1 disproves it.
Answer: First a comment:
You don't need the assumption that
$x^2 < y^2$.
In general,
any statement of the form
$\forall n P(n)$
can only be proved by induction,
ultimately.
In your case,
$y^n - x^n = (y - x)(x^{n-1} + yx^{n-2} + ... + xy^{n-2} + y^{n-1})
$
has to be proved by induction
with $P(n)$ being
$y^n-x^n
=(y-x)\sum_{k=0}^{n-1} x^ky^{n-1-k}
$.
Another proof on the factorization
 could use
$\begin{array}\\
(y+x)(y^n-x^n)
&=y^{n+1}-yx^n+xy^n-x^{n+1}\\
&=y^{n+1}-x^{n+1}+xy(y^{n-1}-x^{n-1})\\
\end{array}
$
or
$y^{n+1}-x^{n+1}
=(y+x)(y^n-x^n)-xy(y^{n-1}-x^{n-1})
$.
From this,
if
$x^n-y^n = (x-y)q_n(x, y)$
for $n$ and $n-1$
then
$\begin{array}\\
y^{n+1}-x^{n+1}
&=(y+x)(y-x)q_n(y, x)-xy(y-x)q_{n-1}(y, x)\\
&=(y-x)((y+x)q_n(y, x)-xyq_{n-1}(y, x))\\
\end{array}
$
so
$q_{n+1}(y, x)
=(y+x)q_n(y, x)-xyq_{n-1}(y, x)
$.


What to check when buying a new electric guitar?

Question: I have been playing acoustic guitar for quite some time now. I'm not a beginner but neither am I pro. I'm now looking into buying an electric guitar.
My questions are -

What do I need to check/lookout for when trying out the guitars?
What kind of amplifier should I go for?
What are the other necessary items needed with an electric guitar?
Comment: @leonine, Yes, it really does warrant a separate question. It's generally encouraged here to split up multi-part questions in to individual questions so that each can get a definitive answer and in order to help people searching in the future.
Comment: I would seriously consider putting the amplifier part of this into a separate question.
Comment: @Neil Fein So should I ask another question that specifically deals with amp?
Comment: @yossarian I'll keep that in mind next time. This time though, I think I'm done, thanks to some excellent advice from you and others.
Comment: This is *awfully* broad.  I'd prefer to see separate questions about what to look for in an amp and what equipment might be needed.  I've removed the price info to avoid it being a shopping recommendation, though I think it could still be improved.  The answers don't devolve into shopping recommendations, though, which is good.
Answer: When it comes to buying your first electric guitar, you want to take your time, try not to rush into it. Once you have found a guitar that suits your intended playing style, and price range, there a few things it would be a good idea to check.

The action: if the action of the strings is too high, it could make playing difficult and uncomfortable for you. If it is too low, you may experience the dreaded fret buzz.
Make sure the neck is straight. A bent or warped neck is really not good.
Quickly check the intonation: play a 12th fret harmonic, and then the 12th fret note. They should be at the same pitch. If they are not, that needs to be fixed.
Check the tone and volume controls work, along with the pickup selector and possibly the tremolo, as Stuart suggested. Check every pickup works, and that it sounds clean. It should not be too hissy or crackly.

Most decent guitar shops offer a free setup with each guitar purchase. Get one done anyway, even if the guitar seems fine. A well set up guitar is a joy to play, one with no setup at all can be an annoying and frustrating experience to play.
With your first amp, I would recommend a small solid state amp. Again, as Stuart mentioned, Line 6, Marshall and Fender all market a very good range of beginner amps, with, in my opinion, The Line 6 Spider IV series being the most versatile and probably cheapest.
In terms of other accessories, you need a cable (the amp does not come with one), a guitar strap, and picks. I would suggest getting a range of pick weights/thicknesses and find your preference, even if you already have a preferred pick when playing acoustic.
I would also suggest a clip on chromatic tuner, so you can tune quickly. You may already have one if you play acoustic, but if not, get one, they are invaluable.
Hope this helps! :)
Comment: -1 because I hate the Line 6 stuff and I think intonation and action aren't relevant as those are fixable issues. The rest of the advice is right on target though.
Comment: I think the line 6 is one of the worst "clean" sounds I've ever heard on an amp. It's terrible. The distortion is passable for the price. But I think it's totally worth spending a little more and getting a Vox that will last you for a lot longer.
Comment: @leonine, personally, in that price range, I'd get a Vox amp and a PRS se guitar. That's a little over your budget (Total $650 - $800), but would be a very nice set up that could grow with you for 5-6 years.
Comment: Yes to the setup.  Especially important if you're going to use different gauge strings than the instrument is strung with in the shop.  As to intonation and action, they are fixable (and that's a big part of the setup), but only to an extent.  This should not be an issue with a name-brand guitar in your price range, though.
Answer: Don't spend too much money on a guitar. When you start playing electric, you'll have a hard time distinguishing between different guitars. Once you've been playing for a while, you'll be able to tell huge differences in the size of the neck, scale, pickups, body, neck joint, etc. But prior to having much experience, you won't be able to tell what it is you really want.
So start cheap (relatively speaking). In the US $300 will get you a decent guitar and $450 will get you a nice guitar. There isn't much reason to spend more than about 500-600 for a first electric (if you think that doesn't qualify as "don't spend too much", I hear you, but you're in for a shock later in your guitar life).
Don't worry about the intonation or action. You can have someone fix that stuff. However, you want to check that the guitar feels well constructed. Do the tone and volume pots move smoothly? Is the neck straight? Does the fretboard fit the neck well? Do the joints look well constructed and clean? Are the frets set cleanly in to the fretboard?
In the lower price range, you can get a lot of variability in construction (you can in the upper range too, unfortunately, but not as much), so you want to make sure that your guitar is well built. Do not order a guitar sight unseen, play before buying. Think about who your favorite electric artists are and see what guitars they play. If they all play something similar, I'd look at that style of guitar for a first go around (a cheaper version, obviously). I'd plan on replacing any first guitar eventually. So don't worry too much about the decision.
You will also need an amp and a guitar cord, maybe a tuner. It's also worth picking up a spare set of strings.
For an amp, I disagree with the Line 6 recomendations. I've had a couple students go that route and they universally hate the sheap Line 6 stuff. The clean sounds are absolutely terrible. You can't really go wrong with Fender or Marshal, however, my absolute favorite starter amps that I recommend to all my students are the Vox Valvetronix. For under $200, these amps sound awesome and will grow with your playing for a lot longer than other stuff in the price range, in my opinion. Again, $200 might sound like a lot, but it's worth it (and it's not a lot, just ask my wife about the $4000 amp I keep bugging her about).
Comment: @slim, I disagree. It's super easy to fix and $200 is almost nothing for an electric guitar. If you're a beginner and don't know what you are doing, you should get a setup on your guitar anyway. It's worth doing for any guitar, pretty much regardless of price.
Comment: I think for $200 you should expect something with good action and intonation as soon as you get it home. You shouldn't need to pay anyone (or spend time) correcting stuff like that.
Answer: First of all play it and make sure it feels good and suits your style.  Check there are no buzzes and rattles from the fret board.  Make sure all the switches and controls work.  Check the tremelo works ok if it has one.  Make sure the action is ok.  Check the paintwork for any scratches etc.   Try and buy from a reputable shop and all the above should have been taken care of.  You will need a guitar,  amplifier, strap, lead, and some picks.
Try and get an amplifier with a clean and dirty sound on it.  Line 6,  Marshall, and fender all make some well priced versatile amplifiers.
Take plenty of time selecting amps and guitars otherwise you will be back in the store in a few weeks looking for new gear.
Comment: I'd also suggest taking a look at the Line 6 PODs and similar effects boxes.  Not for effects but as a cheap amp substitute.  You can practice with headphones, and it stores in your gig bag (or case).  It's a cheap way to get started, and while you're practicing you can be saving up for a better amp.  Then, when you do get a proper amp, you already have some effects to play with.  I have the low-end model, and it even has a built-in tuner that works at least as well as my standalone low-end tuner.
Comment: By "check the fretboard", that means to systematically intone each string at every fret.  There are few things more disconcerting than buying a new guitar only to find that certain notes buzz or have other defects due to manufacturing issues.
Comment: Thanks @Stuart Moir. Some people are against Line 6 amps (see answers below). Could you elaborate on "Try and get an amplifier with a clean and dirty sound on it"
Also, some amps come with effects. Is that a standard thing or more like depends on manufacture thing?
Thanks!
Comment: @Leonine - and some are against other brands of amps. Everyone has a different opinion. You should have a listen to a few and see what YOU like. Clean and dirty refers to 2 channels, one with distortion. As for effects - reverb is fairly standard, but there is a wide range.
Answer: This answer contains most of my advice for guitar selection, no matter what the situation.
As far as amplifiers go, I would follow the same general route: try some, and pick one that works for you.
For a specific recommendation, I like Vox amps. My years-old AD30VT provides good amp models, fantastic genuine-tube dynamics and picking response, and all the effects I need except a standard wah. I also like the power-damping capability that allows me to get high-drive breakup at bedroom volume levels.
But your mileage may vary depending on what you want to play. I also love my Line 6 Pocket Pod for portability and headphone practice - or for using a stereo as an amp in a pinch!
I offer up one final piece of advice for all these equipment-recommendation questions, and like all good advice it comes in the form of a story:

I was trying to pick the items for my first electric rig, and I was terribly nervous. I had little idea what I wanted, less certainty about what I wanted to play, and I had the standard jitters about "What if I don't end up liking this guitar thing?" It was a lot of money to plunk down for something that had hit me out of the blue. I was analyzing everything, reading every review, and generally driving myself insane.
My wife said, "Remember, this isn't the only guitar you're ever going to buy. It's just the first."
And I understood what she was getting at. I was trying to optimize every facet of my decision. I was trying to get a guitar (and amp) that would do everything, that would be perfect for anything I wanted to do. And I wanted to do it as cheaply as possible, in case I ended up dropping the whole thing. I just calmed down, and focused on getting something that worked for me at the time.

I still have and still love the gear I bought then. Occasionally, I consider upgrading to a newer Valvetronix because lights and buttons are shiny and cool. But nobody will ever tear my SZ away from me. Calm down. Stop optimizing. Take care of now.
Answer: I have a friend who is a guitar builder and his advice to me on this topic was quite interesting
He told me to concentrate on the sound of the guitar rather than how it feels to plays because it is often the case that any guitar can be made to play pretty good if you get it setup by someone who knows what they are doing
That said, the cost of doing a guitar up can skyrocket pretty easily so if you can find one that feels right to you that is definitely the thing to go for. Also keep in mind that guitars in the price range you are looking at tend to not have the best pickups so if you find one that sounds pretty lively and bright acoustically chances are that you will be able to up the sound quality pretty drastically just by sticking some replacements in there later
Answer: When it comes to buying an electric guitar, there are a lot of things to look into. If you start listing them all, then it will look like a "things that I want to do in my life".
Form your question it feels to me that you don't know much, when it comes to buying electric guitar. Its good to know what to look for when it comes to buying one. But rather then deciding on these factors, take someone with you who knows about electric guitar and also knows about what AND how you play.
Picking a suitable guitar varies a lot form person to person depending on their play style. Though, selected according to the "101-ways-to-pick-the-best-guitar" might not be the best one for you.
Comment: "Form your question it feels to me that you don't know much, when it comes to buying electric guitar"
Yes, thats precisely why I asked this question. I'm aware of this part- "Picking a suitable guitar varies a lot form person to person depending on their play style. Though, selected according to the "101-ways-to-pick-the-best-guitar" might not be the best one for you."
I needed to know what technical stuff I should know before shell out the money.
Thanks.


What happen when mobile provision expire?

Question: I have an ad hoc build sent to some persons what will happen when the mobile provision will expire? He ca run the app after that?
Answer: No he won't.... you'll have to make a new provisioning profile and re-build. That's the point in an adhoc distro, its mean for testing and doesn't last forever. If they want the full app they'll have to download it off the app store. If you want to give it away for free there's a special feature where you can create free download coupons or something similar in itunes connect.
Comment: Thanks man. I wonder if I renew the mobile provision I must also do an other build?
Comment: you will have to I would assume.


Does $P(A\cap B) + P(A\cap B^c) = P(A)$?

Question: Based purely on intuition, it would seem that the following statement is true, when thinking of the events as sets:
$$P(A\cap B) + P(A\cap B^c) = P(A)$$
However, I am not sure if this is true, and cannot find out how to prove it, or describe a straight forward intuition of it.
Is this equation true? And if not, is there another way to link $P(A\cap B)$ and $P(A\cap B^c)$ with $P(A)$?
Answer: As $A\cap B$ and $A\cap B^c$ are disjoint, we have
$$P(A\cap B)+P(A\cap B^c)=P((A\cap B)\cup(A\cap B^c))=B(A\cap(B\cup B^c))=P(A).  $$
Answer: Yes it is true. In fact is one of the basic properties.
$$
P(A)=P(A\cap\Omega)=P(A\cap\left(B\cup B^c\right))=P((A\cap B)\cup (A \cap B^c))=P(A\cap B)+P(A\cap B^c)
$$


reading (decoding, converting) barcode scanner output via LibUsbDotNet in C#

Question: in a small .net c# app I read the usb output of a barcode scanner with LibUsbDotNet http://libusbdotnet.sourceforge.net/V2/Index.html . The problem is that I don't know how to convert the output into something I can read. The scanner is set to output a return after each barcode, so I need for example to detect that. The output is, I think, in groups of 8 bit bytes. It can be installed as a keyboard input. So what do i have to do with the scanner output to turn it into something readble?
Answer: I think (haven't tried it myself - but I've worked quite a bit with barcodescanners) that this example: http://libusbdotnet.sourceforge.net/V2/html/e61bb81e-108b-4f84-a77d-8ccdecebfa31.htm is the example you are looking for.
Barcode scanners generally post "strings" followed by a linefeed / carriage-return (or both) just like when you use the keyboard to input the code followed by an enter.
The example uses: Console.Write(Encoding.Default.GetString(e.Buffer, 0, e.Count)); in the event, posting the string to the console. You wont need to write to the device, just the read-event will suffice.
Comment: Hi riffnl,

and thank you for the answer! That's exactly how I tried to read the data from the scanner, based on the read only example from here http://libusbdotnet.sourceforge.net/V2/html/9926451f-29bf-4fae-9233-f6467ed072c7.htm but in the console I only see garbage.
Comment: Can you configure this scanner to read specific type of codes?
Comment: Yes. From the configuration guide:

DECODER SELECTION
EAN/UPC
Code 128/EAN 128
Code 39
Code 32
Codabar
Interleaved 2/5

Default is EAN/UPC (AddOn Off).
Comment: Yes, bar code scanner send a string like a keyboard followed by carriage-return (but you cange change this configuring the device) .
I develop same simple application and instead of reading usb port i force focus on a textbox capturing the onchange event.
Comment: Hi Flatlineato, I also thought about the textbox onchange, but I'm worried about losing focus. Also, the frontend of the app is a flash that runs fullscreen, and the flash player disables keyboard input on fullscreen, for security reasons. I don't know if there's a workaround for that, like maybe using zinc to create the projector. So I think reading the usb is the most elegant approach, and then sending stuff to the flash via an xml socket (I have yet to reseach how to do that in .net :) )


What could these email mean?

Question: I receive these mysterious emails with no subject, no body, forged yahoo addresses, and forged Message-Id. I receive hundreds of these every day. I've included a sample of about a dozen below (I've replaced my actual domain name with "myserver.com").
Does anyone else receive emails like these? The IP address resolves to China. What could someone be trying to accomplish by sending these?

From firstname.lastname@example.com Sat Apr 25 10:22:26 2015
Received: from 220.127.116.11 ([188.8.131.52])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEMOVx013935;
        Sat, 25 Apr 2015 10:22:25 -0400
Date: Sat, 25 Apr 2015 10:22:24 -0400
From: firstname.lastname@example.com
Message-Id:
Status: RO
Content-Length: 0
Lines: 0

From firstname.lastname@example.com Sat Apr 25 10:22:28 2015
Received: from 22.214.171.124 ([126.96.36.199])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEMOW1013935;
        Sat, 25 Apr 2015 10:22:27 -0400
Date: Sat, 25 Apr 2015 10:22:27 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0

From email@example.com Sat Apr 25 10:24:27 2015
Received: from 188.8.131.52 ([184.108.40.206])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEOOxR014269;
        Sat, 25 Apr 2015 10:24:24 -0400
Date: Sat, 25 Apr 2015 10:24:24 -0400
From: firstname.lastname@example.com
Message-Id:
Content-Length: 0
Lines: 0

From email@example.com Sat Apr 25 10:25:28 2015
Received: from 126.96.36.199 ([184.108.40.206])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEPPBp014799;
        Sat, 25 Apr 2015 10:25:26 -0400
Date: Sat, 25 Apr 2015 10:25:25 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0

From email@example.com Sat Apr 25 10:25:30 2015
Received: from 22.214.171.124 ([126.96.36.199])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEPPBr014799;
        Sat, 25 Apr 2015 10:25:29 -0400
Date: Sat, 25 Apr 2015 10:25:29 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0

From email@example.com Sat Apr 25 10:26:53 2015
Received: from 126.96.36.199 ([22.214.171.124])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEQpF5015268
        for ; Sat, 25 Apr 2015 10:26:52 -0400
Date: Sat, 25 Apr 2015 10:26:51 -0400
From: firstname.lastname@example.com
Message-Id:
Content-Length: 0
Lines: 0

From email@example.com Sat Apr 25 10:28:00 2015
Received: from 220.127.116.11 ([18.104.22.168])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PERxxY015848
        for ; Sat, 25 Apr 2015 10:28:00 -0400
Date: Sat, 25 Apr 2015 10:27:59 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0

From firstname.lastname@example.com Sat Apr 25 10:34:33 2015
Received: from 220.127.116.11 ([18.104.22.168])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEYVKv017946;
        Sat, 25 Apr 2015 10:34:31 -0400
Date: Sat, 25 Apr 2015 10:34:31 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0

From email@example.com Sat Apr 25 10:37:30 2015
Received: from 184.108.40.206 ([18.104.22.168])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEbS3S019367;
        Sat, 25 Apr 2015 10:37:29 -0400
Date: Sat, 25 Apr 2015 10:37:28 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0

From email@example.com Sat Apr 25 10:50:54 2015
Received: from 184.108.40.206 ([126.96.36.199])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PEoqMW023362;
        Sat, 25 Apr 2015 10:50:53 -0400
Date: Sat, 25 Apr 2015 10:50:52 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0

From firstname.lastname@example.com Sat Apr 25 11:00:47 2015
Received: from 184.108.40.206 ([18.104.22.168])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PF0k6d026108;
        Sat, 25 Apr 2015 11:00:46 -0400
Date: Sat, 25 Apr 2015 11:00:46 -0400
From: firstname.lastname@example.com
Message-Id:
Content-Length: 0
Lines: 0

From firstname.lastname@example.com Sat Apr 25 11:09:10 2015
Received: from 18.104.22.168 ([22.214.171.124])
        by myserver.com (8.13.8/8.13.8) with SMTP id t3PF98Cm028275;
        Sat, 25 Apr 2015 11:09:09 -0400
Date: Sat, 25 Apr 2015 11:09:08 -0400
From: email@example.com
Message-Id:
Content-Length: 0
Lines: 0
Comment: Those headers are lacking information about what arguments the client send in the `HELO` and `RCPT` commands. That information is needed in order to fully understand the pattern. But even with that information, we cannot tell you what is going on inside the mind of the sender of those emails.
Answer: It can be a brute force mail address scan: someone is trying thousands of destination email addresses in the hope to distinguish non-existent emails addresses (for example, due to destination mail server replying with "unknow user" error) from existent (and active) ones.

What could these email mean?


Hint for $\lim_{n\rightarrow\infty} \sqrt[n]{\prod_{i=1}^n\frac{1}{\cos\frac{1}{i}}}$.

Question: How to calculate the following limit:
$$\lim_{n\rightarrow\infty}\sqrt[n]{\prod_{i=1}^n\frac{1}{\cos\frac{1}{i}}}$$
thanks.
Comment: Using `\prod` will render the formula much better than `\Pi`.
Answer: Hint:
$$\lim_{n \to \infty} a_n ^{1/n} = \lim_{n \to \infty} \frac{a_{n+1}}{a_n},$$
and
$$\lim_{n \to \infty} \frac{1}{\cos[1/(n+1)]} = 1$$
Comment: Cauchy's second limit theorem
Comment: many thanks @RRL but why this two test is equal?
Answer: Apply $\ln$ to get
$$\tag 1\frac{1}{n}\left (\sum_{k=1}^{n}\ln [1/\cos (1/k)].\right)$$
Now $\ln [1/\cos (1/k)] \to 0$ as $k\to \infty.$ Therefore $(1),$ which are the Cesaro means of these terms, also converge to $0.$ Hence the limit of the original expression is $1.$


Reference a Variable From Query of Query

Question: I have this on my controller:
$results = Model::where('foreign_id', $id)->get();

The result is:
Collection {#111 ▼
  #items: array:3 [▼
    0 => Model {#112 ▶}
    1 => Model {#113 ▶}
    2 => Model {#114 ▶}
  ]
}

However, I need to access the $results further with these:
$role_A = $results->where('role_id', 1);
$role_B = $results->where('role_id', 2);
$role_C = $results->where('role_id', 3);

My problem is that I am having a error if I reference them via:
$user_A = $role_A->created_at;
$user_B = $role_B->created_at;
$user_C = $role_C->created_at;

I still need include their index position like so:
$user_A = $role_A[1]->created_at;

My problem is that cannot know the index position for me to reference them, for example, $user_A can be any of this below.
$user_A = $role_A[0]->created_at;
$user_A = $role_A[1]->created_at;
$user_A = $role_A[2]->created_at;

Is there any way where I can reference a variable from a query of query more efficiently?
Comment: Try to add `->first()` like this `$role_A = $results->where('role_id', 1)->first();`
Comment: I can't understand what your problem is, how many results `$role_A = $results->where('role_id', 1);` do you want to retrieve?
Comment: check contains(); https://laravel.com/docs/5.3/collections#method-contains if you want to check for exist in collection of objects
Comment: @Takachi - that solved it. thank you very much! you can make an answer for me to accept =)
Comment: @kapitan Done, thanks ! :)
Answer: You need to filter your collection based on the role_id
for a role_id of 2 you do
$results = $results->filter(function ($value, $key) {
    return $value->role_id == 2;
});

or add the where directly in the first query
$results = Model::where('foreign_id', $id)->where('role_id', 1)->first();

Answer: You have to get a collection everytime and not a QueryBuilder.
For example, do something like this
$role_A = $results->where('role_id', 1)->first();
$role_B = $results->where('role_id', 2)->first();
$role_C = $results->where('role_id', 3)->first();

to get what you want as a collection.
Answer: You can simply add a first
$role_A = $results->where('role_id', 1)->first();


Drupal 7: How can I display nodes of specific author in a taxonomy term?

Question: I've a question about taxonomy terms.
In my organization I've actors that work for me and, for each actor I created a taxonomy term containing some information, such as bio, an image etc.
Each actor can create content of type "post". I want display all contents of a specific actor in his own term.
So, if in actors vocabulary there are "alan", "jack" and "Lucy", whan an user reaches alan term, he can see all posts created by Alan, and so on.
For security I don't want the actors select terms when create posts.
I hope you can understand my question.
Answer: I probably wouldn't have used a taxonomy term to store that info, but that's not a big deal.
It sounds like you want a block containing the information in the taxonomy term to appear on a user's post.
You need an entity reference connecting a user/author with the appropriate taxonomy term.
Create View that is based on the taxonomy vocabulary. Use a "contextual reference" starting with the post's node id in the URL to a relationship to the author of the post to another relationship to the taxonomy term using the entity reference.


How can I test significant differences across multiple categories in different dataframes?

Question: I have very basic statistic knowledge and would like to hear some suggestions to analyze my data. I've three dataframes as displayed below:
dataset 1
   Group.1     Moving   Feeding    Standing
1 cluster1 0.04863636 0.1268182 0.7993182
2 cluster2 0.05632530 0.1722892 0.7503012
3 cluster3 0.09220779 0.2644481 0.6118506

dataset2
   Group.1     Moving   Feeding  Standing
1 cluster1 0.03750000 0.1462121 0.7922980
2 cluster2 0.04978355 0.1470238 0.7795848
3 cluster3 0.08214286 0.3216518 0.5642857

dataset3
   Group.1     Moving    Feeding  Standing
1 cluster1 0.07052469 0.1273148 0.7875000
2 cluster2 0.08409091 0.1659091 0.7293706
3 cluster3 0.06950000 0.3496667 0.5476667

I would like to test wether values on cluster 1 row in dataset 1 are statistically different from cluster 1 in dataset 2 and dataset 3. I would like to apply the same information to cluster 2 and cluster 3 for all three datasets.
Is an ANOVA the right test to provide me such information? Maybe multiple t-tests?
Any input is appreciated!
Comment: How did you get on @juansalix?
Comment: ANOVA stands for analysis of variance because they analyse the within group variance as compared to the between group variance. This means tests like ANOVAs require there to be multiple observations for each group. What that means is that you need to have multiple rows in the `Group.1` column with the value `cluster1` in *each* dataset for you to be able to test if there are differences between the datasets. Do you have more data?
Comment: @André.B Yes indeed, this are just average tables of full datasets. I've three different levels (`cluster1`, `cluster2` and `cluster3`) that are based on three different categories (`Moving`,`Feeding`,`Standing`). Therefore, is this what you call a Multi-Way ANOVA instead?
Answer: I think to begin with you want to change the shape of your dataset(s), as this will make it much easier to analyse. In this case I would enter the data into long format; Hadley Wickham has a good paper on this here. To combine the datasets you could carry out something like the following:
df1$dataSet <- "Dataset 1" #The top three lines retain the information about dataset
df2$dataSet <- "Dataset 2"
df3$dataSet <- "Dataset 3"
combine.df <- tidyverse::bind_rows(df1,df2,df3) #This line forms a single dataset

If you provide a easily reproducible dataset then it is a lot easier to help (see this link).
From the sounds of it, and please correct me if I am wrong, you want to test to see if a given cluster is different between datasets across three continuous numeric response variables.
If this is the case then what I would do is to fit a multivariate analysis of variance (MANOVA) to each cluster. What this will do is simultaneously test across all three response variables (Moving, Feeding, Standing) allowing you to control for type I error in a given test. However, you would need to conduct three separate MANOVA's - one for each cluster. Each of these would have the form like:

clust1.man <- manova(cbind(Moving, Feeding, Standing) ~ dataset, subset(combine.df, Group.1 == "cluster1)
clust2.man <- manova(cbind(Moving, Feeding, Standing) ~ dataset, subset(combine.df, Group.1 == "cluster2)
clust3.man <- manova(cbind(Moving, Feeding, Standing) ~ dataset, subset(combine.df, Group.1 == "cluster3)

After this you could control for type 1 error across your three significance tests as well - something like false discovery rate (FDR) might work quite well, as you can even do it by hand.
Let me know how you get on and if you hit any walls.


fail2ban does not ban one address

Question: all. I just installed fail2ban 0.11.2 and it seems to run. All settings are default.
Looking into its log file I see that from qpsmtpd analysis there is one address which it doesn't want to ban, although other addresses (in the same qpsmtpd log) are banned as required. Here is the log copy:
<code>2022-09-11 21:31:03,696 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 18.104.22.168 - 2022-09-11 21:31:03
2022-09-11 21:33:31,672 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 22.214.171.124 - 2022-09-11 21:33:31
2022-09-11 21:36:10,064 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 188.8.131.52 - 2022-09-11 21:36:10
2022-09-11 21:38:38,204 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 126.96.36.199 - 2022-09-11 21:38:38
2022-09-11 21:41:03,928 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 18.104.22.168 - 2022-09-11 21:41:03
2022-09-11 21:43:28,399 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 220.127.116.11 - 2022-09-11 21:43:28
2022-09-11 21:46:06,612 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 184.108.40.206 - 2022-09-11 21:46:06
2022-09-11 21:48:42,169 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 22.214.171.124 - 2022-09-11 21:48:42
2022-09-11 21:51:11,410 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 220.127.116.11 - 2022-09-11 21:51:11
2022-09-11 21:53:50,462 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 184.108.40.206 - 2022-09-11 21:53:50
2022-09-11 21:56:20,768 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 22.214.171.124 - 2022-09-11 21:56:20
2022-09-11 21:58:57,079 fail2ban.filter         [1299]: INFO    [qpsmtpd] Found 126.96.36.199 - 2022-09-11 21:58:57
</code>
Is there something I missed?
Thanks.
Update: To be on the safe side I updated the settings as FindTime=900 and MaxRetry=3.
Comment: If everything is configured as default, the value of "findtime" is set to 10m and "maxretry" to 5 which means an host is getting banned if it makes 5 attempts within 10 mins. In your case the fifth attempt seems to happens after 10mins, I guess this is the reason why is not banning that host
Comment: Thank you, DarkVex, but all the manuals I saw speak about FindTime=15m and MaxRetry=3. To be on the safe side I set them manually to these values.
Still, this IP is not banned.
Comment: This is another demonstration why `recidive` jail is a must. Brute forcing bots became more intelligent and they are now able to accurately test and find out your fail2ban parameters and play just to not be banned.
Answer: OK, I found the solution.
The configuration file has different maxretries for each protocol.
The default value for qpsmtpd was 9 for some reason.
Changing this to 3 solved the issue.

fail2ban does not ban one address


Find the area of the parallelogram $ABCD$

Question: In a parallelogram $ABCD$ the diagonals intersect at $O$. The distances from $O$ to sides $BC$ and $CD$ measure $2$ and $3$ respectively. Calculate the area of the parallelogram if $\angle ABC = 135^o$ (Answer:$24\sqrt2$)
My progess:

$S_{BCD}= \frac{BC.2}{2}=BC\\
S_{OCD} = \frac{CD.3}2=\frac{3CD}{2}\\
S_{BOC}=S_{COD} \implies BC = \frac{3CD}{2}\\
S_{ABCD} = 4BC = 6CD$
...ome detail is missing and I didn't see the given angle function
Comment: Drop perp from $D$ to $BC$, it is two times $OE$. Now given angle of $45^\circ$, you know $CD$. Then as given answer suggests, drop perp from $A$ to $CD$, what is that given $OF = 3$?
Answer: Hint: drop the altitude $AH$ from $A$ to $DC$. What is the length of $AH$? What are the angles in $\triangle DAH$?Can you calculate the area of parallelogram knowing the base and the height?


Using pseudo-priors properly in Bayesian model selection

Question: One approach to model comparison in a Bayesian framework uses a Bernoulli indicator variable to determine which of two models is likely to be the "true model". When applying MCMC-based tools for fitting such a model, it is common to use pseudo-priors to improve mixing in the chains. See here for a very accessible treatment of why pseudo-priors are useful.
In their seminal paper on the topic, Carlin & Chib (p. 475) state that "the form of [the pseudo-prior] is irrelevant," which I take to mean that it should not affect posterior inference based on the model (though it might affect MCMC mixing during model fitting). However, my inuition is that the form of the pseudo-prior DOES matter. I asked about this previously in this question. @Xi'an commented (4th comment): "inference about which model is correct does not depend on the pseudo-priors".
Recently I read comments from Martyn Plummer that contradict my understanding of Carlin & Chib. Martyn says: "In order for the Carlin-Chib method to work, the pseudo-prior must match the posterior when the model is true."
(I am NOT saying that Plummer contradicts Carlin & Chib; only that he contradicts my understanding of Carlin & Chib's claim).
All of this leaves me with five questions:

What is going on here? Provided that the model converges and yields a good effective sample size from the posterior, will my inference about which variables to include in a model depend on my pseudo-prior?
If not, how do we square this with my intuition and Plummer's comment? If so, how do we square this with Carlin & Chib's paper and Xi'an's comment (4th comment)?
If my understanding of Plummer's comment is correct, and the pseudo-priors must correspond to the posterior when the variable is included... does this mean it's impermissible to pseudo-priors corresponding exactly to the true priors? This would mean that pseudo-priors are much more than a convenient technique to improve the mixing in the MCMC!!
What if the indicator variable turns on and off a part of the model with several parameters (for example, a random effect with a grand mean, a variance, and n group effects)? Which of the following are permissible (in order of how confident I am that the approach is permissible)? Is there a better approach that I do not list?
i. Use a pseudo-prior that approximates the full joint
posterior distribution of all of the parameters.
ii. If mixing is acceptably non-atrocious, don't use pseudo-priors at all (i.e. use pseudo-priors equivalent to the true priors).
iii. Use a pseudo-prior based on the univariate posterior distributions for each parameter, but don't worry about how they are jointly distributed.
iv. Following the apparently plain language of Carlin & Chib, use any pseudo-prior that gives computationally efficient mixing in the MCMC chains, as "the form of [the pseudo-prior] is irrelevant".
What does @Xi'an mean in the first comment on my question in saying "the pseudo-priors need correction in an importance sampling type of correction."
Comment: Have you checked this similar [question](https://stats.stackexchange.com/q/292582/7224)? It points out that [Doing Bayesian Data Analysis 2ed](http://amzn.to/2ugvdp2), by Kruschke, is using Carlin and Chib's method [chapter 10]. This would be a soft introduction to the method if the original paper sounds too hard.
Answer:

What is going on here?

This is a very generic question with the obvious answer to study in details Carlin & Chib (1995). The essential idea is to consider the joint parameter $(m,\theta_1,\theta_2)$ where $m$ denotes the model index ($m=1,2$) and $\theta_1,\theta_2$ the parameters of both models, in the sense that the data comes from the density
$$f(x|m,\theta_1,\theta_2)=f_m(x|\theta_m)$$
i.e. one of the two parameters $\theta_{3-m}$ is superfluous once the model index $m$ is set.
Once this completion is done, a prior has to be chosen on the triplet $(m,\theta_1,\theta_2)$, which is
$$\pi(m,\theta_1,\theta_2)=\pi(m)\pi_m(\theta_m)\tilde\pi_m(\theta_{3-m})$$
where I denote by $\pi(m)$ and $\pi_m(\theta_m)$ the true priors on the model index and on the parameter of each model. The additional $\tilde\pi_m(\theta_{3-m})$ is free because the posterior on $\theta_{3-m}$ is equal to the prior:
$$\pi(m,\theta_1,\theta_2|x)=\pi(m|x)\pi_m(\theta_m|x)\tilde\pi_m(\theta_{3-m})$$
The data does not impact the parameter it does not depend of. And thus inference about $\theta_m$ is not impacted by the choice of $\tilde\pi_m(.)$. In practice, this means that the algorithm of simulating from the augmented model produces

a frequency for each model approximating the posterior probability of this model
a sequence of parameters $\theta_m$ when $m$ is the model index, to be used for inference on this parameter
a sequence of parameters $\theta_{3-m}$ when $m$
is the model index, to be ignored.

how do we square this with my intuition and Plummer's comment?

What Martyn Plummer means in his comment is that the pseudo-prior does not matter on the parameter with the other index $m$ but must be the true prior on the parameter with the current index $3-m$. This is 100% coherent with Carlin & Chib (1995) paper.

does this mean it's impermissible to pseudo-priors corresponding exactly to the true priors?

Pseudo-priors can be taken as the true priors, provided these are proper. But as Carlin & Chib (1995) indicate, it is much more efficient to take an approximation of the true posterior, $\pi_{3-m}(\theta_{3-m}|x)$, approximation that can be obtained by a preliminary MCMC run for each model.

What if the indicator variable turns on and off a part of the model with several parameters

The resolution to this conundrum is to consider different sets of parameters for all different models, i.e., to have no common parameters between any two models. If you are in a variable selection problem, this means using a different parameter and a different notation for the coefficient of variable $X_1$ when $X_2$ is part of the regression and when $X_2$ is not part of the regression. From this point, use any pseudo-prior you want on the superfluous parameters.

What does @Xi'an mean in the first comment

I mean that if the probabilities of visits to the two models are not the probabilities in the prior, the posterior probability of one model estimated by the simulated frequency must be corrected.
Comment: I respect your expertise in this issue and I trust this answer is right.  However, I find it difficult to square this answer with Plummer's full comment, where he suggests to "Fit model 1 after adding the entry m=1 to the data (forcing model 1 to be true). Monitor the values of a1[1], b1[1] and c1[1]. Set the pseudo prior for a1[2], b1[2], c1[2] so that it matches the posterior moments of a1[1], b1[1] and c1[1],
Do the same for model 2 but with m=2 in the data. Set the pseudo prior for a2[1], b2[1], c2[1] to match the posterior moments of a2[2], b2[2] and c2[2] in this model."
Comment: This is but one (valid) choice of pseudo-prior.
Comment: Great. So my last snag is to square these answers with the following. If model 1 has pseudopriors that don't strongly overlap the posterior mass and model 2 has good pseudopriors, and the two models have similar posterior probability given the data, it will be easy to jump from 1 to 2, and hard to jump from 2 to 1. I cannot grasp how this doesn't cause the MCMC to spend more time in model 2, leading to invalid posterior inference on m. Plummer's full comment seems like it would solve this issue (false issue?).
Comment: An inefficient MCMC that does not visit often a particular region will compensate by staying very long in that region so that on average it is there the right amount of time.
Comment: Thanks again. Last question: Clearly I don't fully understand Carlin & Chib. Can you pinpoint what I'm missing? Because I thought that the Markov chain for m should take a random walk where the per-step probability of switching to 2 (given m=1) is lower than the per-step probability of switching to 1 (given m=2)? When m=1, the parameters of model 2 are sampled from their (not good) pseudopriors, so it's hard to accept a proposal where m=2.  But when m=2, the parameters of model 1 are sampled from their (good) pseudopriors, so it should be easy to accept a proposal where m=1.


Evaluate definite integral$\int_{\frac{\pi}{6}}^{\frac{\pi}{3}}\frac{\sin t +\cos t}{\sqrt{\sin 2t}}dt$.

Question: How to evaluate this definite integral

$$\int_{\frac{\pi}{6}}^{\frac{\pi}{3}}\frac{\sin t +\cos t}{\sqrt{\sin 2t}}dt$$

I have tried using the property $\int_{a}^{b}f(x)dx=\int_{a}^{b}f(a+b-x)dx$ but not able to solve it.
Answer: Hint
$$\frac{\sin t + \cos t}{\sqrt{\sin 2t}}=\frac{\sin t + \cos t}{\sqrt{2\sin t\cos t}}=-\frac{\left(\cos t-\sin t\right)'}{\sqrt{1-\left(\cos t - \sin t\right)^2}}$$
So you then have:

  $$\int \frac{\sin t + \cos t}{\sqrt{\sin 2t}} \,\mbox{d}t=-\int\frac{\left(\cos t-\sin t\right)'}{\sqrt{1-\left(\cos t - \sin t\right)^2}}\,\mbox{d}t = -\arcsin\left(\cos t - \sin t\right) + C$$


Cluster Analysis for large data in R

Question: I am trying to perform a clustering analysis for a csv file with 50k+ rows, 10 columns. I tried k-mean, hierarchical and model based clustering methods. Only k-mean works because of the large data set. However, k-mean does not show obvious differentiations between clusters. So I am wondering is there any other way to better perform clustering analysis?
The data looks like this
Revenue  Employee  Longitude Latitude  LocalEmployee BooleanQuestions ...
1000     100       xxxx      xxxx      10
...                                                                   ...

Here is part of my code:
mydata <- scale(mydata)
wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
for(i in 2:15)wss[i]<- sum(fit=kmeans(mydata,centers=i,15)$withinss)
plot(1:15,wss,type="b",main="15 clusters",xlab="no. of cluster",ylab="with clsuter sum of squares")

fit <- kmeans(mydata,7)
clusplot(mydata, fit$cluster, color=TRUE, shade=TRUE, labels=2, lines=0)

Comment: Seems perhaps better-suited to Cross Validated
Comment: 'Better' is not uniquely defined in cluster analysis.  It seems you want it to mean 'clusters should be maximally distinct'.  Notice that this will be a complicated function of what the data is actually like, the number of clusters you are looking for, and the distance function / component distribution you decide to use. The last is probably the one to think about when choosing a new tool.
Comment: Agreed it belongs on CV (did a mod for that just now). We regularly do clustering of 200K+ row and 500+ column data sets and it works quite well. Folks on CV shld be able to help you.
Comment: Note also that, at least in an exploratory phase, you can try things out with a subset of your data and project the remaining points in.
Comment: I like the speed and scalability of random forests.  They can be used for clustering.
Comment: R packages such as [fpc](https://cran.r-project.org/web/packages/fpc/index.html) or [mcclust](https://cran.r-project.org/web/packages/mcclust/mcclust.pdf) offer additional procedures and metrics to validate your clusterings.
Answer: Unless you have a good reason to believe that hierarchical (or other) clustering algorithms will work better for your specific application then k-means is probably a good place to start as it has computational advantages (as you have already discovered).
You didn't give a ton of background on what you have done from a data mining process standpoint, so you may have looked into these things already... but the first set of things that I would try are:

Feature selection: use your domain knowledge on the subject at hand to ensure you are including all of the attributes that are likely to be useful for your analysis, and exclude those that will only add noise.
Dimensionality Reduction: you may want to do PCA (or similar) and select only the top handful of dimensions that are less correlated. Potentially this could help you identify the relevant variables, avoid issues associated with the curse of dimensionality, and reduce the computation.
Feature normalization: you are measuring distances. If the attributes don't have a standardized unit of measure then you can get nonsensical results. For example, say you have revenue and employees as two of your input values. If you transformed your revenue data from dollars to euros, would your result change? If it does then you are likely missing a step in your process. The solution to that issue would be normalizing the data (e.g. calculate z-score or min-max normalization) and use that transformed data.
Outliers: k-means can be sensitive to outliers. You should validate that outliers aren't skewing your results. If they are then you may want to either transform the data to impose minimum/maximum values and/or consider excluding certain cases from your analysis.
Different values of K: one drawback of k-means is that you need to predetermine the number of clusters you want. You almost certainly want to experiment with a number of different values for K, and see what works best for your application.

If you still are not getting the results you want, then you may also want to consider:

Experimenting with different distance measures
Experimenting with different initial cluster centroids. You can get different results for the same dataset if you have different starting points.
Experimenting with other algorithms (e.g. hierarchical). Start with a random sample, and if the results are promising then figure out how to scale the full analysis on your system.
Answer: You could try package optpart. You'll find a variation of k-means, pam, as well as two methods of non-hierarchical partitioning, OPTPART and  OPTSIL, available. http://cran.r-project.org/web/packages/optpart/optpart.pdf
Your question is a little vague, so I'm not sure these will help you any better. At the very least, they'll provide you with a handful of additional (often overlooked) clustering methods to try.

Cluster Analysis for large data in R


How do I display a form element only when a checkbox is selected?

Question: I want to create a form with a checkbox and two text fields. The text fields should only be shown when the checkbox is selected.
I am using this code.
<code>$form['display_count'] = [
  '#type' => 'checkbox',
  '#title' => t('Display count'),
  '#description' => t('Display how many times each term is used on a node.'),
  '#default_value' => $config['display_count'],
];

$form['count_prefix'] = [
  '#type' => 'textfield',
  '#title' => t('Count prefix'),
  '#description' => t('Set a prefix to be displayed before count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_prefix'],
  '#states' => [
    'visible' => [
      ':input[name="display_count"]' => [
        ['checked' => TRUE],
      ],
    ],
  ],
];

$form['count_suffix'] = [
  '#type' => 'textfield',
  '#title' => t('Count suffix'),
  '#description' => t('Set a suffix to be displayed after count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_suffix'],
  '#states' => [
    'visible' => [
      ':input[name="display_count"]' => [
        ['checked' => TRUE],
      ],
    ],
  ],
];
</code>
Setting the #states value doesn't seem to work.
How do I display a form element only when a checkbox is selected?
Answer: Use like this:
<code>$form['count_prefix'] = [
  '#type' => 'textfield',
  '#title' => t('Count prefix'),
  '#description' => t('Set a prefix to be displayed before count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_prefix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];
$form['count_suffix'] = [
  '#type' => 'textfield',
  '#title' => t('Count suffix'),
  '#description' => t('Set a suffix to be displayed after count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_suffix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];
</code>


Can't call controller function from jsf:action

Question: I'm trying to call the function save in my controller SeminaireControl.java
package be.helha.aemt.control;

import java.io.Serializable;
import java.util.List;

import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

import be.helha.aemt.ejb.GestionSeminaireEJB;
import be.helha.aemt.entities.Seminaire;

@SessionScoped
@Named
public class SeminaireControl implements Serializable{

    private static final long serialVersionUID = 1L;
    @EJB
    private GestionSeminaireEJB bean;

    public List<Seminaire> getAll()
    {
        return bean.getAll();
    }

    public void save(Seminaire seminaire)
    {
        System.out.println("HELLO");
        bean.save(seminaire);

    }
}

with the  in my seminaires.xhtml
. . .

    <h:dataTable class="seminaire" value = "#{seminaireControl.getAll()}" var = "seminaire">
        <h:column>
            <f:facet name="header">Id</f:facet>
            <h:form>
               #{seminaire.id_student}
             </h:form>
        </h:column>
        <h:column>
            <f:facet name="header">Nom</f:facet>
            #{studentControl.getNameById(seminaire.id_student)}
        </h:column>
        <h:column>
            <f:facet name="header">Séminaire 1</f:facet>
            <h:inputText value="#{seminaire.seminaire1}"/>
        </h:column>
        <h:column>
            <f:facet name="header">Séminaire 2</f:facet>
            <h:inputText value="#{seminaire.seminaire2}"/>
        </h:column>
        <h:column>
            <f:facet name="header">Séminaire 3</f:facet>
            <h:inputText value="#{seminaire.seminaire3}"/>
        </h:column>
        <h:column>
            <f:facet name="header">Séminaire 4</f:facet>
            <h:inputText value="#{seminaire.seminaire4}"/>
        </h:column>
        <h:column>
            <f:facet name="header">Save</f:facet>
            MODIFIER // THIS LINE
        </h:column>
        <h:column>
            <f:facet name="header">Total</f:facet>
            0
        </h:column>
    </h:dataTable>
. . .

and for some reason, my code isn't executed (no changes in my database & no "HELLO" in my console)
Answer: I think you shold replace
MODIFIER

with
<h:commandLink value="MODIFIER" action="#{seminaireControl.save(seminaire)}">

You may also need take h:dataTable into h:form
<h:form>
   <h:dataTable >
   ..............
   ..............
   </h:dataTable>
<h:form>


Slow performance of Latitude/Longitude conversion in query

Question: I have a performance problem with a SQL query running on SQL Server 2019 that returns the lat/long from a geography column.
My query is as follows and it takes around 5 seconds to return 553 rows:
SELECT ActivityLocations.ID, ActivityLocations.ActivityID, ActivityLocations.Number, ActivityLocations.Location.Lat AS 'Latitude', ActivityLocations.Location.Long AS 'Longitude'
FROM Plans
INNER JOIN Activities ON Plans.ID = Activities.PlanID
INNER JOIN ActivityLocations ON Activities.ID = ActivityLocations.ActivityID
WHERE CustomerID = 35041

The query plan it generates is:

But if I change the query a little to return a bit less data, it takes 0 seconds to return 207 rows:
SELECT ActivityLocations.ID, ActivityLocations.ActivityID, ActivityLocations.Number, ActivityLocations.Location.Lat AS 'Latitude', ActivityLocations.Location.Long AS 'Longitude'
FROM Plans
INNER JOIN Activities ON Plans.ID = Activities.PlanID
INNER JOIN ActivityLocations ON Activities.ID = ActivityLocations.ActivityID
WHERE PlanID > 22486

And the query plan is:

I guess my question, is why is the Compute Scalar operation happening before the join on the slow query and after the join on the fast query?  I don't understand why it would do the Lat/Long operation on every row the activity locations table when we only want a small subset of the rows?
Any help would be greatly appreciated.
Edited to contain table information
CREATE TABLE [dbo].[Activities](
[ID] [int] NOT NULL,
[PlanID] [int] NOT NULL,
[Name] [nvarchar](255) NOT NULL,
CONSTRAINT [PK_Activity] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[ActivityLocations](
    [ID] [int] NOT NULL,
    [ActivityID] [int] NOT NULL,
    [Number] [int] NOT NULL,
    [Location] [geography] NOT NULL,
 CONSTRAINT [PK_ActivityLocations] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE TABLE [dbo].[ActivityPlans](
    [ID] [int] NOT NULL,
    [CustomerID] [int] NOT NULL,
    [PurchaseOrder] [nvarchar](255) NULL,
    [Deleted] [bit] NOT NULL,
    [Name] [nvarchar](500) NULL,
 CONSTRAINT [PK_ActivityPlan] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [PlanID_IX] ON [dbo].[Activities]
(
    [PlanID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [ActivityID_IX] ON [dbo].[ActivityLocations]
(
    [ActivityID] ASC
)
INCLUDE([Number],[Location]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [CustomerID_NCIX] ON [dbo].[ActivityPlans]
(
    [CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]

Comment: If you want an accurate answer, you need to [paste the plan](https://www.brentozar.com/pastetheplan/) and provide DDL scripts for the used tables. The order in which the `Compute Scalar` operator is being used is a symptom of the problem, and not the issue. Your second query that you changed `to return a bit less data` is using a different column `PlanID` in the filter predicate, one that is able to seek the index `ActivityID_IX` of the table `ActivityLocations`, which means that same seek cannot be done using the `CustomerID` column of your first query which is the reason for the difference.
Comment: You can also try updating statistics.
Comment: Hi Trenton, thank you very much for your help!  Here is the execution plan: https://www.brentozar.com/pastetheplan/?id=r1pxmjcpY
Before generating this execution plan, I created a copy of the Plans table, named ActivityPlans and used that in this example.
Comment: Hi Alex, thank you for response too.  I updated the statistics for the three tables in this query, but that didn't seem to make any difference.  Thank you for the suggestion though.
Comment: @Stephen looks like you left out the defined indexes on your tables out of the DDL scripts. For example, in your query plan we see the index `ActivityID_IX` on the table `ActivityLocations`, but it is not included in the DDL scripts you provided. If you are unsure of how to do that, you can follow [this](https://www.c-sharpcorner.com/blogs/how-to-get-table-script-with-their-all-indexes-in-sql-server1) link on how to do it.
Comment: Hi Trenton, thank you again. I have updated the original question to include the indexes
Comment: @Stephen don't change the name of any tables between your original question and then the posted DDL scripts and paste the plan. People aren't going to answer your questions on SO if you make changes like that.
Comment: @trenton-ftw, sorry about that.  I wasn't expecting to provide so much detail and the original Plans table had some column names that I didn't feel appropriate to share.  How would you like me to rectify this?
Answer: NOTE: OP changed the name of the table Plans to ActivityPlans between the originally posted queries/graphical executions plans and his subsequently provided execution plan (via paste the plan) and DDL scripts. I am going to speak in terms of the table Plans (as it was originally posted).
I am going to try to explain this in its entirety, including trying to note the things that are not an issue between these two queries because the obvious differences when looking at the two queries is not resulting in the issue (per se). Read on to see my explanation.
Similarities
First, lets talk about where the two execution plans are similar. It is important to note the similarities because (assuming second query plan is acceptable for the OP) the issues is not with the similarities between the two query plans.

Both execution plans start by accessing the tables Plans and Activities.

The table accessed first changes based on your WHERE clause. Which is good. The optimizer makes a good decision and is able to use an index seek in both cases. The filter WHERE CustomerID = 35041 is resolved to an index seek on the index CustomerID_NCIX of the Plans table and the filter WHERE PlanID > 22486 is resolved to an index seek on the index PlanID_IX of the Activities table. Then the join to the subsequent table (Activities in the first query and Plans in the second query) is done. It is supported by an index in both cases, the estimates for the seek operations are not horrific, and both joins are done using Nested Loops that output a number that is relatively close to the final result set. So even though the only visual difference in these two queries is the difference in the WHERE clause, it appears the WHERE clause in each query is being handled fairly similarly and does not appear to be an issue.

The actual order that all 3 tables used in both the first and second query are accessed in the same order in both execution plans.
Both queries access the table ActivityLocations using the index ActivityID_IX.
Both queries have a Compute Scalar operator that retrieves the required values for your expressions ActivityLocations.Location.Lat and ActivityLocations.Location.Long from ActivityLocations.Location of your SELECT statement.

Differences
Now lets talk about the (important) differences, which is where the issues lie.

The first query accesses the table ActivityLocations using an Index Seek operator, while the second query uses an Index Scan operator.
The Index Scan operator that accesses the table ActivityLocations of the first query has an Actual/Estimated Row Count of 329,475/331,523 and the Index Seek operator that accesses the table ActivityLocations of the second query has an Actual/Estimated Row Count of 207/9.
The first query uses a Merge Join to join the results of the first two tables (Plans and Activities) and the second query uses a Nested Loop Join.
The Compute Scalar operator to retrieve the needed values from ActivityLocations.Location of the first query has an Actual/Estimated Row Count of 329,475/331,523 and in the second query it has an Actual/Estimated Row Count of 207/9.
The actual/estimated number of rows in the output of the final join of the first query increases from its input Sort operator (471/3341->553/3402) while the actual/estimated number of rows in the output of the final join of the second query remains consistent from its input Nested Loop operator (207->207).

What is the actual problem?
Put simply, the first query is reading much more data when we look at the execution plan. The rows read from the table ActivityLocations of roughly 300k in the first query is much higher than the 207 rows read in the second query. Additionally, the Compute Scalar operator of the first query is required to compute values for (the same) roughly 300k rows as opposed to the 207 rows of the second query. This obviously leads to a longer running query.
It is also worth noting that the larger row counts coming from the table ActivityLocations is the reason for the Merge Join (seen in the first query plan) in place of the Nested Loop Join operator (seen in the second query plan). According to the optmizer, given your environment, a Merge Join is more suitable to join 300k rows to 3.3k rows than a Nested Loop Join would be. And the use of a Merge Join requires both sides of the join to be sorted by the join columns, thus the reason for the additional Sort operator in the query plan of the first query.
Why is it happening?
Estimates. Estimates drive the optimizer's decision making. In the first query we see that the estimated number of rows to read from the table ActivityLocations (from the Index Scan) is 331,523 and in the second query (from the Index Seek) we see an estimate of 9. It might seem odd to say, but these estimates are closer than you might think. An Index Scan (on up to date statistics) is usually going to have row estimates equivalent to the rows in the table (except for filtered indexes). An Index Seek would ideally estimate a lower number of rows than what is contained in the table. Ideally that number would match the actual number of rows that the Index Seek is required to touch, but the fact that your Index Seek estimate is lower than the entire table is a step in the right direction.
So if the issue is not with the estimates in the Index Scan or Index Seek then where is it? The issue is in the choice to access the table ActivityLocations using an Index Scan in the first query over the choice to use an Index Seek. So why does the first query choose an Index Scan? It is quite clear by looking at the execution plan that an Index Seek would have been a better option. I believe the answer in this case is the cardinality estimation, specifically in this case, the cardinality estimation used for the join to the table ActivityLocations.
We see that the estimated number of rows in the output of the final join of the first query increases from its input Sort operator (3341->3402) while the estimated number of rows in the output of the final join of the second query remains consistent from its input Nested Loop operator (207->207). And not only did the optimzer estimate this, it was right. The actual rows counts returned from these same operators reflect the same pattern.
Why does that matter? What it means is that based on the optimizer's estimate, the join to the table ActivityLocations is going to increase the row count of the input result set. Meaning this join is going to be 1 (input row) to many (output row). Keep in mind, the optimizer needs to return your requested values ActivityLocations.Location.Lat and ActivityLocations.Location.Long from the table ActivityLocations. So when it considers this join, that it believes is going to increase the rows it plans to output from accessing the table ActivityLocations while keeping in mind that it needs to perform a Compute Scalar on columns output from that table, it would make sense to run the Compute Scalar prior to running the join because if the Compute Scalar is run before the join it can guarantee that the Compute Scalar is only running once per row of ActivityLocations, but it cannot guarantee that if the Compute Scalar is run after the join. In this case, the join is actually what ends up limiting the rows from AcitivityLocations and the number of rows returned from that table (for the purposes of this query) is much lower than the row count of the table. In the second query, the estimate says that the output number of rows will be the same, so running the Compute Scalar after the join makes no difference to the number of rows where the compute will be required, so it makes sense to perform the Index Seek in place of the Index Scan.
So to summarize, the rows returned from the first two tables of your first and second query (using your WHERE clause) are different. And it is likely that the rows returned from the first query resulted in a join estimation that estimated a different cardinality than the second query. Thus the differences in how the query plan was built and how it was subsequently run.
Cardinality estimation (with joins specifically) is made up of several factors. If you really want to get in to the internals I would recommend these two articles from the legend Paul White and SQL Shack. The things discussed there should guide you on how you can review the estimation within your system.
How to fix it?
The first goal would be to improve the estimate. If the estimated cardinality for the join was incorrect (which is actually not the case here) then updating the statistics might help. Out of date statistics could lead to a bad cardinality estimate, and thus a bad query plan.
In some cases you might be able to restructure your query to a logical equivalent to result in a better execution plan. This might be by writing it to produce better estimates or even possibly returning different rows in different orders. In this case, I would say the first query looks fine to me, and thus rewriting the query for a logical equivalent would likely not help.
In this case, the cardinality estimate is correct (and you mentioned that you updated statistics and it did not help), the query appears to be written in a good fashion, but the execution plan chosen is still sub-optmial. So I would recommend a query hint. This problem would easily be solved with a query hint to seek the index ActivityID_IX of ActivityLocations. Your join in your first query would look like so:
INNER JOIN ActivityLocations (WITH FORCESEEK,INDEX(ActivityID_IX)) ON Activities.ID = ActivityLocations.ActivityID

There is plenty of information out there on why query hints might be a bad idea, but given the information I have here I would say that is the best option. I am always open to other opinion. Cheers!
Comment: Thank you very much Trenton!  The query hint you suggested resolved the issue.  And thank you for taking the time to explain the issue in depth and helping me understand what was happening and why.  Greatly appreciated!!
Comment: Hints are fragile, especially for this dataset which is unlikely to see update changes.  Go with indexes - they will be stable, storage is cheap, and updates to the affected indexes will be rare, if not "never occurring".
Comment: storage is cheap for small data. indexes are not just storage, again not a problem with small data. issues with using hints (as mentioned in post) are documented out there for all to see.  indexes don't solve the cardinality issue pointed out in my post. if this data is `unlikely to see update changes` as you put it (which OP does not state) then a hint is actually much less 'fragile'. maybe 3 indexes that don't solve the cardinality issue is what OP wants, but I would suggest its not  the best solution and a hint is a much lower cost alternative.
Answer: The issue is with the indexes themselves: your Customer ID can occur anywhere in the Plans table, whereas in the second query, the greater-than on the PlanID means you are limiting the query to only the end of the table because the clustered index (the index which determines the actual ordering of rows in the Plan table) is on PlanID.
As a result, the query planner is making different choices about how to sequence the query execution.
Your best option here is to add three additional indexes:

First on Plan with fields CustomerID, PlanID
Second on Activities with PlanID, ActivityID
Third on ActivityLocations with ActivityID, ID, Number, Lat, Long

This allows the query engine to:

immediately find the rows in Plan for a customer using the first index
take those PlanIDs and use the second index to immediately find the Activities for those Plans (looking up Activities by PlanID)
take those ActivityIDs and use the third index to immediately return the resulting ID, Number, Lat, Long
Comment: This answer is wrong on several counts. The `PlanID` column is not the clustered index on any of the tables involved in the query. Adding three indexes is not required in order to make the first query run just as fast (or with similar number reads) as the second query.
Comment: @trenton-ftw late response, but the Plans table is clustered on PlanID (ID in that table, but it's joined to PlanID, which anchors the join to the clustered ID of Plans).  Indexes are storage-expensive and update-expensive, but read-cheap.  In GIS data sets, lat/lon pairs don't change alot, neither generally do plan/customer relationships, nor activity/plan relationships, so updates that would alter these indexes would be rare.  I appreciate you taking the time to analyze my response, but your statement is dead wrong: PlanID is "involved" by join association to the clustered index on Plans.
Comment: right, `ID` is the clustered index of the Plans table, not `PlanID`. As stated, no table in the posted DDL scripts has a clustered index with a `PlanID` column in it. contrary to your post that states `because the clustered index (the index which determines the actual ordering of rows in the Plan table) is on PlanID`


When are interpolated string evaluated?

Question: I have following code:
    internal class Constants
    {
        internal static string Source { get; set; }

        #region EvaluationRepository
        internal static string QUERY_001 = $@"
select
  e.*
from {Source} e
where
  e.id = @Id
";

        internal static string QUERY_002 = $@"
select
  e.*
from {Source} e
where
  e.statusid=@StatusId
  and e.begindate >= @FromDate
  and e.enddate <= @ToDate
";

        internal static string QUERY_003
        {
            get
            {
                return $@"
select
  d.statusid [StatusId],
  count(1) [Count]
from
  (select e.statusid
  from {Source} e
  where e.begindate >= @FromDate and e.enddate <= @ToDate) d
group by d.statusid
";
            }
        }
        #endregion
    }

The only time {Source} is filled is when I expose the query as a property. (QUERY_003)
It doesn't work when exposed as a field. (QUERY_001, QUERY_002)
Can anyone explain why? Because of the staticness (not sure if that's a word)?
Sorry for the verbatim interpolation noise for the SQL :)
Comment: It is because it's `static` which means it will create the value the first time it initializes the `static` class so changing `Source` after that has no effect.  But the property will initialize a new `string` when you access it thus using the latest value for `Source`.
Comment: Really, string interpolation is a red herring here. You're effectively asking "when are field initializers evaluated?".
Comment: Yes because when I expose the string as a field {Source} is not filled.
Answer: It's done at runtime. It's equivalent (down to the IL generated) to using string.Format.
The reason the fields are not properly filled is because Source is empty when it initially executes (when the static class is initialized).
Comment: YES! That's it. I could trick it with a static constructor and give it a default value to prove it.
Comment: also, I rather see String.Format instead of string.Format *trollface
Comment: @grmbl `string` and `String` are the same thing. `string` is just a language keyword that is an alias for the class `String`.
Comment: I know. I guess it's OCD for me to not use keywords as objects.
Comment: @Rob Your answer is rather ambiguous - all variables are evaluated at runtime. It would be more helpful to say that grmbl's string initializations are evaluated once, when the containing class's static constructor is invoked (they require non-trivial initialization). For more help, see [Static Classes and Static Class Members (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members).

When are interpolated string evaluated?


Is it possible to run Mercurial without ssl installed?

Question: I have a Solaris 5.8 machine without OpenSSL.  This platform is a real pain to get OpenSSL compiled for, and getting Mordac, our unix admin, to install the Solaris package isn't an option.
I'd like to run the Mercurial client, but this seems to require the Python _ssl module, which in turn requires OpenSSL or equivalent.  Is there a way to get Mercurial running without these libraries?
Answer: That's not going to be possible without hacking Mercurial itself. We have a bunch of imports of the _ssl module, so those will certainly break without _ssl. You may put try/except ImportErrors around those imports and that might improve the situation a little bit. You could also try opening an issue in our bug tracker, but it's not really sure any of our crew will be interested in this somewhat outlandish scenario (of not having _ssl).


Geometric Inequality Related To Median, Altitude

Question: For a triangle $ABC$, let $m_{a}$, $h_{a}$ be $A$-median, $A$-altitude.
Define $m_{b}$,$h_{b}$ and $m_{c}$,$h_{c}$ likewise.
Prove that $\dfrac{h_{a}}{m_{b}}+\dfrac{h_{b}}{m_{c}}+\dfrac{h_{c}}{m_{a}}\leq 3$
I have no solution.
Comment: The only reference I can find is: Walther Janous, "Further Inequalities of Erdos-Mordell Type", *Forum Geometricorum* **4** (2004), pp. 203–206 ([PDF](http://forumgeom.fau.edu/FG2004volume4/FG200423.pdf)), citing p. 315 of D. S. Mitrinovic et al., *Recent Advances in Geometric Inequalities*, (Kluwer 1989; there's an expensive Springer reprint), which attributes to Klamkin and Meir the result that $\frac{\overline{h_1}}{m_1} + \frac{\overline{h_2}}{m_2} + \frac{\overline{h_3}}{m_3} \leqslant 3$, where $(\overline{h_1}, \overline{h_2}, \overline{h_3})$ is any permutation of $(h_1, h_2, h_3)$.
Answer: Denote the side of the triangle opposite vertex $ A $ as $ a $.  Now consider the points on side $ a $ where $ m_a,h_a $ intersect side $ a $.  Label the intersection of $ a $ and $ h_a $ as the point $ X $, and label the intersection of $ a $ and $ m_a $ as the point $ Y $.  Then the triangle $ XYA $ is a right triangle.  The ratio $ \dfrac{h_a}{m_a} $ is actually the sine of the angle that $ m_a $ makes with side $ a $.  Since the sine is always less than or equal to 1, we see that $ \dfrac{h_a}{m_a} \leq 1 $.  The same argument shows that $ \dfrac{h_b}{m_b} \leq 1 $ and $ \dfrac{h_c}{m_c} \leq 1 $.  Taking the sum of all three inequalities, you have your result.
Comment: Not $\dfrac{h_{a}}{m_{a}}$    but $\dfrac{h_{a}}{m_{b}}$
Answer: Let $a^2=x$, $b^2=y$ and $c^2=z$.
Thus, by C-S $$\sum_{cyc}\frac{h_a}{m_b}\leq\sqrt{\sum_{cyc}h_a^2\sum_{cyc}\frac{1}{m_b^2}}=\sqrt{\sum_{cyc}\frac{4S^2}{a^2}\sum_{cyc}\frac{4}{2a^2+2c^2-b^2}}=$$
$$=\sqrt{\sum\limits_{cyc}(2a^2b^2-a^4)\sum\limits_{cyc}\frac{1}{a^2}\sum_{cyc}\frac{1}{2a^2+2c^2-b^2}}=$$
$$=\sqrt{\frac{\sum\limits_{cyc}(2xy-x^2)\sum\limits_{cyc}xy\sum\limits_{cyc}(2x+2y-z)(2x+2z-y)}{xyz\prod\limits_{cyc}(2x+2y-z)}}=3\sqrt{\frac{\sum\limits_{cyc}(2xy-x^2)\left(\sum\limits_{cyc}xy\right)^2}{xyz\prod\limits_{cyc}(2x+2y-z)}}$$ and it's enough to prove that
$$xyz\prod\limits_{cyc}(2x+2y-z)\geq\sum\limits_{cyc}(2xy-x^2)\left(\sum\limits_{cyc}xy\right)^2$$ or
$$\sum_{sym}(x^4y^2-x^4yz-x^3y^3+x^3y^2z-x^2y^2z^2)\geq0$$ or
$$(x-y)^2(x-z)^2(y-z)^2\geq0$$ and we are done!
Comment: Congratulations.


IPTABLES not blocking EoIP Tunnel

Question: So I decided to play with EoIP Tunnels today on two VMs which I installed free trial RouterOS on them.
I set rules on iptables on the hypervisor (which is Proxmox) that prevents any input to vms except my pc, but my OUTPUT policy is ACCEPT.
Now I can't ping vms from anywhere except my pc and I can't ping my two vms (RouterOS) from each other, but EoIP Tunnel works fine and I'm routing packets from one RouterOS to another one.
iptables config on both vms:
IN ACCEPT -source a.b.c.d
IN DROP

(a.b.c.d is IP of my pc)
What I am doing wrong?
RouterOSs' config:
VM1:
/ip address
#   ADDRESS            NETWORK         INTERFACE
0   r.o.s.1/32         m.a.i.n         ether1
1   172.22.22.1/30     172.22.22.0     eoiptunnel

/ip route
#      DST-ADDRESS        PREF-SRC        GATEWAY            DISTANCE
0 A S  0.0.0.0/0                          172.22.22.2               1
1 ADC  m.a.i.n/32         r.o.s.1         ether1                    0
2 ADC  172.22.22.0/30     172.22.22.1     eoiptunnel                0

VM2:
/ip address
#   ADDRESS            NETWORK         INTERFACE
0   r.o.s.2/32         m.a.i.n         ether1
1   172.22.22.2/30     172.22.22.0     eoiptunnel

IPs:
r.o.s.1 : Router OS 1
r.o.s.2 : Router OS 2
m.a.i.n : Main Server IP

I monitor traffic on my host server by iptraf and I watched two RouterOSs are seeing each other via another interface, actually I realize that for every VM, proxmox creates 4 interfaces, therefore I assume "some" packets between two VMs which are on the same bridge go through another interface.
I must read the documentation on multiple interfaces created by proxmox upon creating each VM.
Comment: How are you verifying your EOIP connectivity between your RouterOSs, if they cannot ping each other?
Comment: And it would be helpful to send Proxmox iptables rules.
Iptables -L
Comment: @Arash I'm routing for example (22.214.171.124) to go through second RouterOS on VPN, when I block outgoing packets to 184.108.40.206, I can't ping 18.104.22.168, therefore I can verify my vpn is correct.
Answer: Arguably you're doing nothing wrong.
Your iptables rules are blocking traffic into your Proxmox environment, and your two guests are talking to each other across the internal bridge.
The iptables rules won't touch bridge traffic between VMs, and that's by design. (If you routed traffic from one VM to the other via your host, or you tried to ping between a VM and the host, iptables rules would apply.)
Comment: I suppose I should put firewall on RouterOS itself to block packets coming from internal bridge.

IPTABLES not blocking EoIP Tunnel