Monte-Carlo estimation of the mean chord length in a polygon

Question: This is a more "statistical" version of my  Math.SE problem .
 Question   Let $\mathbf{P}$ be a convex polygon of $m$ sides. Pick two of its edges at random, and further pick a random point on each of these edges, and compute the length of the chord we get. If we repeat this process $n$ times,and average the chord lengths we thus obtained, we get an estimate $\hat{\ell}_n$ of the expected chord length $\ell$ of $\mathbf{P}$.  Then,how large should $n$ be to ensure that $\hat{\ell}_n$ differs from $\ell$ by (say) at most 5%,with a confidence level of (say) 95%, and precisely how  should we collect our samples?
Note that determining the expected chord length analytically leads to intractable integrals as shown in my SE post. Also,note that there are multiple inequivalent ways to define the expected chord length of $\mathbf{P}$; the one we need here is $\ell = \lim_{n\rightarrow \infty} \hat{\ell}_n$.
Comment: The integrals do not appear to be "intractable"; indeed, they appear to be solvable with elementary functions.  The [mean distance from a point to a line segment](http://gis.stackexchange.com/questions/7440/transform-polygon-to-equivalent-circle-qgis) involves linear expressions times quadratic expressions and quadratic expressions times logarithms of linear plus quadratic expressions.  Integrating the latter by parts gives rational functions of quadratic algebraic expressions.  Those all can be done by completing the square and trig substitutions.
Comment: I've tried to edit your post to (a) make the math slightly more readable and (b) change what I believe were some typos in the math. Please make sure I have not messed things up in the process.
Comment: Also, what do you mean by "ensure"? Strictly speaking, Monte Carlo can't (quite) provide such guarantees.
Comment: @cardinal: Thanks for your editing. I think I have fixed the guarantees part.
Comment: E.g., 48 times the mean distance between two non-parallel, non-adjacent sides of a regular hexagon of side 2 equals $32-48 \sqrt{3}-22 \sqrt{7}+46 \sqrt{13}+27 \text{ArcCsch}(3 \sqrt{3})-108 \text{ArcSinh}(\frac{1}{3 \sqrt{3}})+81 \text{ArcSinh}(\frac{5}{3 \sqrt{3}})$ +  $66 \text{ArcSinh}(\sqrt{3})-27 \text{Log}(3)-18 \text{Log}(27)+36 \text{Log}(432)+36 \text{Log}(7-4 \sqrt{3})+6 \text{Log}(-135+78 \sqrt{3})$ +  $48 \text{Log}(2+\sqrt{7})-72 \text{Log}(-\frac{2}{3} (2+\sqrt{7}) (-7+\sqrt{13}))-24 \text{Log}(-1+\sqrt{13})+24 \text{Log}(1+\sqrt{13})$ (yielding a mean of about 2.8331).
Answer: This is really a question about numerical integration because it reduces immediately to the problem of finding the mean distance between two line segments in the plane.
Monte-Carlo integration would be wasteful and inefficient compared to other methods that are readily available, including

Direct analytic integration.  This is messy but can be done.
Numeric quadrature.  Adaptive methods will be accurate.
Analytic integration of the mean distance between a point and a line segment and numeric quadrature of that mean distance.
Discrete approximations, such as Riemann sums, the Trapezoidal Rule, etc.

Because the mean distance function in (3) is differentiable and varies relatively slowly, simple numerical methods such as Simpson's Rule work well.  It's best to do the numeric integration over the shorter of the two line segments.  In experiments I find that using the endpoints and midpoint in Simpson's Rule typically gives better than 1% accuracy and using five equally spaced points is far better than that.  (The toughest cases occur where two sides are equally long, parallel, and close together.)  If you need to, you can do the analysis to estimate the Simpson's Rule error and adaptively decrease the point spacing.
For the original problem, the approximations sometimes overestimate and sometimes underestimate the mean distance, so we could expect some cancellation of errors.
At any rate, you will definitely achieve 5% accuracy using method (3).  For an $n$ sided polygon it requires $n$ computations (each of constant cost) per vertex and $n-1$ computations per midpoint for a cost of $O(n^2)$.  The individual computations of mean point-segment distances require some basic arithmetic, four square roots, and two logarithms, so they're quick and easy.  (Mathematica computes about 7,500 mean segment-segment distances per core per second.)
If you want to avoid all but the simplest arithmetic, you can approximate each segment-segment integral with a double Simpson's Rule pass, one for each segment (method 4).  With three division points (requiring the computation of nine distances) you will achieve 5% accuracy.  With five division points (25 distances) you will be better than 1% accurate (usually better than 0.05%) except for extremely close parallel segments.  In Mathematica, with its interpreted overhead, this technique actually is only half as fast as method (3).

This plot shows (negative) log (base 10) relative errors for 1000 segments randomly distributed near the endpoint of a unit segment (which is the larger of the two).  E.g., a value of 2 is a 1% error; a value of 6 is a 0.0001% error.  This is a severe test, because the worst performances occur when the segments are crossing or close to doing so, situations that are impossible or unlikely in convex polygons.  (Note that the smallest possible mean distance is 1/4 (for an infinitesimally short segment near the middle of the unit segment).)
Where the approximation is high, the error is plotted on the right, and where the approximation is low, the error is plotted on the left.  Blue dots are the three-point by three-point Simpson's Rule calculation (method 4) and red dots are the three-point Simpson's Rule calculation (method 3).
Typically method 3 (red) has much better than 2% accuracy and is better than method 4 (blue), which in a few cases has almost 10% error.  Method 3 has a tendency to overestimate slightly (more of its values are at the right).  Both methods almost always obtain better than 0.1% accuracy (a height of 3 or better on the plot), especially at mean distances greater than the longer side.  This implies that if you want to improve the accuracy, focus first on nearby edges of a convex polygon.

In this plot of the 1000 segments, the brighter, thicker, redder ones have the greatest relative error for Method 3.  The black segment is the reference (unit) segment.


Why does /register redirect to home page if you are logged in on jhipster app?

Question: I have a simple jhipster app.  I'd like to allow authenticated users to register accounts for new users.  I tried to do this by linked to /register.  The way it is configured, it will always redirect to the home page if you are already logged in (preventing you from accessing the register page).  I can't figure out where this behaviour is configured.  It works fine if you are not logged in.
My register.js is shown below
<code>angular.module('myApp')
.config(function ($stateProvider) {
    $stateProvider
        .state('register', {
            parent: 'account',
            url: '/register',
            data: {
                authorities: [],
                pageTitle: 'register.title'
            },
            views: {
                'content@': {
                    templateUrl: 'scripts/app/account/register/register.html',
                    controller: 'RegisterController'
                }
            },
            resolve: {
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('register');
                    return $translate.refresh();
                }]
            }
        });
});
</code>
Answer: This behavior is coded in the authorize function of auth.service.js:
<code>// an authenticated user can't access to login and register pages
if (isAuthenticated && ... $rootScope.toState.name === 'register')) {
   $state.go('home');
}
</code>
Comment: I'll add that as of jhipster 2.25.0 there is now create/delete user functionality on the user management page so accessing the registration page while you're logged in isn't as important as it used to be.


Difficulty to list taxonomy terms in a block for specific content type (d7)

Question: I have made a page using views to list a specific content type.
Then I wanted to make a block to list a taxonomy vocabulary in a sidebar in order to sort the posts according to terms.
The problems I am facing are:

If I select the block to appear for specific content types, the block doesn't show
I am having a multilingual website and the block shows terms in both languages, how do I choose to show the terms in the current users language?
I have also tried the module taxonomy menu but it also lists terms in both languages and doesn't show for specific content types

Any help would be highly appreciated.
Comment: As far as I remember, views already has a filter, current language. Did you apply that filter?
Answer: To get the block to appear on certain content types you will need to get the common URL for the content types you are looking to put it on.  You may have to use a module like pathauto to set better URLs for your content.  For example if you are on an article content and the URL is www.example.com/article/3 you would go to the block configuration and at the bottom choose to show blocks only on certain pages.  Then in the text box type the urls of the content types you want them to show on.  Again as Article content type as an example you would enter: article/* or just simply article* like so:


Values of $x$ where series converges, showing continuity

Question: Been revising in advance for complex analysis, and struggling with questions relating to power series. I've got the following series,
$$g(x) = \sum_{n=0}^{\infty} \frac{x^{2n}}{(1+x^{2n})}$$
and I'm asked to find values of $x$ where $g(x)$ converges, and to show it's continuous there. I tried doing a ratio test to get an interval of convergence, and somehow got $\frac{1}{\sqrt{x}}$ which probably isn't right, since I'm fairly certain this converges for values $x \in [0,1]$ although I'm unsure as to how to explain the reasoning there. I also know I should use the Weierstrass M-Test.... but I'm not sure how to "cook up" an appropriate convergent series.
Given that though, continuity should follow from term-by-term continuity on the defined interval, right?
Thanks
Comment: Try the root test.  It might tell you something.
Comment: This is not a power series, so radius of convergence and the like is not really correct terminology.
Comment: Thought had crossed my mind but thanks, edited.. Somehow we never covered the root test @ncmathsadist in either of the analysis courses I've taken, and embarrassingly I still don't know how to calculate a limit superior...
Answer: Note that if $|x|\ge1$, then $g(x)\ge \sum_{n=0}^\infty\frac{x^{2n}}{2x^{2n}}=\sum_{n=0}^\infty \frac{1}{2}$ diverges to infinity.
You can show that $g$ converges pointwise in $(-1,1)$ by showing that $g$ converges uniformly on every compact subinterval $[-\beta,\beta]\subset(-1,1)$. For the denominator satisfies $1+x^{2n}\ge 1$ and on $[-\beta,\beta]$ the numerator satisfies $x^{2n}\le \beta^{2n}$. Thus
$$
\frac{x^{2n}}{1+x^{2n}}\le\beta^{2n}.
$$
As $\beta<1$, can you apply the $M$-test to finish? Moreover as the partial sums are continuous on $[-\beta,\beta]$, can you conclude that $g$ is continuous on $[-\beta,\beta]$ and hence continuous on all of $(-1,1)$?
Comment: Oh cool that all makes sense, except for why is $x^{2n} \leq \beta^{2n}$?
Comment: @AdrianHindes Since $|x| \le \beta$ for every $x\in [-\beta,\beta]$, if we square both sides of this inequality, we get the answer to your question.
Comment: Oh right sorry, I thought for a moment we were taking $x$ in a larger interval. Okay great that makes perfect sense then, thanks so much!


A-Frame & ar.js: Multiple markers & boxes

Question: Is there any proof of concept of how to implement multiple AR markers w/ A-Frame?
Ex. Something like this: https://www.youtube.com/watch?v=Y8WEGGbLWlA

The first video in this post from Alexandra Etienne is the effect I'm aiming for (multiple distinct AR "markers" with distinct content): https://medium.com/arjs/area-learning-with-multi-markers-in-ar-js-1ff03a2f9fbe
I'm a bit unclear if when using multiple markers they need to be close to each-other/exist in the same camera view
This example from the ar.js repo uses multiple markers but they're all of different types (ie one is a Hiro marker, one is a Kanji marker, etc): https://github.com/jeromeetienne/AR.js/blob/master/aframe/examples/multiple-independent-markers.html
Comment: The multiple independent marker example that you linked to works fine.... so you want the Aframe scene to render on each of multiple copies of the same marker image?
Comment: Should have been more clear-- I'd like to use the same marker type (ie qr code of some kind) but each has different content within them (ie a qr marker with data 123456789 and a qr marker with data 987654321)
Comment: With that example, the number of unique tags appears to be limited by how many different tag types exist
Comment: QR code example (scan and then use Hiro): https://medium.com/arjs/ar-code-a-fast-path-to-augmented-reality-60e51be3cbdf
Comment: this would work, too: you could create QRcodes with links like example.com/ar.html?id=123 which create different models on the same AR marker like Hiro. The obvious limitation is that users need to rescan the QRcode on every marker.
Comment: there is this multiple-independent-markers.html for A-Frame, is there an example for Three.js?
Answer: tldr: working glitch here. Learn the area (the image is in the assets), click the accept button, and toggle the marker helpers.
Now, a bit of details:
1) Loading saved area data
Upon initialisation, when ar.js detects, that you want to use the area marker preset, it tries to grab a localStorage reference:
localStorage.get("ARjsMultiMarkerFile")

The most important data there is an array of pairs {markerPreset, url.patt} which will be used to create the area.
Note: By default it's just the hiro marker.
2) Creating an area data file
When you have debugUIEnabled set to true:

There shows up a button "Learn-new-marker-area".
At first glance it redirects you to a screen where you can save the area file.
There is one but: by default the loaded learner site is on another domain.
Strictly speaking: ARjs.Context.baseURL = 'https://jeromeetienne.github.io/AR.js/three.js/
Any data saved there won't be loaded on our website, for local storage is isolated per origin.
To save and use the marker area, you have to create your own learner.html. It can be identical to the original, just keep in mind you have to keep it on the same domain.
To make the debugUI button redirect the user to your learner html file, you need to set
ARjs.AnchorDebugUI.MarkersAreaLearnerURL = "myLearnerUrl.html"

before the s are initialized. Just do it in the .

Once on the learner site, make sure the camera sees all the markers, and approve the learning.
It should look like this:

Once approved, you will be redirected back to your website, the area file will be loaded, and the data will be used.
Comment: my simple glitch [here](https://glitch.com/edit/#!/aframe-ar-area?path=index.html:18:0)
Comment: Marker learner is working again. Check out:
https://github.com/jeromeetienne/AR.js/issues/283#issuecomment-507312601
Comment: @droid001 Thanks for the info, i'll retry my steps and post the results !
Comment: @droid001 I've updated my anwser though the solution seems to be more suitable for a medium tutorial than SO answer :P
Comment: Could you update the first link (`tldr: working glitch here.`) which only leads to a .png?
Comment: @droid001 snap, it got mixed up when i was removing the old anwser. I've updated the link !
Answer: As @mnutsch stated, AR.js does what you want.
You can display two different models on two different markers. If the camera doesn't see one of the markers the model vanishes (or stays where it was last, depending on your implementation.
The camera doesn't need to see both.
Screenshot:
https://www.dropbox.com/s/i21xt76ijrsv1jh/Screenshot%202018-08-20%2011.25.22.png?dl=0
Project:
https://curious-electric.com/w/experiments/aframe/ar-generic/
Also, unlike Vuforia, there is no 'extended tracking' - once the code is out of sight, you can't track anymore.
Comment: He wants to use multiple markers as one. You should be able to create the "area" with "area-learning". Its supposed to be more stable than a single marker.


Interpretation of sum of squares divided by sim

Question: For the collection of numbers $S=\{x_1,x_2,...,x_n\}$ consider the term,
$T_S =({\sum_{i=1}^n x_i^2})/({\sum_{i=1}^n x_i})$
where $\forall i, x_i \in [0,1]$ . Is there any specific name for this term?
If not what is the interpretation of this term?
Example:
$T_{\{x_1,0,0,...,0\}} = x_1$
$T_{\{0.9,0.01\}} = 0.89$
$T_{\{0.9,0.3\}} = 0.75$
Comment: (1) What is "sim" in the title?  (2) See https://en.wikipedia.org/wiki/Index_of_dispersion for a statistic that is, up to an additive function of $n$, equal to $T_S.$
Answer: The statistic you have defined could be regarded as the ratio of the first two raw sample moments.  The first two raw sample moments are the sample mean and sample mean-of-squares, given respectively by:
$$\bar{x} = \frac{1}{n} \sum_{i=1}^n x_i \text{ } \text{ } \text{ } \text{ } \text{ } \text{ } \tilde{x}^2 = \frac{1}{n} \sum_{i=1}^n x_i^2.$$
Your statistic is equivalent to $T_S = \tilde{x}^2 / \bar{x}$, which is the ratio of these quantities.  I have not seen this statistic in use before, and it is a strange statistic to use, since it does not have any obviously useful properties.  There is no interpretation I am aware of other than saying that this is the ratio of the first two raw sample moments.


Does PHP Support Arrow Function Syntax?

Question: After complaining about the tumultuous task of writing the keyword function over and over, I asked someone about an easier way. The person said that PHP is going to have arrow function syntax similar to es6.

const foo = (x, y) => {
    return x + y;
};

As I continued to look into this, I have not been able to find many examples online.
Can someone of the right caliber please expound upon this?
At this point, I am also really interested in how this would fit into the OOP aspect of PHP.
Comment: I think you have been downvoted because your question is a bit open and it has two separated questions. You should only make one question and they need to be a bit more specific, for example, "Does exist this functionality in PHP?". The second question is also too broad for StackOverflow, maybe is better for https://softwareengineering.stackexchange.com/
Answer: Original answer from February 2018:
This appears to be the syntax described in https://wiki.php.net/rfc/arrow_functions. It does have an experimental implementation.
In the arrow functions proposal, it is mentioned that it's an alternative to the "short closures" proposal, https://wiki.php.net/rfc/short_closures
As of February 2018, the current versions of PHP are 7.1.4 / 7.2.2.
I can't find any confirmation that either proposal has been approved. The former is in the "Under Discussion" state, the latter is "Declined / Withdrawn in favor of http://wiki.php.net/rfc/arrow_functions". I think it's too soon to know whether it will be adopted in any future version of PHP.

Update December 2019:
The feature has been released in PHP 7.4, according to https://www.php.net/manual/en/migration74.new-features.php

Arrow functions provide a shorthand syntax for defining functions with
  implicit by-value scope binding.
<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);

But the usage has not been updated yet in the PHP manual page about Anonymous Functions
Here's a blog going into detail: https://stitcher.io/blog/short-closures-in-php
Comment: also, see https://wiki.php.net/rfc/arrow_function_preference - it seems there's an RFC coming for 7.2 about it... maybe we'll *finally* see it one day.
Comment: @BillKarwin the RFC mentioned above was accepted and will be implemented in the PHP 7.4
Comment: It's here in 2019.
Comment: There is a new RFC which aims for PHP 7.4. You can find it here: https://wiki.php.net/rfc/arrow_functions_v2.
Comment: So after discussing the feature for four years, they have a third RFC. Maybe by 2030 they will have it implemented in a released product.
Answer: Yes. The new RFC has been accepted for PHP 7.4 https://wiki.php.net/rfc/arrow_functions_v2
Answer: Based on RFC for PHP 7.4 code could look like
$users->map(
    fn($user) => $user->first_name.' '.$user->last_name
);

instead of
$users->map(function($user) {
    return $user->first_name.' '.$user->last_name;
});

Comment: Congrats Dude, your code is on laravel-news https://laravel-news.com/short-arrow-functions

Does PHP Support Arrow Function Syntax?


Itens de array relativas ao adicionar novo item

Question: Possuo uma array que possui 10 itens, por exemplo:
var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

E, no meu html, possuo vários botões, com id's, por exemplo:
<button id="item_12">12</button>
<button id="item_27">27</button>
<button id="item_54">54</button>

Porém, gostaria que, ao clicar em algum botão, adicionasse o id na array no primeiro item, e os outros passarem para o item seguinte, como por exemplo (se eu clicasse no botão com id = item_54):
var array_exemplo = ["item_54", "item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9"];

Como posso fazer isso?
Answer: Use o método unshift que insere um novo valor no início da lista da array:
    var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

    var button = document.getElementById("item_54");

    button.onclick = function(){

        array_exemplo.unshift(this.id);

    }

Caso queira fazer isso no HTML:
HTML
<input type="button" id="item_54" onclick="addId(this.id)">

JS
    var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

    function addId(Id){

        array_exemplo.unshift(Id);

    }

Comment: Perfeito! Nem imaginava da existência do `unshift`! Muito obrigado!


Segmentation fault on malloc for double pointer

Question: I'm making a program that reads in text from a file, delimits it into alphanumerical words, and so on. I'm running into an issue where, I've read from the file into a string, and I'm trying to delimit that string into a 2d array where each word is stored in an array. From there I will go on to order them.
However, I am getting a segfault when I malloc for words[n]. For a test file that I'm using, it has ~400 characters. No word is longer than say 10 characters, so (j - i + 1) wouldn't be a huge allocation that might cause a stack overflow (unless I'm misunderstanding my allocation).
I can explain my code for the function if need be, it's a manipulation of a strsplit() function that I wrote.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    if (argc != 2) {
        printf("Please provide 1 argument.\n");
        return 0;
    }

    FILE *file = fopen(argv[1], "r");
    fseek(file, 0, SEEK_END);
    size_t length = ftell(file); // Getting file size

    char buff, **words, buffer[length + 1];
    int i = 0, j = 0, n = 0, h = 0;

    buffer[length] = '\0';
    rewind(file);
    fread(buffer, 1, length, file); // Read file into buffer, close file
    fclose(file);

    // Deliminate to 2-D array of words
    while (buffer[i] != '\0') {
        while (isalnum(buffer[j]))
            j++;
        i = j;
        while (isalnum(buffer[j]))
            j++;

        words[n] = (char *)malloc(sizeof(char) * (j - i + 1));
        while (i < j)
            words[n][h++] = buffer[i++];

        n += 1, h = 0;
    }
}

It's worth noting that the file input works, and the algorithm to delimit works (it correctly captures the first word from the file from i to j). Do I need to malloc for **words? I don't think that's the issue, but I wouldn't know how many words are in a sample file so I would have to malloc some large amount.
Answer: You never actually set the value of words to anything. words needs some memory before you can populate words[n].
You could do char** words = malloc(MAX_NUM_OF_WORDS * sizeof(char*)) or have a stack based collection: char* words[MAX_NUM_OF_WORDS]
Free tip for the day: using file without a NULL check is not good practice.
Comment: Damn, that's what I thought it might be. I didn't want to set some arbitrary MAX_NUM_OF_WORDS but I supposed there's no way around it.

And I agree, this program is only in early stages (there's still a lot more to do) and I'm in testing phase, using only a specific file to get my functions working. I'll add in the NULL check. Thanks!
Comment: @DanBan you can resize it as you go with realloc
Comment: @jenesaisquoi So every time it runs through the loop I realloc and add space for a word before I add it? That wouldn't affect the current contents of it would it?
Comment: @DanBan you could do that, but I would limit the system calls by reallocation larger chunks at a time. The contents won't be affected
Comment: Either go with a different structure (perhaps a linked list? depends what you want to do with the words at the end). If it really needs to be an array then as @jenesaisquoi says: allocate in "chunks" (pretty much implementing a C++ vector ;-)


Allow users to submit content that is approved before it is published

Question: I want to allow users to submit the content to my site, but the content must be first approved, and then it can be published.
Is there a module that do this? Which code should I write for such module, if one doesn't exist?
Answer: You might want to try: http://drupal.org/project/workflow & http://drupal.org/project/formfilter
If you create a workflow you can set it to only allow users to create content in the 1st state, something like "needs review". Then, an admin can come in and progress to the 2nd sate, say to "published".
I used an action and trigger to automatically publish any content placed into the 2nd state.
You can use the form filter to disable the ability to set the content straight as published in the normal node edit form.
Ideally you will want some type of approval queue too, you can use the default Workflow summary but I think this requires views.
Comment: http://drupal.org/project/override_node_options may be helpful as well.
Comment: Ooo, looks good a lot less complicated than form filter. thanks
Comment: i used the drupal's default function, enabling the permission to the anonymous user to creat story. and then unchecked the publish option in story content type. then the anonymous user can publish articles and the articles will be reviewed can publish. what's the difference with the workflow module?
Comment: Sometimes you might want tighter control over administer nodes, for example we have quite a strict workflow process with many roles involved, each role can only change to and from certain states.

Content is created by agents and put into draft / awaiting media. If it is in awaiting media an email is sent to the Media Developers linking to the workflow - here comments describe the requirement. Then the devs can change the state to review. This is then reviewed by stakeholders who also add comments in the workflow before an editor (who is the only role who can publish) signs it off.
Answer: Another way to do this is the Revisioning module.  If you set the content type to not be published by default, you can use this module to control publication as well as any revisions.  It provides a view for administrators showing all revisions that are awaiting publication.
Comment: How does this compare to @WestieUK's answer?
Answer: "Workflow" or "Revisioning", depends up on your requirements.
Workflow module provides state based content control, i.e., you can make your content flow across  various states (Draft, Pending, Review etc.,) and various users, before you publish it.
Revisioning module creates a new revision for every edit made on a node, and finally you can publish it.
I suggest you to use the combination of both these modules, for a cleaner impact. This slideshare presentation would be helpful for you, read this before you proceed http://www.slideshare.net/mewren/workflow-revisioning-and-rules-in-drupal
But remember, this is a back and forth task. Choose carefully between workflow_node and workflow_field. Also, you may need to work around this issue http://www.ionsden.com/article/problems-workflow-and-revisioning-drupal


Few images on the same line

Question: I need to images will be on the same line. How to style it?

This of course give me images on the same line but with some spaces. Of course only when i write  on the same line it works. Display inlnine doesn't helps to me. Any clues?
Comment: Try float:left. Though you'll need to clearfix the containing div.
Comment: http://www.webtoolkit.info/css-clearfix.html do you mean that? :)

I try also a few diffrent ways and it doesn't works
Comment: Overflow is not neccesery it works anyway :) Thanks
Answer: It's recommended start with some css reset, like this:
CSS Reset
Then use:
img {
    float:left;
    border: 0;
    margin: 0;
}

Comment: The easiest way. I forget about that. Thanx :)

Few images on the same line


How to implement a retry mechanism for goroutines?

Question: new to working with goroutines; currently have a really simple implementation of:
func someFunc() error {
  resp, err := httpClient.Post()
  if err != nil {
    log...
    return error
  }

  return nil
}

func flowA() {
  ...

  go someFunc()
}

What I'd like to achieve is to implement retrying on unsuccessful response from the Post request inside of the func being managed by the goroutine. Not sure if it's better to handle the retry logic by wrapping the someFunc() err value, or if there's a more idiomatic way to handle errors returned within a goroutine.
Comment: you could look at this implementation https://github.com/hashicorp/go-retryablehttp
Answer: One way to have a retry mechanism is this, here I am retrying for a max of n=5 times, based on the status code we can also have a check to retry only if response status code is 4XX
 func someFunc(maxRetry int) error {
      maxRetry = maxRetry - 1
      resp, err := httpClient.Post()
      if resp.StatusCode != http.StatusOK {
          if maxRetry > 0 {
            return someFunc(maxRetry)
          }
      }

      if err != nil {
        log...
        return error
      }

      return nil
    }

    func flowA() {
      ...

      go someFunc(5)
    }


When are odds ratios worse/better than risk ratios as measures of the effect size of associations between categorical variables?

Question: Wikipedia gives some information on this. However, I seek more detailed information on when odds ratios/risk ratios are better, and why one is better than the other in certain circumstances.
Answer: It depends on what you mean by "better", but for most reasons I can think of, the "Risk Ratio" is the superior measure in terms of better reflecting what most people are looking for, having a slightly easier interpretation, etc.
But there are some study types that prevent the calculation of a risk ratio (case-control studies) and logistic regression, which is used to calculate odds ratios, is somewhat easier to do - less likely to end up with weird values or convergence problems. But for most of those cases, people are using the odds ratio as a reasonable approximation of the risk ratio they'd actually like in an ideal world.
To expand on gung's question a little bit, to explain this reasoning: In an ideal world, an observational epidemiologist would run nothing but cohort studies. As a field, the "desirable" estimate is a risk - there's a back and forth about whether or not the comparison between groups should be a relative risk or a risk difference, but the core is risk, not odds, and right now the de facto effect estimate is relative risk.
But cohorts are super-expensive, especially for rare diseases, so case-control studies exist to make the study of those diseases feasible. You can't estimate a relative risk for those however, but it's a decent approximation for rare diseases, so we accept odds ratios as "close enough".
Comment: +1, but I'd love to hear more detail about this. To me it seems like odds ratios would always be better, but I also don't deal w/ that sort of thing in the matter that / as much as epidemiologists do.
Comment: @gung Some expansion of my answer - I don't know the exact history of the evolution of the field, but the big debate is over risk ratios or risk differences, but it's always been trying to look at differences between rates. Odds are...an acceptable compromise in some circumstances. That may not generalize to other fields, but I've never heard it advanced that odds may be directly preferable beyond logistic regression having less convergence issues than binomial regression. I'd be interested in your thoughts.
Answer: There are many advantages of measures that have unrestricted ranges and that can be interpreted out of context.  A risk ratio of 2 cannot apply to a risk exceeding $\frac{1}{2}$ whereas an odds ratio has an unrestricted range and can apply to any base risk.  Also, odds are tied to fair bets in gambling.  Odds ratios tend to be more constant over strata than risk ratios (and certainly more constant than risk differences).
Comment: How could a non-collapsible measure such as the odds ratio be "certainly more constant over strata" than a risk difference, a strictly collapsible measure?
Comment: Being collapsible is what makes a measure unstable/non-transportable.  Absolute risk differences **must** change as the base risk changes.  Same for risk ratios.  An odds ratio on the other hand can apply to any base risk.  Many a study has claimed an interaction because the study used a scale for which the effect measure was incapable of being constant.


Probability of Full House in 5 Cards Given a Pair of Aces

Question: What is the probability of a full house in a 5 card hand, given the first 2 cards are aces?
My thought process is that there are 4 other events that could occur:
A: Ace
p: any card of given face
App —> (2/50) * (4/49) * (3/48)
pAp —> (4/50) * (2/49) * (3/48)
ppA —> (4/50) * (3/49) * (2/48)
ppp —> (4/50) * (3/49) * (2/48)
Am I approaching this incorrectly? I believe these are all the possible combinations for which this could occur.
Comment: This is correct.  Do note however the distinction between the problem "Probability of a full house in 5 cards given at least two aces *in any position* in the hand" versus "Probability of a full house in 5 cards given two aces *very specifically in the first two positions* among possibly additional"
Comment: @JMoravitz Isn't this a conditional probability problem?  Also, the rank of the non-ace cards has not been selected.
Comment: @N.F.Taussig in the same way that "Find the probability that the second ball drawn is red given the first ball is red given a bag with 10 balls, 4 of which red" can be done immediately as $\frac{3}{9}$ rather than $\dfrac{\frac{4\cdot 3}{10\cdot 9}}{\frac{4}{10}}$, the above problem can be jumped straight to imagining a 50 card deck and drawing three cards.  That is to say, rather than using $\Pr(A\mid B) = \frac{\Pr(A\cap B)}{\Pr(B)}$ you can use the intuitive interpretation of $\Pr(A\mid B)$ as the probability of $A$ when restricted to the smaller sample space where $B$ occurred.
Comment: @JMoravitz I see what you are saying about the conditional probability aspect of the problem, but there are $48$ choices for the first non-ace.
Comment: Good catch.  Yes then, multiply the result above by $12$ representing the selection of what rank `p` represents.  It may be that the OP was still aware of this step and just neglected to mention it, putting the final probability as $12\cdot 4\cdot 4\cdot 3\cdot 2 / (50\cdot 49\cdot 48)$
Answer: Method 1:  If the first two cards selected from the deck are aces, then of the remaining $50$ cards, two are aces.  There are $$\binom{50}{3}$$ ways to select three cards from the $50$ that remain.  To obtain a full house, either one of the two remaining aces and two cards from one of the remaining $12$ ranks must be selected or three cards from one of the remaining $12$ ranks must be selected.  Thus, the number of favorable cases is
$$\binom{2}{1}\binom{12}{1}\binom{4}{2} + \binom{12}{1}\binom{4}{3}$$
where the first term counts the number of ways of selecting one of the two remaining aces, one of the remaining $12$ ranks, and two cards of that rank and the second term counts the number of ways of selecting one of the remaining $12$ ranks and three of the four cards of that rank.  Hence, the probability of obtaining a full house given the first two cards selected are aces is
$$\frac{\dbinom{2}{1}\dbinom{12}{1}\dbinom{4}{2} + \dbinom{12}{1}\dbinom{4}{3}}{\dbinom{50}{3}}$$
Method 2:  We correct your attempt.
You did not take into account the rank of the non-aces.  Observe that there are $48$ cards which can be selected as the first non-ace.  Choosing that card determines the rank of the cards which are non-aces.  Hence, there are three choices for the second non-ace and, if there is a third non-ace, there are two choices for that card.  The probability of selecting an ace, then two cards of one of the other $12$ ranks in that order is
$$\frac{2}{50} \cdot \frac{48}{49} \cdot \frac{3}{48}$$
Since there are three possible positions for the remaining ace, the probability of obtaining a full house with three aces given that the first two cards are aces is
$$\frac{2}{50} \cdot \frac{48}{49} \cdot \frac{3}{48} + \frac{48}{50} \cdot \frac{2}{49} \cdot \frac{3}{48} + \frac{48}{50} \cdot \frac{2}{49} \cdot \frac{3}{48} = 3 \cdot \frac{2}{50} \cdot \frac{48}{49} \cdot \frac{3}{48}$$
The probability of obtaining a full house containing three cards of another rank given that the first two cards are aces is
$$\frac{48}{50} \cdot \frac{3}{49} \cdot \frac{2}{48}$$
Hence, the probability of a full house given that the first two cards selected are aces is
$$3 \cdot \frac{2}{50} \cdot \frac{48}{49} \cdot \frac{3}{48} + \frac{48}{50} \cdot \frac{3}{49} \cdot \frac{2}{48}$$
Comment: I see my issue! I was limiting the first non-Ace to a very specific card as opposed to allowing that card to be any non-Ace!  Thank you @N.F. Taussig and others that replied!


Why not just run a Markov chain to get stationary probabilities?

Question: I'm reading Performance Modeling and Design of Computer Systems which contains some analysis of Markov chains. In particular, it emphasises various analytical methods for finding the stationary distribution of a Markov chain.
Here's what confuses me: when I have formally studied computer-intensive statistics (more specifically, Monte Carlo integration) in the past, a core theme has been about constructing Markov chains that have stationary distributions that approximate the distribution you want to draw from, and then running those Markov chains to get draws from the desired distribution.
So here we have one source preferring to analytically derive the distribution implied by a Markov chain, and another that prefers to imply a Markov chain and then run it to get draws from a distribution.
It seems much easier to me to just run the chain -- so why is it that is not preferred by some statisticians?
I get the argument for analytic solutions in some edge cases where running the chain might have extreme computational cost -- but that has not been the case in the examples I've seen.
Will I make a mistake in practical terms if I choose to run the chain instead of derive probabilities analytically?
Comment: MCMC builds a Markov chain with a guaranteed stationary that is given in one form or another. This perspective is reversed: the Markov chain is given and the goal is to find its stationary, if any.
Comment: Running a Markov chain "until" stationary provides one realisation from the stationary distribution (assuming one can be certain to be in the stationary regime). This is far from "finding" the stationary distribution.
Comment: I don't think you are certain to reach the stationary distribution in finite time
Comment: @jcken in fact, I think I'm guaranteed not to reach it! But in practical terms, as an industrial statistician facing ill-specified problems and decisions with some tolerance for error, I usually get close enough to it in a time span measured in minutes at worst, in my experience. And I can always verify whether I have with the bootstrap, so I don't think of that as an obstacle.
Comment: @Xi'an right, which implies to me that running the Markov chain is, at least in many cases, comparatively effective to find the stationary distribution. So why would the authors prefer analytical solutions?
Comment: @Xi'an I feel like maybe my terminology is incorrect -- wouldn't the long-run proportion the Markov chain is in each state, when run for some time, be the stationary distribution?
Comment: "but that has not been the case in the examples I've seen": examples in textbooks are designed to be easy.
Comment: @Tim I was talking also about examples I've encountered professionally, to be clear!
Answer: In theory, some Markov chains will not have a stationary distribution. Hence, using theoretical approaches deriving the stationary distribution from the transition matrix itself should identify this issue, while simply running simulations could make it more difficult, especially if you are not careful about this potential issue.
Comment: While this is a valid concern, I'm not sure "some prefer analytical solutions because if you're not careful the numerical solution might be inappropriate" is an argument that flies with me, simply because you have to be very careful to get analytical solutions right too!
Comment: Fair enough! Both require some checks.
Answer: I find it useful to draw a distinction between the standard use of Markov chains for statistical modelling purposes from use of MCMC techniques for integration.  In the latter case, we are talking about a clever use of Markov chains to write an integral of interest as the stationary distribution of the chain, in order to allow a new form of numerical integration.  This is essentially the reverse of the standard use of Markov chains, where the chain itself is specified, but its stationary distribution is derived from specification of the model.
Outside of the use of MCMC methods for numerical integration, Markov chains are most commonly used for direct statistical modelling of data.  There are a number of results in this analysis that are made easier if you can derive the spectral decomposition of the transition probability matrix (or more generally, the Jordan normal form), which includes derivation of the stationary distribution(s).  Knowledge of this form allows you to get a number of simplified results in the analysis, so it is a common early computational step.  There are a few reasons that analytic derivation of the stationary distribution(s) is preferred over just running the chain for a long time:

Derivation of the stationary distribution(s) is often just seen as one piece of the broader derivation of the spectral decomposition (or Jordan normal form) of the transition probability matrix.  Once you derive all the eigenvalues and unit eigenvectors of this matrix, it is helpful for various aspects of later analysis.  As part of this derivation you will have identified the stationary distribution(s) of the chain.

There are cases of Markov chains where there are stationary distribution does not exist or is not unique.  In the latter case, any convex combination of two stationary distributions is also a stationary distribution.  Consequently, deriving the stationary distribution merely by running the chain for a long time may not work, and if it does it often misses the full specification of all possible stationary distributions in the chain.

Direct analytic derivation of the stationary distribution is often computationally quicker and more accurate than derivation via running the chain for a long time.
Answer: The book I was reading pointed out in a later chapter the obvious that I had missed.
By learning to work on Markov chains analytically, it's possible to derive probabilities that are functions of inputs of high dimension, and answer more interesting counterfactuals in the form of "if I vary this one parameter out of five, what happens to the quantities involved?"
This is technically possible also numerically, but the higher dimensions of inputs start to hurt sooner -- both computationally and in trying to interpret the results, as they will always be conditional on a bunch of other values.
Comment: This is a general fact.  Mathematical analysis always is superior to simulation in this respect.


What happens when I initialize an array having the size as a variable?

Question: I want to know where is my array stored if it has variable size such as in the code below this is because in my textbook it says that during runtime memory is allocated to the heap to my understanding, but it seems that it actually allocated to the stack can someone clarify how stack and heap memory allocation actually works.
#include<iostream>
using namespace std;

int main(){
int Array_size;
cin >> Array_size;
int array[Array_size];
return 0;
}

Comment: That is not valid C++. it uses VLA extension.
Comment: this is not valid c++
Comment: That's not valid standard c++. The standard doesn't support variable length arrays. Just look that up.
Comment: You can't do that in a standard compliant manner in C++. Use a `std::vector`.
Comment: Answer: you invoke *Undefined Behavior* and a compiler error -- unless your compiler supports the VLA extension for C++.
Answer: Your book is wrong, or you are misreading it.
A Variable-Length Array (a non-standard extension implemented by few C++ compilers) is always allocated in automatic memory (ie, on the stack), never in dynamic memory (ie, on the heap).  The array's memory is reclaimed by the compiler when the array goes out of scope, just like any other local variable.
Dynamic memory is allocated only by the new operator, or by the [std::](m|c)alloc() functions.
Answer: Stack and heap memory are a bit abstract so I understand your confusion. In general, any variables inside functions, including main, that are not dynamically allocated (i.e. declaring a variable using new) go on the stack. If you declare a pointer, that pointer points to a variable on the heap while the pointer remains on the stack. This is why you must always clear the pointer using delete and, preferably, set the pointer to NULL if it has no more use. Any variables or functions that are pushed onto the stack are popped automatically (think of push and pop as inserting and removing, it's just correct terminology). Memory on the heap is allocated and deallocated manually and during runtime. Hopefully that clears some confusion.


TFA Module not providing place to enter code, email is sent

Question: I am having trouble getting TFA working on a new site -- Drupal 9.4.
My key's in place, I have email enabled, as well as trusted browser, etc. But when I go to login, after I enter the username and password, I am just returned back to the login page. The mail with the code gets sent -- I just have nowhere to enter that code.
I have another site, in the same multi-site, where it is working as expected. I enter my username and password, and it takes me to a page to enter my code. I did set the other one up a while back, but I can't find any significant differences between the two setups (the one minor thing is that the order to plugins is different on the settings page).
Feel like there must be something simple I am missing, a companion module I haven't installed, but I have yet to find it.
Permissions are set up the same on the two sites. I don't see any related errors logged.
Update:

The code seems to be firing through TFA.
It looks like it gets to the right route tfa/{userid}/{hash}
The formstate redirect seems to be set correctly
but it ends back on user/login
Answer: The problem here was that I had a module with a
hook_user_login_form_submit redirecting the user to /user
which was overwriting the redirectURL of the submit form.
The good news is that I understand forms a bit better! It was pretty difficult to know that the redirect was being overridden... and I didn't know enough to look for it until I'd understood how the form worked.


Within bootstrap theme, print radio item with label and input as siblings instead of parent -> child

Question: By default, Bootstrap will render the input radio and checkbox elements as children of the label.  This is done in Drupal\bootstrap\Plugin\Preprocess\FormElement, starting at line 45:
// Place single checkboxes and radios in the label field.
if (($checkbox || $radio)) {
  $label = Element::create($variables['label']);
  $children = &$label->getProperty('children', '');

In some instances, I don't want these printed as siblings - how can I undo this?  form-element.html.twig isn't helpful unless I can somehow print the children first e.g. {{ label.#children }} and then twig will know not to print them again.  Not sure if that solution is even possible.
Thanks!
Answer: At first I was going to say hook_form_alter, but when I started digging into the Bootstrap theme I found they've created their own plugin system. I would checkout this page, you might be able to get to the render array by creating a Bootstrap theme plugin: https://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins_form/8
Comment: I posted a full answer with code samples but you are correct, the solution is to extend the appropriate `\Preprocess\[element name]`
Answer: As @icicleking states, bootstrap uses theme plugins that can be extended.  So that we have a thorough answer for what I did I'll post it separately here.
Extend \Drupal\bootstrap\Plugin\Preprocess\FormElement.  There's only one method, preprocessElement.  In my case I replaced the following:
// Place single checkboxes and radios in the label field.
if (($checkbox || $radio)) {
  $label = Element::create($variables['label']);

with
// Place single checkboxes and radios in the label field.
if (($checkbox || $radio) && !$element->hasProperty('no_wrap_label')) {
  $label = Element::create($variables['label']);

Then you can use the no_wrap_label property on any element that you don't want to be wrapped inside a label, I'm using hook_preprocess_form_element:
function your_module_preprocess_form_element(&$variables) {
  if ($variables['name'] == 'field_field_name') {
    $variables['element']['#no_wrap_label'] = TRUE;
  }
}

Comment: Is that mean we have to modify bootstrap core theme? code at https://www.drupal.org/project/bootstrap/issues/2644016 is for 7 (although Closed (won't fix) by module author)
more discussion at https://ux.stackexchange.com/a/104517 https://stackoverflow.com/a/13317256 https://www.thirdandgrove.com/theming-form-elements-drupal-8


Optimized alternative code for the function to reverse input string word by word in SQL SERVER

Question: alter FUNCTION FlipName(@input VARCHAR(250))
RETURNS VARCHAR(250)

AS BEGIN

DECLARE @i int ,@add varchar(255)
set @i=1
set @add=''
declare @work varchar(250)
set @work=''
WHILE @i <= len(@input)
BEGIN
  declare @pivot varchar(255)
  set @pivot=SUBSTRING(@input,@i,1)
  while @pivot <>' '
  begin
     set @add=@add+@pivot
     set @i=@i+1
     set @pivot=SUBSTRING(@input,@i,1)
  end

  set @work=@add+' '+@work
  set @add=''

  SET @i = @i + 1

END
return @work
END

Sample Input: My name is Jarvis
Sample Output:Jarvis is name My

I am looking for better,shorter and more concise alternative code to this as the nested loops here are performance killers.
I am looking for a better workaround without loops maybe
Please provide a concise explanation to your solution stating how is it better.
Thank you in advance
Comment: The sensible alternative is to not be doing string manipulation in a language such as T-SQL which is notoriously weak in terms of its support for string manipulation. Why does this code belong in the database *at all*?
Comment: Having a `WHILE` loop **inside** a `WHILE` loop is going to also be awful for performance. SQL Server is terrible at iterative processes; it's far better at set based processes.
Comment: I agree T-SQL isn't the best language for doing string manipulation.Having said that i am just looking for better alternative solution to the above scalar function
Comment: @Larnu Yes, that is why i am here looking for some alternative workaround to achieve this without nested loop.
Comment: One thing about these sorts of codings, is that you've always got to be careful to code for (or validate input), for various odd boundary conditions, things like leading and trailing spaces, words with >1 spaces between them.  What happens then?  Always best to test that.
Answer: T-SQL is not best solution for string manipulation. But it could be done without loop at all (SQL Server 2017+):
DECLARE @s NVARCHAR(MAX) = N'My name is Jarvis';

SELECT @s, STRING_AGG(value, ' ') WITHIN GROUP(ORDER BY rn DESC)
FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY 1/0)AS rn
      FROM STRING_SPLIT(REPLACE(@s, ' ', '.'), '.'))s;

DBFiddle Demo
Comment: And don't forget, when you create this as a function use a Table-Value function, not a scalar function.
Comment: Thanks.Great Solution, But as Larnu pointed out that STRING_SPLIT and STRING_AGG are more recently added function and would not be supported by previous versions
Comment: Nice solution but this is not guaranteed to work.  We have to wait for `split_string()` to provide an ordinality column as well as the string part.
Answer: Considering that ordinal position is important here (something that STRING_SPLIT doesn't return), and that STRING_SPLIT and STRING_AGG are more recently added function, you could use delimitedsplit8k and FOR XML PATH. This means that the order is guaranteed (as delimitedsplit8k returns the ordinal position) and it means you don't need SQL Server 2017:
USE Sandbox;
GO

CREATE FUNCTION dbo.ReverseString_fn (@input varchar(255))
RETURNS table AS
RETURN

    SELECT STUFF((SELECT ' ' + DS.Item
                  FROM dbo.DelimitedSplit8K(@input,' ') DS
                  ORDER BY DS.ItemNumber DESC
                  FOR XML PATH('')),1,1,'') AS ReverseString;
GO

WITH VTE AS (
    SELECT 'My name is Jarvis' AS String)
SELECT *
FROM VTE V
     CROSS APPLY dbo.ReverseString_fn(V.String) RS;
GO

DROP FUNCTION dbo.ReverseString_fn;

Comment: As for why I didn't provide a DB Fiddle, or similar, that's because I am citing a function designed by Jeff Moden. I doubt they would be happy for me to put their work in a DB Fiddle. You would be much better off reading their article I linked to in my answer.
Comment: Great!! Could you provide me with code demo as this also seems to NOT be running on my SQL server 2014
Comment: @alamshahbaz16497 "Seems to not be running"? Are you getting an error? If so, what is the error? The above is a demo. It creates the function and then uses it.
Comment: Can you please provide a link to some online IDE where you tested this code as I am not able to run this on SQL14 and azure
Comment: @alamshahbaz16497 again, what do you able "not able to run"? If you can't execute the query, I would suggest you don't have permission to `CREATE` on your database; as that's the first statement in the batch. Again, what is the error you are getting?
Comment: >Msg 208, Level 16, State 1, Procedure ReverseString_fn, Line 7
>Invalid object name 'dbo.DelimitedSplit8K'.
>Msg 208, Level 16, State 1, Line 12
>Invalid object name 'dbo.ReverseString_fn'.
>Msg 3701, Level 11, State 5, Line 19
>Cannot drop the function 'dbo.ReverseString_fn', because it does not exist or >you do not have permission.  P.S-I have not down voted.
Comment: @alamshahbaz16497 Seems you haven't created `dbo.DelimitedSplit8K`. Have you clicked the link I provided?
Comment: I've love to hear some constructive feedback from the downvote, please.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174156/discussion-between-alamshahbaz16497-and-larnu).
Answer: and yet one more... The following approach is fully inline and uses an on-the-fly tally table in connection with XML's ability to fetch an element by its position:
DECLARE @input VARCHAR(100)='My name is Jarvis';

WITH Casted(inputXml) AS
(
    SELECT CAST('<x>' + REPLACE((SELECT @input AS [*] FOR XML PATH('')),' ','</x><x>') + '</x>' AS XML)
)
,Tally(Nmbr) AS
(
    SELECT TOP(SELECT inputXml.value('count(/x)','int') FROM Casted) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM master..spt_values
)
SELECT STUFF(
(
    SELECT ' ' + c.inputXml.value('(/x[sql:column("t.Nmbr")]/text())[1]','varchar(100)')
    FROM Tally t
    CROSS JOIN Casted c
    ORDER BY t.Nmbr DESC
    FOR XML PATH(''),TYPE).value('.','varchar(max)'
),1,1,'');

Answer: I don't suggest doing it in backend.
But for a work around(below SQL Server 2016) you can have below code.
You can make a function with the below code and call it on table rows.
DECLARE @VAL VARCHAR(MAX) ='My name is Jarvis', @NEW_VAL VARCHAR(MAX)='';

SELECT @VAL = '<M>'+ REPLACE(@VAL, ' ','</M><M>')+'</M>';

SELECT @NEW_VAL = @NEW_VAL+ ' ' + NEW_TEXT FROM (
SELECT ROW_NUMBER() OVER(ORDER BY(SELECT 1)) SNO,
 splt.x.value('.','varchar(100)') NEW_TEXT FROM (
SELECT CAST(@VAL AS XML) AS DATA
)AS A
CROSS APPLY DATA.nodes('/M') as splt(x)
)B
ORDER BY SNO DESC;

SELECT @NEW_VAL

Result:
 Jarvis is name My

Answer: If you want to reverse string word by word then you can use following optimized code for it.
CREATE FUNCTION [dbo].[fn_ReverseWordsInSentence]
(
    @ip VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)

BEGIN
    DECLARE @op VARCHAR(MAX)
    SET @op = ''
    DECLARE @Lenght INT

    WHILE LEN(@ip) > 0
    BEGIN
        IF CHARINDEX(' ', @ip) > 0
        BEGIN
        SET @op = SUBSTRING(@ip,0,CHARINDEX(' ', @ip)) + ' ' + @op
        SET @ip = LTRIM(RTRIM(SUBSTRING(@ip,CHARINDEX(' ', @ip) + 1,LEN(@ip))))
    END
    ELSE
        BEGIN
        SET @op = @ip + ' ' + @op
        SET @ip = ''
        END
    END
RETURN @op
END

You execute this function with the input string you mentioned as follows.
SELECT [dbo].[fn_ReverseWordsInSentence] ('My name is Jarvis')

And this will return following string as output.
"Jarvis is name My"
If you just want reverse entire string character by character then you can use Sql Server in built reverse string function.
DECLARE @test varchar(250) = 'My name is Jarvis'

SELECT reverse(@test)

And this will return "sivraJ si eman yM" as output.
Comment: A `WHILE` loop is still a bad choice here.
Comment: @SandipPatel but the OP is looking for concise, and faster, code, and they've stated (in the comments) they looking for a method with a loop, wouldn't a loop therefore be the wrong choice? Especially when they are so frowned upon when there is a set-based solution. :) Yes, the answer is "right(ish)", however, that doesn't m,ake it a good answer. String Splitters that use `WHILE` loops and `CURSOR` are "correct" answers, but they're also very bad ones, when far better approaches are available.
Comment: @Larnu: the answer give solution but way is little bit wrong, so there should no down vote for it
Comment: @SandipPatel this thing is, `WHILE` loops are notorious slow in SQL Server. `WHILE` loops and `CURSOR`s are misused a lot, especially when doing something that should be set based. Can you imagine how slow this would be against a table with 1,000 or so rows? It would require 1,000 (or so) `WHILE` loops (as this would have to be a scalar function), each iterating over **every** character in **every**`varchar`. That is never going to perform well.
Comment: @Larnu: as I told the answer little bit wrong way, but the solution is right. From my point of view the solution of any question comes first then after other things which you can improve as you got experience.
Comment: I would go a step further, string splitter that use loops are not correct answers because they are so slow. There are many set based splitters available all over the place that using one with a loop is just awful. Even though this answer returns the correct data the approach is so painfully slow it needs to be downvoted or other people may think it is ok to use loops for this kind of thing.


Electoral college simulation using SQL Server

Question: As I'm sure will be apparent to most here, I'm not a statistician or a programmer, but one of my hobbies is politics. I've created a (very simple) USA electoral college simulation, seen below.
The idea is that if you think you have a good estimate of the probabilities of the different states, you can simply run a simulation to get the odds of victory for the candidates. Technically, the way this works is, say you assume the R candidate has a 45% of victory in, say, Wisconsin. The SQL rand() function should return a value (roughly speaking) less than or equal to 45% roughly 45% of the time. So over a million rows you'd expect for rand() to produce around 450,000 rows that are 45% or less. So for each row where this is "true" I assign electoral college points, but I do it for the same randomized number across all states.
I guess my question is, does this simple SQL model make sense or am I fooling myself into thinking that if I can get good state probabilities that this will actually produce a decent overall probability? The actual state odds I have in there right now are of course completely fictitious as I've been playing with different numbers.
<code>--run once
Create Table database.dbo.Numbers(
[Num] [int] NOT NULL,
CONSTRAINT [PK_Numbers] PRIMARY KEY CLUSTERED
([Num] ASC ))

Insert into database.dbo.Numbers
select top 10000000 row_number() over (order by s1.name)
from sysobjects s1 cross join sysobjects s2, sysobjects s3
</code>
<code>--run many times
--input the probability of R win for each state

declare @AK as float
Set @AK = .99

declare @AL as float
Set @AL = .99

declare @AR as float
Set @AR = .999

declare @AZ as float
Set @AZ = .4

declare @CA as float
Set @CA = .01

declare @CO as float
Set @CO = .5

declare @CT as float
Set @CT = .01

declare @DE as float
Set @DE = .01

declare @FL as float
Set @FL = .5

declare @GA as float
Set @GA = .5

declare @HI as float
Set @HI = .01

declare @IA as float
Set @IA = .6

declare @ID as float
Set @ID = .99

declare @IL as float
Set @IL = .01

declare @IN as float
Set @IN = .8

declare @KS as float
Set @KS = .8

declare @KY as float
Set @KY = .7

declare @LA as float
Set @LA = .7

declare @MA as float
Set @MA = .01

declare @MD as float
Set @MD = .01

declare @ME as float
Set @ME = .01

declare @MI as float
Set @MI = .45

declare @MN as float
Set @MN = .5

declare @MO as float
Set @MO = .8

declare @MS as float
Set @MS = .9

declare @MT as float
Set @MT = .99

declare @NC as float
Set @NC = .55

declare @ND as float
Set @ND = .99

declare @NE as float
Set @NE = .7

declare @NH as float
Set @NH = .1

declare @NJ as float
Set @NJ = .1

declare @NM as float
Set @NM = .3

declare @NV as float
Set @NV = .5

declare @NY as float
Set @NY = .01

declare @OH as float
Set @OH = .6

declare @OK as float
Set @OK = .8

declare @OR as float
Set @OR = .99

declare @PA as float
Set @PA = .5

declare @RI as float
Set @RI = .1

declare @SC as float
Set @SC = .99

declare @SD as float
Set @SD = .99

declare @TN as float
Set @TN = .8

declare @TX as float
Set @TX = .55

declare @UT as float
Set @UT = .99

declare @VA as float
Set @VA = .1

declare @VT as float
Set @VT = .2

declare @WA as float
Set @WA = .1

declare @WI as float
Set @WI = .6

declare @WV as float
Set @WV = .99

declare @WY as float
Set @WY = .9

declare @DC as float
Set @DC = .01

declare @ME1 as float
set @ME1 = .2

declare @ME2 as float
set @ME2 = .8

declare @NE1 as float
set @NE1 = .99

declare @NE2 as float
set @NE2 = .5

declare @NE3 as float
set @NE3 = .99

Select F.WinLose,cast(F.Count as float) / cast(F.Sumtotal as float) as Chance

from

(

Select E.WinLose,E.Count,sum(E.Count) over () as Sumtotal

from

(Select D.WinLose,count(D.Winlose) as Count

from

(Select C.Num,(case when (C.[R-AK]+C.[R-AL]+C.[R-AR]+C.[R-AZ]+C.[R-CA]+C.[R-CO]+C.[R-CT]+C.[R-DC]+C.[R-DE]+C.[R-FL]+C.[R-GA]
+C.[R-HI]+c.[R-IA]+c.[R-ID]+c.[R-IL]+c.[R-IN]+c.[R-KS]+c.[R-KY]+c.[R-LA]+c.[R-MA]+c.[R-MD]+c.[R-ME]+c.[R-MI]+c.[R-MN]+c.[R-MO]
+c.[R-MS]+c.[R-MT]+c.[R-NC]+c.[R-ND]+c.[R-NE]+c.[R-NH]+c.[R-NJ]+c.[R-NM]+c.[R-NV]+c.[R-NY]+c.[R-OH]+c.[R-OK]+c.[R-OR]+c.[R-PA]+c.[R-RI]+
c.[R-SC]+c.[R-SD]+c.[R-TN]+c.[R-TX]+c.[R-UT]+c.[R-VA]+c.[R-VT]+c.[R-WA]+c.[R-WI]+c.[R-WV]+c.[R-WY]+c.[R-NE1]+c.[R-NE2]+c.[R-NE3]+c.[R-ME1]+c.[R-ME2])

 >= 269 then 'Win' else 'NotWin' end) as WinLose

from

(Select B.Num,(case when B.AK = 'TRUE' then 3 else 0 end) as 'R-AK',
(case when B.AL = 'TRUE' then 9 else 0 end) as 'R-AL',
(case when B.AR = 'TRUE' then 6 else 0 end) as 'R-AR',
(case when B.AZ = 'TRUE' then 11 else 0 end) as 'R-AZ',
(case when B.CA = 'TRUE' then 55 else 0 end) as 'R-CA',
(case when B.CO = 'TRUE' then 9 else 0 end) as 'R-CO',
(case when B.CT = 'TRUE' then 7 else 0 end) as 'R-CT',
(case when B.DE = 'TRUE' then 3 else 0 end) as 'R-DE',
(case when B.FL = 'TRUE' then 29 else 0 end) as 'R-FL',
(case when B.GA = 'TRUE' then 16 else 0 end) as 'R-GA',
(case when B.HI = 'TRUE' then 4 else 0 end) as 'R-HI',
(case when B.IA = 'TRUE' then 6 else 0 end) as 'R-IA',
(case when B.ID = 'TRUE' then 4 else 0 end) as 'R-ID',
(case when B.IL = 'TRUE' then 20 else 0 end) as 'R-IL',
(case when B.[IN] = 'TRUE' then 11 else 0 end) as 'R-IN',
(case when B.KS = 'TRUE' then 6 else 0 end) as 'R-KS',
(case when B.KY = 'TRUE' then 8 else 0 end) as 'R-KY',
(case when B.LA = 'TRUE' then 8 else 0 end) as 'R-LA',
(case when B.MA = 'TRUE' then 11 else 0 end) as 'R-MA',
(case when B.MD = 'TRUE' then 10 else 0 end) as 'R-MD',
(case when B.MI = 'TRUE' then 16 else 0 end) as 'R-MI',
(case when B.MN = 'TRUE' then 10 else 0 end) as 'R-MN',
(case when B.MO = 'TRUE' then 10 else 0 end) as 'R-MO',
(case when B.MS = 'TRUE' then 6 else 0 end) as 'R-MS',
(case when B.MT = 'TRUE' then 3 else 0 end) as 'R-MT',
(case when B.NC = 'TRUE' then 15 else 0 end) as 'R-NC',
(case when B.ND = 'TRUE' then 3 else 0 end) as 'R-ND',
(case when B.NH = 'TRUE' then 4 else 0 end) as 'R-NH',
(case when B.NJ = 'TRUE' then 14 else 0 end) as 'R-NJ',
(case when B.NM = 'TRUE' then 5 else 0 end) as 'R-NM',
(case when B.NV = 'TRUE' then 6 else 0 end) as 'R-NV',
(case when B.NY = 'TRUE' then 29 else 0 end) as 'R-NY',
(case when B.OH = 'TRUE' then 18 else 0 end) as 'R-OH',
(case when B.OK = 'TRUE' then 7 else 0 end) as 'R-OK',
(case when B.[OR] = 'TRUE' then 7 else 0 end) as 'R-OR',
(case when B.PA = 'TRUE' then 20 else 0 end) as 'R-PA',
(case when B.RI = 'TRUE' then 4 else 0 end) as 'R-RI',
(case when B.SC = 'TRUE' then 9 else 0 end) as 'R-SC',
(case when B.SD = 'TRUE' then 3 else 0 end) as 'R-SD',
(case when B.TN = 'TRUE' then 11 else 0 end) as 'R-TN',
(case when B.TX = 'TRUE' then 38 else 0 end) as 'R-TX',
(case when B.UT = 'TRUE' then 6 else 0 end) as 'R-UT',
(case when B.VA = 'TRUE' then 13 else 0 end) as 'R-VA',
(case when B.VT = 'TRUE' then 3 else 0 end) as 'R-VT',
(case when B.WA = 'TRUE' then 12 else 0 end) as 'R-WA',
(case when B.WI = 'TRUE' then 10 else 0 end) as 'R-WI',
(case when B.WV = 'TRUE' then 5 else 0 end) as 'R-WV',
(case when B.WY = 'TRUE' then 3 else 0 end) as 'R-WY',
(case when B.DC = 'TRUE' then 3 else 0 end) as 'R-DC',

(case when B.NE = 'TRUE' then 2 else 0 end) as 'R-NE',
(case when B.ME = 'TRUE' then 2 else 0 end) as 'R-ME',
(case when B.ME1 = 'TRUE' then 1 else 0 end) as 'R-ME1',
(case when B.ME2 = 'TRUE' then 1 else 0 end) as 'R-ME2',
(case when B.NE1 = 'TRUE' then 1 else 0 end) as 'R-NE1',
(case when B.NE2 = 'TRUE' then 1 else 0 end) as 'R-NE2',
(case when B.NE3 = 'TRUE' then 1 else 0 end) as 'R-NE3'

from

(Select A.Num,A.RanSelection,
(Case when A.RanSelection <= @AK then 'TRUE' else 'FALSE' end) as AK,
(Case when A.RanSelection <= @AL then 'TRUE' else 'FALSE' end) as AL,
(Case when A.RanSelection <= @AR then 'TRUE' else 'FALSE' end) as AR,
(Case when A.RanSelection <= @AZ then 'TRUE' else 'FALSE' end) as AZ,
(Case when A.RanSelection <= @CA then 'TRUE' else 'FALSE' end) as CA,
(Case when A.RanSelection <= @CO then 'TRUE' else 'FALSE' end) as CO,
(Case when A.RanSelection <= @CT then 'TRUE' else 'FALSE' end) as CT,
(Case when A.RanSelection <= @DE then 'TRUE' else 'FALSE' end) as DE,
(Case when A.RanSelection <= @FL then 'TRUE' else 'FALSE' end) as FL,
(Case when A.RanSelection <= @GA then 'TRUE' else 'FALSE' end) as GA,
(Case when A.RanSelection <= @HI then 'TRUE' else 'FALSE' end) as HI,
(Case when A.RanSelection <= @IA then 'TRUE' else 'FALSE' end) as IA,
(Case when A.RanSelection <= @ID then 'TRUE' else 'FALSE' end) as ID,
(Case when A.RanSelection <= @IL then 'TRUE' else 'FALSE' end) as IL,
(Case when A.RanSelection <= @IN then 'TRUE' else 'FALSE' end) as "IN",
(Case when A.RanSelection <= @KS then 'TRUE' else 'FALSE' end) as KS,
(Case when A.RanSelection <= @KY then 'TRUE' else 'FALSE' end) as KY,
(Case when A.RanSelection <= @LA then 'TRUE' else 'FALSE' end) as LA,
(Case when A.RanSelection <= @MA then 'TRUE' else 'FALSE' end) as MA,
(Case when A.RanSelection <= @MD then 'TRUE' else 'FALSE' end) as MD,
(Case when A.RanSelection <= @ME then 'TRUE' else 'FALSE' end) as ME,
(Case when A.RanSelection <= @MI then 'TRUE' else 'FALSE' end) as MI,
(Case when A.RanSelection <= @MN then 'TRUE' else 'FALSE' end) as MN,
(Case when A.RanSelection <= @MO then 'TRUE' else 'FALSE' end) as MO,
(Case when A.RanSelection <= @MS then 'TRUE' else 'FALSE' end) as MS,
(Case when A.RanSelection <= @MT then 'TRUE' else 'FALSE' end) as MT,
(Case when A.RanSelection <= @NC then 'TRUE' else 'FALSE' end) as NC,
(Case when A.RanSelection <= @ND then 'TRUE' else 'FALSE' end) as ND,
(Case when A.RanSelection <= @NE then 'TRUE' else 'FALSE' end) as NE,
(Case when A.RanSelection <= @NH then 'TRUE' else 'FALSE' end) as NH,
(Case when A.RanSelection <= @NJ then 'TRUE' else 'FALSE' end) as NJ,
(Case when A.RanSelection <= @NM then 'TRUE' else 'FALSE' end) as NM,
(Case when A.RanSelection <= @NV then 'TRUE' else 'FALSE' end) as NV,
(Case when A.RanSelection <= @NY then 'TRUE' else 'FALSE' end) as NY,
(Case when A.RanSelection <= @OH then 'TRUE' else 'FALSE' end) as OH,
(Case when A.RanSelection <= @OK then 'TRUE' else 'FALSE' end) as OK,
(Case when A.RanSelection <= @OR then 'TRUE' else 'FALSE' end) as "OR",
(Case when A.RanSelection <= @PA then 'TRUE' else 'FALSE' end) as PA,
(Case when A.RanSelection <= @RI then 'TRUE' else 'FALSE' end) as RI,
(Case when A.RanSelection <= @SC then 'TRUE' else 'FALSE' end) as SC,
(Case when A.RanSelection <= @SD then 'TRUE' else 'FALSE' end) as SD,
(Case when A.RanSelection <= @TN then 'TRUE' else 'FALSE' end) as TN,
(Case when A.RanSelection <= @TX then 'TRUE' else 'FALSE' end) as TX,
(Case when A.RanSelection <= @UT then 'TRUE' else 'FALSE' end) as UT,
(Case when A.RanSelection <= @VA then 'TRUE' else 'FALSE' end) as VA,
(Case when A.RanSelection <= @VT then 'TRUE' else 'FALSE' end) as VT,
(Case when A.RanSelection <= @WA then 'TRUE' else 'FALSE' end) as WA,
(Case when A.RanSelection <= @WI then 'TRUE' else 'FALSE' end) as WI,
(Case when A.RanSelection <= @WV then 'TRUE' else 'FALSE' end) as WV,
(Case when A.RanSelection <= @WY then 'TRUE' else 'FALSE' end) as WY,
(Case when A.RanSelection <= @DC then 'TRUE' else 'FALSE' end) as DC,

(Case when A.RanSelection <= @ME1 then 'TRUE' else 'FALSE' end) as ME1,
(Case when A.RanSelection <= @ME2 then 'TRUE' else 'FALSE' end) as ME2,
(Case when A.RanSelection <= @NE1 then 'TRUE' else 'FALSE' end) as NE1,
(Case when A.RanSelection <= @NE2 then 'TRUE' else 'FALSE' end) as NE2,
(Case when A.RanSelection <= @NE3 then 'TRUE' else 'FALSE' end) as NE3

from

(SELECT TOP 1000000 [Num],RAND(convert(varbinary, newid())) as RanSelection
  FROM [Database].[dbo].[Numbers])A)B)C)D

  group by D.WinLose)E

  )F

```
</code>
Answer: I actually inputted Nate Silver's 2016 state-by-state odds into this and the results came very close to his overall 2016 prediction seen here.
https://projects.fivethirtyeight.com/2016-election-forecast/


Do random variables bounded by random variables which converge in mean also converge in mean?

Question: Let $X_n \ge 0$ be a sequence of random variables such that $X_n \to X$ in distribution.
Assume that $X_n$ is stochastically dominated by $Y_n \ge 0$, $Y_n \to Y$ in distribution, and $\mathbb{E}[Y_n] \to \mathbb{E}[Y]$.
Then do we have $\mathbb{E} X_n \to \mathbb{E}(X)$?

My guess is yes.
$Y_n$ is uniformly integrable. This is because we can find a coupling $(Y_n, Y_n')$ such that $Y_n' \sim Y_n$ and $Y_n' \to Y_n$ in probability. Since $\mathbb{E}(Y_n')=\mathbb{E}(Y_n) \to \mathbb{E}[Y]$, $Y_n'$ is uniformly integrable. This in turn suggests $Y_n$ is uniformly integrable.
This implies that $X_n$ is uniformly integrable. So we have $\mathbb{E}{X_n} \to \mathbb{E}{X}$. Is this correct?
Can we omit the condition that $Y_n \to Y$ in distribution?
Comment: What do u mean by "stochastic dominance"?
Comment: @KaviRamaMurthy I added a bit more explanation of my thoughts.
Answer: If you drop the assumption that $Y_n \to Y$ in distribution then  $Y$ almost looses its relevance. On $(0,1)$ with Lebesgue measure take $X_n=nI_{(0,\frac 1 n)},Y_n=X_n, X=0$ and  $Y=1$. This will give you a counterexample.
Comment: @ablmf I think your argument is correct when you have convergence in distribution.
Comment: But is my argument correct when $Y_n \to Y$ in distribution?


JavaFX ExtensionFilter not working properly in ubuntu

Question: I have created a small application in javafx wherein one has to choose JPG,PNG or GIF image to work with. Here's the code am using to filter the files :
FileChooserBuilder fcb = FileChooserBuilder.create();
FileChooser fc = fcb.title("Open Dialog").initialDirectory(new File(currentDir)).build();

//Set extension filter
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
FileChooser.ExtensionFilter extFilterGIF = new FileChooser.ExtensionFilter("GIF files (*.gif)", "*.GIF");

fc.getExtensionFilters().addAll(extFilterJPG, extFilterPNG, extFilterGIF);

selectedFile = fc.showOpenDialog(link);

This code works fine in Windows 7. But while using it in Ubuntu it doesn't show me all files with JPG, PNG or GIF. It shows a few, but I couldn't exactly make out why it does that.
Answer: Ubuntu and unix like systems are case sensitive. So it's filtering for "*.JPG" and maybe you have files with uppercase or lowercase extension. So the file won't match in the case of files with lowercase extension.
In windows, there is no problem, because it isn't case sensitive, I mean, one.jpg it's the same that one.JPG.
So to fix it add the extension in lowercase in the constructor of the ExtensionFilter.
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG", "*.jpg");

Hope it helps
Comment: As a note, this won't cover mixed case like .JpG, I couldn't find a way to have a case insensitive ExtensionFilter


Violin too small for daughter?

Question: My daughter is 6 years old and taking violin in school. They recommended that they go with 1/10 or 1/8. I went with 1/8 as she is on the taller side.
Receiving the violin in the mail, this thing looks tiny. When she holds it it is perfect size, but it seems as though she'd grow out of it really quickly.
I checked a chart online and it seems like 1/4 is for 5-7 year olds.
Would it be ok to go with the larger violin for her to grow into instead of the 1/8, where I fear she will grow out of it quickly?
Thanks!
Comment: I think normally instruments that come in different sizes are rented, so when the child is too large you simply switch to the next size up with the rental company. Perhaps that is not an option for you.
Comment: Renting would have been the best way to go.
Comment: Actually *too large* is the only problem you will encounter. An instrument, which is too small just sounds weaker than necessary, while a too big one may lead to wrong posture.
Answer: The important here is to have the correct size, and following a age chart is not the way to find it. Every child is different, some are small at the same age as others already grew up.
If the child can reach out their hand and close the hand around it with a straight arm then the violin is OK.
If when reaching the head and closing the hand the arm gets bent, the child needs a bigger violin.
If the child does not reach the head then the violin is too big.
If you are not sure between two of those possibilities then it's no big deal, it means soon you have to get a new instrument or that the instrument will fit better soon.
If it's very clear that it is too small or too big change it! A bad size will make the child get used to a bad position and will influence the tuning and ergonomy in a bad way.
Comment: That answer is now deleted. But it raised (strongly) the issue of possible improper use of a copyrighted image. Is there a similar non-copyrighted image that can be substituted?
Comment: I think you get no notification when another user writes an answere to the same question so i write this comment to inform you about the answere of @Dave Ingledew.
Answer: I agree with above. In my own personal experience, I switched directly to a 3/4 from a 1/4 with no in-betweens. This was challenging for me but gave me more time to practice with the spacing of the larger violin. At age 16 I got my LRSM (Licentiate of the Royal Schools of Music) in violin performance, so I guess I turned out ok?

Violin too small for daughter?


Is transaction support enabled by default?

Question: I happen to read through the commented lines in settings.php under the "Database settings" (around line no. 45) the following text:

Some database engines support transactions. In order to enable transaction support for a given database, set the 'transactions' key to TRUE. To disable it, set it to FALSE.
Note that the default value varies by driver. For MySQL, the default is FALSE since MyISAM tables do not support transactions.

My databases array, auto-generated by Drupal Installer, is the following one:
$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'test_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Is it true that my site is not transaction aware until I add a key/value, 'transaction' => TRUE (preferably after 'prefix' => '') to $databases?
Answer: Looking at DatabaseConnection_pgsql::__construct(), I noticed the following code:
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;

The code sets DatabaseConnection_pgsql::$transactionSupport to TRUE when the connection parameters don't contain the array index "transactions," which is one you should set in your settings.php file (it's not "transaction"), or when that array index is used in the connection parameters and it is not set to FALSE.
The same code is contained in
DatabaseConnection_mysql::__construct(); in this case, the connection parameters (the ones set in the settings.php file) should be set not to use transactions only when the tables used are MyISAM.
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;

Also DatabaseConnection_sqlite::__construct() contains the same code.
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = $this->transactionalDDLSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;

In short, the drivers used by Drupal always set the transaction support to TRUE, and users should set it to FALSE when they are using MyISAM tables, or they don't want to enable the transaction support.
Comment: Created an issue in drupal.org to fix it http://drupal.org/node/1221772#comment-4746926
Comment: Thanks @kiamlaluno and @wiifm, I guess the line `In order to enable transaction support for a given database, set the 'transactions' key to TRUE` to be removed/rephrased.
Answer: First things first, your database requires the InnoDB engine as MyISAM tables do not support transactions.
From the sounds of the README you then need to add the key to the array as you suggested above.
More information on transactions in general http://drupal.org/node/355875


Question about associating models

Question: I'm working on a Dungeons and Dragons character database. I have two models, character and statistic. I want this to work where each character has one set of statistics. The problem is, when I create a new character, every character shares the same statistic information. This is probably a really easy problem to solve, but I've been butting my head up against it and can't figure it out.
Here's code from the character model:
class Character < ActiveRecord::Base
  has_many :statistics, :dependent => :destroy
end
Here's code from the statistic model:
class Statistic < ActiveRecord::Base
  belongs_to :character
end
What's the proper code for displaying the statistic model when viewing the character? Do I need to use a link_to or a render tag? Thanks!
Answer: Since there is many of them, you'll need to use a loop or something:

  <% @character.statistics.each do |stat| %>

<%= stat %>

  <% end %>

Even better would be to use a partial:

  <% @character.statistics.each do |stat| %>
    <%= render :partial => "characters/statistic", :object => stat %>
  <% end %>

Then you'll have app/views/characters/_statistic.html.erb:

<%= statistic %>

This way you can use the code for the statistic rendering in other places too.
Comment: Thanks for the help! Another question, though. Since each character will only have one instance of the statistic model, do I need to declare has_many? At first, I thought has_one was the way to go, but then I thought it should be has_many since I will have more than one character instance. Which is the right way to go?
Comment: If the Character only has one statistic, then has_one is the way to go. Do you mean that each statistic will belong to many characters, or you'll just have multiple characters in your system?
Comment: I'll have multiple characters in the system. I'm assuming I'll want each character to have one instance of the statistic model, since each character will just have one set of statistics.
Comment: Hmm, so they have one _set_ of statistics? That would mean they have many statistics, so your original has_many/belongs_to setup was the right one. If it's D&D, I'm guessing that each character would have the 6 different statistics, which is a has_many relationship.
Comment: Yeah, each character will have 6 different stats. I'm still having the problem with all characters sharing the same stat, however. I'm not sure where I need to put the code you posted.
Comment: That code goes in a view for when you want to display the character. The same stat issue is probably because the foreign keys are not correctly set. The statistics table should have a character_id field which should be set to the id of the corresponding character.
Comment: I think this is where I first ran into trouble. How do I make that declaration? Does it go in the statistic model, the character model or both?
Comment: It should be in your migration that creates the statistics table. Something like t.integer :character_id although it has been a while since I did any Rails so the exact syntax might have changed.

Question about associating models


JQuery UI Drag & Drop And Align

Question: Here is my draggable and droppable implementation: http://jsfiddle.net/A26ww/
I have groups of playlists and I need to be able to drag a playlist from one group to another. I can do that however I would like to nicely position / align the dropped playlist. Right now it just stays in an awkward position after dropping.
Here is the problem:

I would like the dropped divto align nicely with other divs in the droppable container.
My code:
$(function() {
    $(".draggable").draggable({
        revert: "invalid"
    });

    $(".droppable").droppable({
        drop: function(event, ui) {
            // TODO HELP ME
        }
    });
});

Comment: Just out of curiosity: Was my answer not what you were looking for?
Answer: I think jQuery UI sortable is what you are looking for. I hope you can change your HTML markup.
Especially see the connected lists possibility.
I updated your jsfiddle.
$('.draggable, .droppable').sortable({
    connectWith: '.playlists'
});

Changing it to sortable requires a few changes but still I think this is easier to achieve with sortable than draggable/droppable.
Instead of
 I used
 and
 and styled them accordingly. (but there are some minor changes you have to do, so the styling looks exactly the same as with divs)

Group A

Playlist 0

Playlist 1

Playlist 2

Playlist 3

EDIT
Referring to @R2D2's comment I added the min-height property, so even an empty list (
) has enough height to accept a dropped element.
Comment: Seems like it didn't save my comment O.o However @R2D2 I updated my fiddle and added a short comment. Should work now :)
Comment: One thing, when you drag all elements from group B and drop them in group A (leaving group B empty), you can't drop any elements back to group B.

JQuery UI Drag & Drop And Align


Filter by item name in - Inventory management/Inquiries/On-hand

Question: As far as I understand, ProductName column is shown via a display methods. At least for my implementation here and this method resides in InventSum table:
display public ItemNameDisplay itemName()
{
    // Fields might not have been selected on the specified buffers, or might have been updated since selection
    this.checkInvalidFieldAccess(false);

    if (this.InventDimId)
    {
        return this.inventTable().itemName(InventDim::find(this.InventDimId));
    }
    return this.inventTable().itemName();
}

When I hit Ctrl + G and try to filter the data, this option is disabled for the above column and I think this happens due to that display method.  Is there any way I could achieve this functionality?
Should I try ( at right click ) to add another MenuItem there and do the filtering with the help of a new dialog ( where i will write down the item name),somehow followed by a refresh on the form?
Update 1:
I've found and edited this approach for my special case:
public void context()
{
   InventTable inventTable;

   int selectedMenu;
   real test;
   formrun fr;
   Args ag;
   Itemname strtext;
   querybuilddataSource qb1;
   queryrun qr;
   query q;
   PopupMenu menu = new PopupMenu(element.hWnd());
   int a = menu.insertItem('Find');
   int c = menu.insertItem('Remove Filter');

   selectedMenu = menu.draw();

   switch (selectedMenu)
   {
       case -1:
       break;

       case a:
       ag = new args('SysformSearch');
       fr = new formrun(ag);
       fr.run();
       fr.wait();
       strtext = fr.design().controlName('FindEdit').valueStr();

      if(strtext)
      {
          select ItemId from inventTable
          where inventTable.NameAlias == strtext;

          InventSum_DS.filter(FieldNum(InventSum,ItemId),Sysquery::value(inventTable.ItemId));
      }
      break;

      case c :
          InventSum_DS.removeFilter();
      break;

      Default:
      break;
   }
}

Still I think is not the correct way to just display a new PopupMenu. I would like to hook to the usual menu and add the new Find and Remove Filter right there. And .. remove filter takes a while, I should signal this somehow so the user don't panic.
Comment: Do you want to filter by item name (as stated in your question) or by name alias (as implemented in your update 1)? The possible solutions are quite different for these two fields.
Comment: @FH-Inway, I would like to filter by item name.
Comment: I can't seem to control the things this way. If the user wants to have many results I will have to add many ranges and perform a strScan somehow to check all the values which contain the desired string, and maybe the string contains * or ! etc.. i am going nowhere..
Answer: I've found this article:
Join ItemName from (EcoResProductTranslation )
Basically, we create a query based on InventTable, EcoResProduct and EcoResProductTranslation in order to get the name of the product starting from the Product field in the InventTable.
A new relation is added on InventSum:

On InventOnHandItem > DataSources > InventSum > Methods > executeQuery I've added the new ds:
element.inventDimSetupObject().modifyQuery(inventSum_DS,inventDim_DS, InventLookupView_ds);

And in the class :
InventDimCtrl_Frm_OnHand > modifyQuery, I've added this parameter:
FormDataSource _inventLookup = null

so now i have this:
public void modifyQuery(
   FormDataSource _inventSum_DS,
   FormDataSource _inventDim_DS,
   FormDataSource _inventLookup = null
)

A query build data source instance :
QueryBuildDataSource    qbsInventLookup;

And this section of code:
if(_inventLookup)
{
    qbsInventLookup = query.dataSourceName(_inventLookup.name());

    //filter current company language
    //qbr = SysQuery::findOrCreateRange(qbsInventLookup, fieldnum(InventLookupView, LanguageId));
    //qbr.value(queryValue(CompanyInfo::languageId()));

    qbsInventLookup.addGroupByField(fieldNum(InventLookupView, Name));
    //qbsInventLookup.addGroupByField(fieldNum(InventLookupView,NameAlias));
}

The newly created view is added as a data source in the InventSum :

And drag the Name field from this data source to the grid. It worked just fine for me.
Answer: Using a context menu is not the way to do it, complements for the idea though.
What you need to do extend the form with datasources for the required field.
In this case it requires InventTable inner joined to InventSum, EcoResProduct inner joined to InventTable and EcoresProductTranslation inner joined to EcoResProduct. Add the field EcoresProductTranslation.Name as a field in the grid.
You will have to do a range on the preferred language. There will be no output if no translation to that language exists.
As the query is a group by query, you will need to group by on EcoresProductTranslation.Name.
The code of the form is rather convoluted, so it may be a pain to make it work.
Comment: Thanks a lot for your response Jan. I've got it working Friday evening.. couldn't start the weekend without this .. i think something is missing on my side.. i commented out the language part in order for it to work.


Show/hide div based on selected option value in Javascript

Question: I wonder why it isn't working.
Here is my JS:
$("#cat-code").change(function(){
  var value = $("#cat-code option:selected").val();
  if (value == "10400000"){
    $("#div1").show();
    $("#div2").hide();
  }
});

Select Tag:
<select class="cat-code" id="cat-code" name="project_procurement_management_plan[items_attributes][0][category_id]">
  <option value="1">10400000</option>
  <option value="2">10401000</option>
</select>

Divs to show or hide:

hi

hello

Any workarounds will be appreciated. Thanks.
Comment: replace class with id in div tags.
Answer: It looks like your JS is reference to DOM objects with IDs, but your HTML has classes.
Try this JS instead:
$(".div1").show();
$(".div2").hide();

Answer: You've specifically set the values to 1 and 2, so that's probably what they are then:
$("#cat-code").change(function(){
  var value = this.value;
  if (value == "1"){
    $(".div1").show();
    $(".div2").hide();
  }
});

FIDDLE
The options text will only be used as the selects value if the option does not have a value, and to get the selected value all you need is this.value inside the handler for the select.
Comment: Hi thanks. Sorry im about to collapse just right now for not sleeping. I accidentally interchanged classes to ids and so on. Will accept this answer after 9 mins


What is "Young's modulus", and how does it relate to guitar?

Question: I've come across some posts that mention "Young's modulus" in relation to guitar.
Young's modulus is discussed on physics.SE (Young's Modulus and Vibrating String Harmonics), but I'm looking for a less technical explanation.
On this site, it's mentioned in a few posts in relation to guitar:

This answer to "What types of plastic and manufacturing techniques are used to make guitar picks?"
This answer to "vibrato on classical guitar is more of a "side to side" motion?"
This answer to "How does string gauge affect intonation?"
This answer to "Bridge intonation patterns on stringed instruments"
And this answer, also to "Bridge intonation patterns on stringed instruments"

In lay terms, what is Young's modulus, how does it relate to guitar, and does it similarly relate to other stringed instruments?
Comment: This question is answered in the last two paragraphs of https://music.stackexchange.com/questions/114451/bridge-intonation-patterns-on-stringed-instruments/114466#114466
Comment: The last sentence is important - it may well relate to fretless instruments, the players of which maybe don't even realise they compensate without even considering moduli!
Comment: The last sentence has some importance. It may have relevance to fretless instruments, the players thereof not even realising that they compensate for moduli while in mid-flow! We await, with bated breath, the findings of Jemenake!
Comment: It describes if you need a lot or a little force on the area(stress) to make stuff bend like rubberband(strain).
Comment: Well, it's an inherent property of all solid materials. So it does apply to fretless instruments too, but be prepared to do some interesting integrals if you want to actually calculate something with it.
Comment: @Aaron Can you clarify how that question doesn't answer this one? What would an ideal answer here have that that one doesn't?
Comment: @Richard I've voted to close this question as a duplicate; the other one does answer it. However, a person who has this question would not easily find the linked answer on their own: 1) the linked question is not obviously related, and 2) the relevant answer is lengthy and contains the information only as an addendum, not as its primary focus. I'm looking to see whether the community and mods consider this more valuable as a Q&A in its own right or as a duplicate pointing to the linked post.
Comment: Does this answer your question? [Bridge intonation patterns on stringed instruments](https://music.stackexchange.com/questions/114451/bridge-intonation-patterns-on-stringed-instruments)
Answer: Young's modulus is a parameter of given material describing relation between force and deformation.
The formula is E = σ/ε, where E is Young's modulus, σ = F/A is the tensile stress, or force F over the cross-sectional area A (e.g. string cross-section), and ε = (l - L0)/L0 is relative change of length. The units of E are Pa (pascals); one could visualize it as pressure occurring in the material in response to deformation. https://en.wikipedia.org/wiki/Young%27s_modulus https://en.wikipedia.org/wiki/Stress_(mechanics) https://en.wikipedia.org/wiki/Deformation_(physics)
Young's modulus of the string material is one of the parameters determining how strings are susceptible to intentional or unintentional bending, and how the pitch may vary due to string elongation due to vibration. E.g. listen to pitch change of long notes played on steel strings in the intro to this song:

Young's modulus also determines the relative longitudinal and transverse force exerted by the string on the bridge due to vibrations [Fletcher, Rossing, The Physics of Musical Instruments]. I presume this affects differences between classical (Nylon strings, Young's modulus of 2–4 GPa) and acoustic (steel strings, Young's modulus ~40 times larger) guitars, I however can't provide any details.
Young's modulus is an important parameter, but not the only one to consider. E.g. Nylon strings have much lower value than steel strings, but they have also lower yield and ultimate strength (45, 70 MPa) in comparison to e.g. piano wire (2000–3000 MPa https://en.wikipedia.org/wiki/Yield_(engineering)). As a result Nylon strings are typically made thicker and are tuned at lower tension (so they don't break), which counteracts some of the effect of large difference in Young's modulus. Thicker nylon strings also absorb energy of higher harmonics, resulting in more mellow sound.
Young's modulus determines speed of sound in the material. E.g. for an elongated rod (like a string) it is c² = E/ρ where c is the speed of sound and ρ is the density. (https://en.wikipedia.org/wiki/Speed_of_sound#One-dimensional_solids) I presume this must be an important factor when choosing materials to make an instrument, especially larger parts with resonances significant for the instrument sound.