Convert Canvas to ImageSource

Question: im attempting to convert a canvas to a image source for use as an OpacityMask, I want to save it into memory rather than save it as a file, i'm having trouble though. Below is my code, I think i'm going about it wrong!
Really, I need to get the image information as a Base64String, so somewhere between that I need to convert the RenderTargetBitmap!
public BitmapSource ExportToPng(Uri path, Canvas surface)
{
    BitmapEncoder encoder = new PngBitmapEncoder();
    System.IO.MemoryStream myStream = new System.IO.MemoryStream();

    // Save current canvas transform
    Transform transform = surface.LayoutTransform;
    // reset current transform (in case it is scaled or rotated)
    surface.LayoutTransform = null;

    // Get the size of canvas
    System.Windows.Size size = new System.Windows.Size(surface.ActualWidth, surface.ActualHeight);
    // Measure and arrange the surface
    // VERY IMPORTANT
    surface.Measure(size);
    surface.Arrange(new Rect(size));

    // Create a render bitmap and push the surface to it
    RenderTargetBitmap renderBitmap =
        new RenderTargetBitmap(
        (int)size.Width,
        (int)size.Height,
        96d,
        96d,
        PixelFormats.Pbgra32);
    renderBitmap.Render(surface);

    // push the rendered bitmap to it
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
    // save the data to the stream
    encoder.Save(myStream);

    // Restore previously saved layout
    surface.LayoutTransform = transform;

    var sr = new System.IO.StreamReader(myStream);
    var myStr = sr.ReadToEnd();
    var bytes = Convert.FromBase64String(myStr);

    // Save to memory
    /*Bitmap pg = new Bitmap("525, 350");
    Graphics gr = Graphics.FromImage(pg);

    gr.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(255, 255, 255, 255)), 0, 0, (float)size.Width, (float)size.Height);
    gr.DrawImage(System.Drawing.Bitmap.FromStream(myStream), 0, 0);*/

    return BitmapFromBase64(myStr);
}
public static BitmapSource BitmapFromBase64(string base64String)
{
    var bytes = Convert.FromBase64String(base64String);

    using (var stream = new System.IO.MemoryStream(bytes))
    {
        return BitmapFrame.Create(stream,
            BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    }
}

Edit:
Just found another possible way, however this creates a DrawingVisual, I need to convert that to a ImageBrush
C#
// Create a DrawingVisual that contains a rectangle.
        private DrawingVisual CreateDrawingVisualRectangle(List<Rectangle> rectangles)
        {
            DrawingVisual drawingVisual = new DrawingVisual();

            // Retrieve the DrawingContext in order to create new drawing content.
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            // Create a rectangle and draw it in the DrawingContext.
            foreach(Rectangle x in rectangles)
            {
                Rect rect = new Rect(new System.Windows.Point(x.X, x.Y), new System.Windows.Size(x.Width, x.Height));
                drawingContext.DrawRectangle(System.Windows.Media.Brushes.Black, (System.Windows.Media.Pen)null, rect);
            }

        // Persist the drawing content.
        drawingContext.Close();

        return drawingVisual;
    }

Comment: UIElement takes any Brush as OpacityMask. Why not use a VisualBrush? Canvas c = new Canvas();
element.OpacityMask = new VisualBrush( c );
Comment: Ah, didn't think I could use a VisualBrush there, thanks!
Comment: This makes EVERYTHING so much simplier, I thought I had to convert the canvas to some form of image, but being able to use it directly is MUCH better
Comment: Make that your answer please @SnowballTwo
Comment: Whilst your at it you should add that answer to this other similar question too:
http://stackoverflow.com/questions/34325221/use-canvas-to-mask-background
Answer: A UIElement takes any Brush as OpacityMask. You can simply create a VisualBrush from you Canvas, since the base class of every UIElement is SWM.Visual.
Canvas c = new Canvas();
element.OpacityMask = new VisualBrush( c );

Regards, Snowball

Convert Canvas to ImageSource


Compute Gas Volume Function

Question: Hey guys I'm completely lost on this python homework question the problem is Define a function compute_gas_volume that returns the volume of a gas given parameters pressure, temperature, and moles. Use the gas equation PV = nRT, where P is pressure in Pascals, V is volume in cubic meters, n is number of moles, R is the gas constant 8.3144621 ( J / (mol*K)), and T is temperature in Kelvin.
The starter code is
gas_const = 8.3144621
def compute_gas_volume((gas_pressure,,gas_temperature,gas_moles):

    gas_pressure = 100.0
    gas_moles = 1.0
    gas_temperature = 273.0
    gas_volume = 0.0
    gas_volume = compute_gas_volume(gas_pressure, gas_temperature, gas_moles)
print('Gas volume:', gas_volume, 'm^3')

can anyone help me with the question?
Comment: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/questions/how-to-ask).
Comment: Please see [this article](http://meta.programmers.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) for an explanation of how to ask homework questions.
Comment: You didn't even want to put in the effort to lowercase the first letter of the prompt, or format it? ಠ_ಠ
Answer: As the law is PV = nRT, volume can be simply computed as V= nRT/P, hence:
GAS_CONST = 8.3144621
def compute_gas_volume(gas_pressure, gas_temperature, gas_moles):
    return gas_moles * GAS_CONST * gas_temperature / gas_pressure

Answer: Rearrange it to equal V:
double ComputeGasVolume (double gasPressure, double gasTemperature, double gasMoles) {
   double gasVolume = ((gasMoles * GAS_CONST) * gasTemperature) / gasPressure;

   return gasVolume;
}

Answer: return(moles * gas_const * temperature / pressure)
This is the correct formula.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Compute Gas Volume Function


Question about solution spaces of linear homogeneous differential equations

Question: I'm re-reading a book on introduction to linear algebra, that (I think) I used to understand. The book doesn't define the solution space, just relates solving equations to it. I'm assuming;
A second order linear homogeneous differential equation has a solution,
f(x) = g(x) + h(x)
and there is a solution space associated with that equation, where
f = a.g + b.h, and g,h span the space
Do the set of vectors of the solution space correspond to the same differential equation but with different Initial conditions ?
If the vectors don't correspond to the same equation can you explain to me what the solution space is then?
Comment: Yes, they correspond to the same differential equation (with differents intitial conditions)
Answer: You are right. The two solutions correspond to different initial conditions. However two different conditions might correspond to the same solution. So care must be taken to pick suitable initial conditions for $f$ and $g$ (to be absolutely sure you need some existence and uniqueness theorem, that constrain how unregular your $a_i(t)$'s can be - in $a_0(t)x(t)+a_1(t)x'(t)+a_2(t)x''(t) = 0$).


How to make a 'unconfigured' and 'ready' RAID drive 'online'?

Question: I have 2 drives in RAID 1 configuration, as Ubuntu 16 boot drives. One of the drives failed and recovered by itself and I now have the following output:
root@server:/home/admin/megacli/Linux# megasasctl
a0       PERC H310 Adapter        encl:1 ldrv:1  batt:FAULT, module missing, pack missing, charge failed
a0d0       931GiB RAID 1   1x2  DEGRADED
unconfigured:  a0e*s0
a0e*s0      931GiB        ready
a0e*s1      931GiB  a0d0  online

root@server:/home/admin/megacli/Linux# megacli -pdgetmissing -aALL

    Adapter 0 - Missing Physical drives

    No.   Array   Row   Size Expected
    0     0       0     953344 MB

Exit Code: 0x00

What megacli commands do I need to enter to get the a0e*s0 back online like the other drive?
Answer: You can try to set the device "online" with
MegaCli –PDOnline -PhysDrv[XXX:XXX] -aN

Or maybe if needed set it as "unconfigured good" with
megacli -PDMakeGood -PhysDrv[XXX:XXX] -Force -aN


Formula for the number of numbers $\le n$ with same prime factors as $n$?

Question: Is there a more concise formula for this? I threw this one together,
$\sum_{j=1}^{n}(\lfloor\frac{n^{j}}{j}\rfloor-\lfloor\frac{n^{j}-1}{j}\rfloor)(\lfloor\frac{j^{n}}{n}\rfloor-\lfloor\frac{j^{n}-1}{n}\rfloor)=$ number of numbers $\le n$ with same prime factors as $n$.
I can show this by proving that the term in the left parenthesis is only $1$ or $0$ depending on whether or not $j|n^{j},$ which can only happen if the factors in prime factorization of $j$ are a subset of $n$'s. The function in the parenthesis on the right is $1$ or $0$ depending on whether or not $n|j^{n},$ which only occurs if $j$ is a multiple of $rad(n)$, the product of the distinct prime factors of $n$. So, the sum counts the number of numbers $j\le n$ whose prime factorization is a subset of $n$'s and is a multiple of $rad(n)$. This leaves only those with the same factors. I give this info on the sum because people always ask, but I really just need another version.
I'm looking for a different representation of this function than the one I have created above. I can't find a formula for this anywhere. Anybody got one?
Example of the function is, for $n=24$, the prime factors of $24$ are $2$ and $3$. There are $4$ numbers with these factors $\le n,$ which are $(6,12,18,24),$ so the function at $24=4.$ Sequence is A008479 in oeis, but no formula.
Comment: but yes, $\sum_{k=1}^n 1_{rad(k) = rad(n)} = \sum_{d | \frac{n}{rad(n)}} 1 = \sigma(\frac{n}{rad(n)})$ is clearly "Number of numbers <= n with same prime factors as n." i.e. https://oeis.org/A008479 , but is not $\sum_{k=1}^n 1_{\omega(k) = \omega(n)}$, since $rad$ and $\omega$ are not the same : $$rad(n) = \prod_{p | n} p$$ while $$\omega(n) = \sum_{p | n} 1$$
Comment: "I want to know what to equate it to instead of writing out what it equals".  I really can't tell what this sentence is supposed to mean.
Comment: @ErickWong I believe a more formal expression is needed for .
Comment: I don't think he considered $ \sum_{j=1}^n 1_{j | n^j} 1_{ n | j^n} $ but instead $\sum_{k=1}^n 1_{\omega(k) = \omega(n)}$  @YakovShklarov
Comment: @YakovShklarov Sure, but the formula in the question is already a formal expression.  Maybe it isn't equal to the desired quantity, but it's really hard to guess what OP is looking for.  That is, what property does the current formula have that is not desirable?  Or what property is desirable in an answer that the current formula lacks?
Comment: @user1952009 I don't see it that way. A008479(18) = 3 but $\sigma(18/rad(18)) = \sigma(18/6) = \sigma(3) = 2$.
Comment: @user1952009 See my comment to your answer.  The two are not equal.
Comment: It equals the sequence from oeis I give. I don't have a formula to equate it to. mine is the only one I know. My question was to find another form of this oeis function A008479 that is not my own.
Comment: last sentence in my question.
Comment: @EricWong Fair enough, I'll fix that,
Answer: Let $\omega(n)$ (OEIS A001221) represent the number of distinct prime factors of $n$. Then a (fairly) transparent expression for what you want is
$$\sum_{1 \leqslant k \leqslant n} [\omega(k) = \omega(n) = \omega(\gcd(k,n))],$$
where $[\cdot]$ is the Iverson bracket, equal to $1$ when the condition inside is satisfied and $0$ otherwise. So we're tallying up the $k$s which have precisely the same number of prime factors as $n$ and no extra ones. Note that $\operatorname{lcm}$ would work just as well: $\omega(\gcd(k,n))$  is the number of distinct prime factors shared by both $k$ and $n$; $\omega(\operatorname{lcm}(k,n))$ is the number of distinct primes present in either $k$ or $n$ or both.
It really is necessary to specify the second equality, otherwise you end up including terms like $15=5 \cdot 3$ for $n=24 = 2^3 \cdot 3$. Notice that $\omega(\operatorname{lcm}(15,24)) = 3 \ne 2$ and $\omega(\gcd(15,24)) = 1 \ne 2$.
Another (perhaps more clear) way is to simply write
$$\sum_{1 \leqslant k \leqslant n} [p | n \Leftrightarrow p | k, \text{ for all prime }p].$$
Comment: the same number of prime factors, or the exactly the same prime factors (as I find above) ?
Comment: I'm not sure what you're asking -- $k$ is the index variable. Yes, I found the number of $k$s with the exact same prime factors. I added a small note -- does that clarify things?
Comment: Ahh, I see now! Nope, $\omega$ retains the meaning I claimed for it, my proof holds.
Comment: @user1952009 There's no significant difference between having the same number of prime factors and having the same prime factors in this case.  The inequality $\omega(\gcd(k,n)) \ge \omega(n)$ forces $k$ to have at least the same prime factors as $n$, while $\omega(k) \le \omega(n)$ precludes $k$ from having any additional primes.
Comment: @ErickWong : you are saying that $1_{\omega(k) = \omega(n) = \omega(gcd(k,n))} = 1_{rad(k) = rad(n)}$ ?  yes it is obvious indeed, but very weirdly formulated in my opinion, I just understood what it meant right now :D
Comment: @e2theipi2026 You're welcome! Glad I could help. It was an interesting problem.
Comment: Edit on question was made. I meant rad(n), the "product" of distinct prime factors, but I said the "number" of distinct prime factors. I edited the question. Does this change your proof?
Comment: @Yakov Shklarov Thank you for the help and bearing the trouble. If I could accept all answers I would, this got crazy. Best I can do Is upvote everything.
Answer: (I prefer the notation $\displaystyle \sum_{j=1}^n 1_{j | n^j} 1_{ n | j^n} $, and using that for integers $\lfloor \frac{a}{b}\rfloor-\lfloor \frac{a-1}{b}\rfloor= 1_{b|a}$, and $rad(n) = \prod_{p | n} p$)
we get $$1_{ a | b^a} = 1_{ rad(a) | b}  = 1_{ rad(a) | rad(b)}$$  thus
$$1_{j | n^j} 1_{  n | j^n} = 1_{ rad(j) | rad(n)}1_{ rad(n) | rad(j)} = 1_{ rad(j)= rad(n)}$$
and $rad(j)= rad(n),\ j \le n$ iff $j = d \ rad(n)$ with $rad(d) | rad(n)$ i.e. iff $d | n^d$
 hence $$\displaystyle \sum_{j=1}^n 1_{ j | n^j} 1_{  n | j^n}  = \sum_{j=1}^n 1_{ rad(j) = rad(n)} = \sum_{d=1}^{n/rad(n)} 1_{rad(d)|rad(n)} = \sum_{d=1}^{n/rad(n)} 1_{d | n^d}$$
and I'm not sure there is much simpler anymore, since this $\sum_{d=1}^{n/rad(n)} 1_{rad(d)|rad(n)}$ seems to depend on the precise prime factors of $n$, say if $p | n$, it depends on the maximum power of $p$ that is $\le \frac{n}{rad(n)}$, and hence on the other prime factors of $n$
Comment: @e2theipi2026 :   I don't know, as usual with your questions, I didn't understand what you expected as result. do you have a proof that the result isn't $\frac{n}{rad(n)}$?
Comment: I don't buy it: $\sigma(24/rad(24)) = \sigma(24/6) = \sigma(4) = 3 \ne 4$; it also fails for $n=18$.
Comment: @user1952009 The problem with $\sigma(n/\text{rad}(n))$ is that it only counts the values dividing $n$ rather than all the values $\le n$.  For instance $2\cdot 3^2$ has the same prime factors as $n = 2^3 \cdot 3$ and is $\le n$, but it doesn't divide $n$ and falls out of the above count.
Comment: I like your expression $\sum_{j=1}^n 1_{rad(j)=rad(n)}$, it's a tad more concise than mine and doesn't rely on as much trickery (though there is still some trickery: maybe someone could find an even cleaner expression?) But how did you make the leap to the next sum?
Comment: @e2theipi2026  I edited to say that I'm not sure there is a much simpler formulation
Comment: @e2theipi2026 Note that the summand can now be rewritten as the single term $1_{d\mid n^d}$, which cuts the length of the summand in your original expression in half and also reduces the number of terms in the sum.
Comment: @ErickWong That's a cool result. But it seems scandalously inefficient to raise $n$ to the power of $d$, when it would suffice to raise it to the power of the highest prime multiplicity in $d$.
Comment: The question was clear. I'm looking for a different form of the given function than the one I have. "as usual"? I've only seen you twice including now.
Comment: Looks good enough. Thank you for the help and bearing the trouble. If I could accept all answers I would, this got crazy. Best I can do Is upvote everything.
Comment: @ErickWong Thanks. That's great!
Comment: @user1952009 Outstanding!


How to load an entity using the uuid?

Question: I have created a custom resource which extends the EntityResource class. This way I can use all build in functionality that Drupal core provides on the default entity resource, but I can still add some extra checks. This works perfectly fine.
I defined my canonical route in my resource as /api/my-endpoint/{node}. In this way, I can fetch and patch nodes by the node ID. After careful consideration, I want to implement /api/my-endpoint/{node_uuid} or even /api/my-endpoint/{node_custom_field} to fetch (and patch) a node by UUID.
Of course, Drupal doesn't know this param and cannot load the corresponding node object, which results in fatal errors.
How can make I this work?
I tried to implement a custom RoutingParamConverter class, but I didn't got it to work.
Answer: As long as you have the uuid of an entity you can use Drupal's entity storage interface to load it given that property. It should be as simple as using the loadByProperties method.
$node_loaded_by_uuid = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['uuid' => $your_uuid]);
$node_loaded_by_uuid = reset($node_loaded_by_uuid);

UPDATE: milkovsky is correct. loadByProperties returns an array. If you want the actual node object at the top of it you will have to use the reset function.
Comment: You will get an array back. A `reset(...)` operation should be done in addiiton: `$node_loaded_by_uuid = reset($node_loaded_by_uuid)`.
Comment: @milkovsky thank you. I updated the answer to reflect this.
Comment: See my answer for something simpler.
Answer: You can use EntityRepositoryInterface::loadEntityByUuid():
$entity = \Drupal::service('entity.repository')->loadEntityByUuid('node', $uuid);

Comment: The internals of the `loadEntityByUuid` function does exactly what the other answer is doing, but with a couple extra calls. See `loadEntityByUuid` in EntityRepository.php
Comment: This is a brilliant answer. I have a hook_node_presave() and I need the Node ID but only have the UUID.
Working on Drupal 9.5 and will test for Drupal 10.x after the migration.

`$entity = \Drupal::service('entity.repository')->loadEntityByUuid('node', 'b6bca440-f4d9-41d0-86c6-d913c00b9e78')->id();`

Everything I need is there!

How to load an entity using the uuid?


DBFS : How to get Last access time of DBFS file in Datarbricks

Question: Is it possible to get the time when file was opened last time as like ls -ltu list all the files, showing and sorting by access time in Unix by using of dbutils. This we required to get the stat about ADLS file in Databricks note.
Answer: Unfortunately, you cannot use ls -ltu option while using Databricks Utilities (DBUtils).

Usage: dbuitls.fs.ls The sequence returned by the ls command contains the following attributes:

Use the Hadoop filesystem API to get the last access time for DBFS filesytem in Azure Databricks.
This code uses the Hadoop filesystem's listStatus method to sort the DBFS files based on the modification time.
import org.apache.hadoop.fs._
val path = new Path("/mnt/abc")
val fs = path.getFileSystem(spark.sessionState.newHadoopConf)
val inodes = fs.listStatus(path).sortBy(_.getModificationTime)
inodes.filter(_.getModificationTime > 0).map(t => (t.getPath, t.getModificationTime, t.getLen)).foreach(println)

Example1: stat about ADLS file in Databricks notebook

Example2: stat about DBFS file in Databricks notebook


jQuery keypress get first word

Question: In jQuery I get the value using following code:
$('#input_id').keypress(function(){
  var content= $(this).val(); alert(content);
});

In this case I type 'a' it alerts blank and I type 'ab' it alerts 'a'. Is any idea for when I type 'a' it should alert 'a' and when I type 'ab' it should alert 'ab'?
Answer: You need to use on("keyup" or on("input" since keypress is fired before the value is added to the field. You also use alert which blocks all further processing

$('#input_id0').on("keypress",function() {
  var content = $(this).val();
  console.log(content);
});
$('#input_id1').on("keyup",function() {
  var content = $(this).val();
  console.log(content);
});
$('#input_id2').on("input", function() {
  var content = $(this).val();
  console.log(content);
});

<input id="input_id0" placeholder="keypress" />

<input id="input_id1" placeholder="keyup" />

<input id="input_id2" placeholder="input" />

Answer: You can use keyup instead of keypress function:

$(document).ready(function() {
  $('#input_id').keyup(function(){
   var content= $(this).val(); alert(content);
  });
});
a

<input type='text' id='input_id'>
Answer: That's because you're working with keypress event. Instead, you should use keyup to achieve your requirement.

$('#input_id').keyup(function() {
  var content = $(this).val();
  alert(content);
});

<input id="input_id">

jQuery keypress get first word


Survival analysis with large populations (upscaling sample to population)

Question: Taking the data available from the survival() package, we can develop a survival curve and 95% CI, assuming an underlining weibull distibution.
library(survival)

data(lung)

head(lung)

#create a Surv object
s <- with(lung,Surv(time,status))

#plot weibull survival curves, per sex,
sWei <- survreg(s ~ as.factor(sex), dist='weibull', data=lung)

#
probs <- seq(0.001,0.999,0.001)
pred <- predict(sWei,newdata=list(sex=1),type="uquantile",p=probs,se.fit=TRUE)
val <- cbind(pred$fit,pred$fit-1.96*pred$se.fit,pred$fit+1.96*pred$se.fit)
val <- exp(val)    # convert from log scale to original scale

xlim = range(0,1000)
ylim = range(0,1)
#----------------------------------------------------------------------------------
plot(0.00001, pch=".", col='white', xlim=xlim, ylim=ylim, xlab="", ylab="")
lines(val[,1],probs,col="black",lty=1, lwd = 2)
lines(val[,2],probs,col="black",lty=2, lwd = 1)
lines(val[,3],probs,col="black",lty=2, lwd = 1)

(Hypothetically) We were then provided with weighting factors of each observation, so that we could scale the sample we have to be representative of a population.
lung$weigthsa <- with(lung, ifelse(time < 400, 1000,
                                  ifelse(time < 7000, 500, 300)))

We can continue to create a new model using the same methodolgy and plot
#plot weibull survival curves, per sex,
sWei <- survreg(s ~ as.factor(sex), weights = weigthsa, dist='weibull', data=lung)

#
pred <- predict(sWei,newdata=list(sex=1),type="uquantile",p=probs,se.fit=TRUE)
val <- cbind(pred$fit,pred$fit-1.96*pred$se.fit,pred$fit+1.96*pred$se.fit)
val <- exp(val)    # convert from log scale to original scale

#----------------------------------------------------------------------------------

lines(val[,1],probs,col="red",lty=1, lwd = 2)
lines(val[,2],probs,col="red",lty=2, lwd = 1)
lines(val[,3],probs,col="red",lty=2, lwd = 1)

#----------------------------------------------------------------------------------

So my question is, are we simply allowed to do this?, given that we see that the width of the CI's for the second model become very small.
Do we violate any assumptions of survival analysis when upscaling the model to a larger population?
I ask so, because I similiar question was asked on this link
Where the answer was given

As with any statistical test that uses a null hypothesis, the p-value
    for the phtest is dependent on the sample size. These tests were not
    developed for such large datasets. In population-based survival
    analyses violations of PH assumptions are universal, just as linearity
    assumptions are.

But i have found no other supporting literature
Answer: Without even trying to figure out what you have done, the answer is "No, what you've done is wrong". Survival analysis with survey data is extremely complicated.  None of the large scale survey data that have proper weights are collected at sufficiently high frequency to support survival analysis -- at best, you can figure out that the event happened some time in the prior year if the data are longitudinal and are collected annually. You don't always know the timing of the life events very well, etc. So many assumptions of the strict "got cancer -- got on therapy -- complied with treatment -- was in clinic under constant observation -- died within this many days" analyses are violated.
The supporting literature, unfortunately, comes literally from two people -- Jerry Lawless and Christian Boudreau, both of University of Waterloo, Canada. A good intro reading would be Event History Analysis and Longitudinal Surveys chapter by Lawless in Chambers and Skinner (2003).
Comment: Thanks for the tip. I have since found this article [link](http://onlinelibrary.wiley.com/doi/10.1002/cjs.5550340202/abstract).From what i understand, if the sampling design (of the study or database) is ignoreable, than minimal is gained from by weighting the data as the estimating function is asymptotically unbiased.
Comment: Yeah... right... show me that design.


Neo4J search greater than on Index

Question: I have a Neo4J database with a large number of datasets (~15M), where I want to perform a greater than search on one of its properties. I have the corresponding property indexed. The property is a float value.
When I do an exact match like MATCH (i:Label) WHERE i.property = $value RETURN count(i) I get the result within a very short time. But when I do the same search with greater than, i.e. MATCH (i:Label) WHERE i.property > $value RETURN count(i) it just takes forever. What is the correct way to do this in Cypher?
Edit: Execution plan:
+--------------------------------------------+
| No data returned, and nothing was changed. |
+--------------------------------------------+
74 ms

Compiler CYPHER 2.2

Planner COST

EagerAggregation
  |
  +Filter
    |
    +NodeByLabelScan

+------------------+---------------+-------------+------------------------------+
|         Operator | EstimatedRows | Identifiers |                        Other |
+------------------+---------------+-------------+------------------------------+
| EagerAggregation |          2064 |    count(r) |                              |
|           Filter |       4260557 |           r | r.date > Subtract(Divide(    |
|                  |               |             | TimestampFunction(),{        |
|                  |               |             | AUTOINT0}),Literal(86400))   |
|  NodeByLabelScan |      14201858 |           r |                     :Request |
+------------------+---------------+-------------+------------------------------+

Total database accesses: ?

Comment: Please show us execution plan of the query - http://neo4j.com/docs/stable/how-do-i-profile-a-query.html
Answer: Unfortunately Neo4j doesn't use it's indexes for inequalities in 2.2.x.  In the upcoming 2.3.x this should be supported.
Comment: I was expecting something like that :( Is there any information on when 2.3.x is supposed to be released?
Comment: And is this feature already implemented in the Milestone release?
Comment: It's planned for 2.3.0-M03 which should hopefully be out in the near future.  Feel free to test it when it comes out, but remember that milestone releases don't guarantee an upgrade path for your database when the next milestone/release candidate comes out.
Answer: Another approach is to create additional/aggregation nodes for that property and searching thru those nodes.
Example
Let say the property is a value from 0 - 100.
Create following nodes
 * 0to30
 * 31to60
 * 61to100
Create relationship from you nodes to this 'aggregate' nodes.
Than searching thru those nodes
MATCH (l:Label)-[i:IN]->(a:0to30)
RETURN l
Comment: Thanks, that has been a very great input. Sometimes I'm just too blind to see the obvious

Neo4J search greater than on Index


Weibull distribution

Question: I need to find a distribution that fail regularity condition.Maybe weibull distribution can be but I did not find why, please help me.
Comment: The easiest one to see a violation of immediately is 3. Look at what happens with a normal whose variance is a function of its mean (i.e $\sigma^{2} = \mu^{2}$)
Comment: What made you think the Weibull might be an example?
Answer: A classical example for 2. is given by the uniform distribution $U(0,\theta)$, which has density $1/\theta$ if $0\leq x \leq\theta$. So, the support depends on the parameter.
This also results in an MLE, viz. $\max_i(X_i)$, that violates 5., as the likelihood is 0 to the left of the MLE and $1/\theta^n$ to the right, hence the first derivative does not have slope zero at the maximum.
Comment: I fear this may go a bit beyond the 'hints and guidance' requested for answering homework/self study questions - http://stats.stackexchange.com/tags/self-study/info . (Something to consider for future answers at least.)
Comment: I know uniform distribution that fail for regularity condition .But I need find another distribution will you know distribution that depends on parameter like uniform distribution or can I find distribution that fisher information is negative? Also this is not a homework question. I learnt uniform distrubition in class and I wonder can I find another distribution that fail. @ChristophHanck
Comment: OK, it would have been useful to clarify that in advance. Check Pareto for another example.
Comment: Thank you, which one ıs failing for pareto ? I could not find. @ChristophHanck
Comment: can you help me please I checked Fisher information that is positive.
Comment: It is another example where the support depends on a parameter. I am not aware of a distribution with negative Fisher information.

Weibull distribution


Cannot temporarily disable unknown-pragmas warning in GCC

Question: I cannot make the method to temporarily disable warnings in GCC (see How to disable GCC warnings for a few lines of code) work, at least not for the "unknown-pragmas" warning.
Compiling this code ...
#pragma comment(user,"This should depend on the command line options")

#pragma GCC diagnostic warning "-Wunknown-pragmas"
#pragma comment(user,"This should cause a warning")

#pragma GCC diagnostic error "-Wunknown-pragmas"
#pragma comment(user,"This should cause an error")

#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma comment(user,"This should be ignored")

... produces either no warning/error (except that the linker complais about a missing main), or when using -Wall or just -Wunknown-pragmas it produces one warning for each of the comment pragmas.
The behaviour that I would have expected is that each comment should have caused exactly what the comment says.
I think I can back my expectation with the documentation:

At the moment only warnings (normally controlled by '-W...') can be controlled, and not all of them. Use -fdiagnostics-show-option to determine which diagnostics are controllable and which option controls them.

The warnings I get show as
warning: ignoring #pragma comment  [-Wunknown-pragmas]

and as the part in brackets tells us,

this diagnostic is controllable
and the option -Wunknown-pragmas controls it

Hence my code should work.
So what am I doing wrong?

version info:
$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609

Comment: Possible duplicate of [Suppress -Wunknown-pragmas warning in GCC](https://stackoverflow.com/questions/12842306/suppress-wunknown-pragmas-warning-in-gcc)
Answer: This is a long-standing missing feature in the GCC C++ front end:

C++ preprocessor ignores #pragma GCC diagnostic

Warnings generated by preprocessing cannot be controlled using programs in g++.  Unlike the C front end, pragmas are processed only after the preprocessing phase in the C++ front end.


Outbound VPN issue with Mac OSX Viscosity Client for OpenVPN and pfSense

Question: I'm having an issue using the Viscosity OpenVPN client on a network behind a pfSense firewall. I'm unable to connect to my office vpn from this particular network, however the connection works just fine from other networks. Below is a log from Viscosity showing the error with our IP Address redacted. Any help would be appreciated.
<code>Jan 03 12:21:38: NOTE: OpenVPN 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables
Jan 03 12:21:38: Re-using SSL/TLS context
Jan 03 12:21:38: LZO compression initialized
Jan 03 12:21:38: UDPv4 link local: [undef]
Jan 03 12:21:38: UDPv4 link remote: redacted:1196
Jan 03 12:22:38: TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)
Jan 03 12:22:38: TLS Error: TLS handshake failed
Jan 03 12:22:38: SIGUSR1[soft,tls-error] received, process restarting
</code>
Answer: Hard to tell definitively without seeing the server log too, but usually logs along those lines means the client can't communicate with the server on UDP 1196. Without knowing more about the setup as a whole it's impossible to pinpoint a cause, but in general the following are the most likely:

if you have egress filtering employed on your pfSense, you could be blocking outbound UDP 1196. Packet capture on WAN to ensure it's leaving, if it is, you've ruled out pfSense at least.
something upstream from you (DSL modem, similar), or on your ISP's network, is blocking the traffic. Packet capture on the server would tell you whether the traffic is getting there, my guess is it isn't.
something server-side is blocking the traffic, such as source IP restrictions on the server itself, a firewall, or something else potentially applying such restrictions.


domain access module in drupal

Question: I try to set up drupal multisite by using domain access module.we two sites sscsoftweb.com and kumba.sscsoftweb.com.Both are drupal sites which host in shared environment.i install domain access module in sscsoftweb.com. kumba.sscsoftweb.com is subdomain as per installation instruction i remove text followed after /public_html
Then i create a new domain record and create two page called page1 and page2.page1 published in sscsoftweb.com similarly page2 publish in kumba.sscsoftweb.com.i set the homepage for kumba.sscsoftweb.com is node/2.
the problem is when i hit kumba.sscsoftweb.com it automatically redirect to sscsoftweb.com homepage not to node/2. is there any thing i miss.kindly suggest me how to fix this issue.
thanks..
Answer: I played with the domain access module and I remember I had to set the cookie domain in settings.php to ".example.com", in your case ".sscsoftweb.com".
But I'm not sure this will fix your problem.

domain access module in drupal


Simple proof of stream of ones in Coq

Question: Taking code from CPDT, I'd like to prove a property for the easy stream ones, which always return 1.
CoFixpoint ones : Stream Z := Cons 1 ones.

Also from CPDT, I use this function to retrieve a list from the stream:
Fixpoint approx A (s:Stream A) (n:nat) : list A :=
    match n with
    | O => nil
    | S p => match s with
        | Cons h t => h :: approx A t p
        end
    end.

To get a list of five 1, e.g.:
Eval compute in approx Z ones 5.
= 1 :: 1 :: 1 :: 1 :: 1 :: nil
  : list Z

How do I prove, that for all n given to approx, the list will contain only 1? I'm not even sure how to formulate this. Should I use a help function like nth n list for lists, that return element number n from list? And that
forall (n length : nat), nth n1 (approx Z ones length) = 1

(Or maybe use Zeq instead of =.)
Am I heading the right direction?
Answer: I think having a more general view than the point-wise nth view of lists will be easier to deal with. Here is how I would go (the proof is 0 automation to be sure you see everything) :
Inductive all_ones : list Z -> Prop :=
  | nil_is_ones : all_ones nil (* nil is only made of ones *)
  (* if l is only made of ones, 1 :: l is too *)
  | cons_is_ones : forall l, all_ones l -> all_ones (cons 1%Z l)
  (* and these are the only option to build a list only made of ones
.

CoFixpoint ones : Stream Z := Cons 1%Z ones.

Fixpoint approx A (s:Stream A) (n:nat) : list A :=
    match n with
    | O => nil
    | S p => match s with
        | Cons h t => h :: approx A t p
        end
    end.

Lemma approx_to_ones : forall n, all_ones (approx _ ones n).
Proof.
induction n as [ | n hi]; simpl in *.
- now constructor.
- constructor.
  now apply hi.
Qed.

If you prefer a more functional definition of all_ones, here are some equivalent definitions:
Fixpoint fix_all_ones (l: list Z) : Prop := match l with
  | nil => True
  | 1%Z :: tl => fix_all_ones tl
  | _ => False
end.

Fixpoint fix_bool_all_ones (l: list Z) : bool := match l with
  | nil => true
  | 1%Z :: tl => fix_bool_all_ones tl
  | _ => false
end.

Lemma equiv1 : forall l, all_ones l <-> fix_all_ones l.
Proof.
induction l as [ | hd tl hi]; split; intros h; simpl in *.
- now idtac.
- now constructor.
- destruct hd; simpl in *.
  + now inversion h; subst; clear h.
  + inversion h; subst; clear h.
    now apply hi.
  + now inversion h; subst; clear h.
- destruct hd; simpl in *.
  + now case h.
  + destruct p; simpl in *.
    * now case h.
    * now case h.
    * constructor; now apply hi.
  + now case h.
Qed.

Lemma equiv2 : forall l, fix_all_ones l <-> fix_bool_all_ones l = true.
Proof.
induction l as [ | hd tl hi]; split; intros h; simpl in *.
- reflexivity.
- now idtac.
- destruct hd; simpl in *.
  + now case h.
  + destruct p; simpl in *.
    * now case h.
    * now case h.
    * now apply hi.
  + now case h.
- destruct hd; simpl in *.
  + discriminate h.
  + destruct p; simpl in *.
    * now case h.
    * now case h.
    * now apply hi.
  + discriminate h.
Qed.

Best,
V

Simple proof of stream of ones in Coq


Questions regarding the following initial value problem

Question: I want to solve the initial value problem:
\begin{cases}
\dfrac{dx}{dt} + 2x(t) = f(t), t > 0 \\
x(0) = x_0  \\
\end{cases}
I start off by finding the integrating factor, which is $ e^{2t}$. Multiplying both sides with the integrating factor and using the chain rule gives me following:
$ \Big(x(t) * e^{2t} \Big)' = f(t) * e^{2t}  $
Now i set $t = \tau$ and integrate both sides, i get
$$ \int_0^t\Big(x(\tau) * e^{2\tau} \Big)' \ d\tau  =  \int_0^t\Big(f(\tau) * e^{2\tau} \Big) \ d\tau$$
From this i get that
$$ \left [x(\tau)  e^{2\tau} \right]_{0}^{t}  = \int_0^t\Big(f(\tau) * e^{2\tau} \Big) \ d\tau$$
and then from this we get that
$$ x(t) = e^{-2t}x_0 +\int_0^t\Big(f(\tau) * e^{-2(t-\tau)} \Big) \ d\tau $$ which is the solution.
I have to following questions:

Why do we set $ t = \tau $?

Also, why do i get that $$ \left [x(\tau)  e^{2\tau} \right]_{0}^{t} = \int_0^t\Big(f(\tau) * e^{2\tau} \Big) \ d\tau $$
The way i always learned to solve IVP with integrating factor is that
$$ \int\Big(x(t) * e^{2t} \Big)' = x(t) * e^{2t}  $$ since the integral and the derivative cancel each other out, so why don't is the following wrong?
$$ x(t) * e^{2t}  = \int f(t) * e^{2t}$$
Hopefully someone will understand what i mean. Thanks in advance!
Comment: Just a note, I personally find $*$ very confusing as it's the symbol for convolution.
Answer: Setting $t=\tau$ distinguishes the limits of integration from the variable of integration, which is a dummy variable.
The final indefinite integral would introduce a constant of integration and doesn't allow you to compute $x(t)$ without finding that constant. Using the definite integrals, the constant doesn't appear, it cancels out, and you have an explicit formula for $x(t)$.
Comment: https://mathworld.wolfram.com/DummyVariable.html may be helpful.
Comment: Thanks a lot for the response. I still have a hard time understanding why we set $ t=\tau $. I have been searching for material that explains it in greater detail, but i can't seem to find any. Is this method called something? Do you maybe know where i can find more on this topic? Once again, thanks!
Comment: I have one last question. I hope it is fine. In the IVP where \begin{cases}
\dfrac{dx}{dt} + \dfrac{1}{t}x(t) = e^{t^2} t > 0 \\
x(1) = 1  \\
\end{cases}, i get that the integral and derivative cancel each other out, and i don't have to pay attention to the limits of the integration. Why is this the case here, but not in the first problem? Is it because in this case we can actually determine the integral of the right side? Thanks a lot!


How to loop code until it works in Python?

Question: I have a long code, here is a small excerpt from it. You constantly need to find elements, insert data and click buttons. Sometimes something fails to load and errors pop up. Is it possible to have Python try these commands until it succeeds? I can't use
time.sleep()

with a long delay as it will greatly increase the execution time and even that doesn't always help(
start = driver.find_element(By.CSS_SELECTOR, "SELECTOR")
start.click()
time.sleep(1)

start2 = driver.find_element(By.CSS_SELECTOR, "SELECTOR")
start2.click()
time.sleep(1)

Comment: why don't use `try except ` statements?
Comment: Welcome to Stack Overflow. "Sometimes something fails to load and errors pop up. Is it possible to have Python try these commands until it succeeds?" Well, first off, *why should it ever succeed* if you simply keep trying in the same way? "...and even that doesn't always help" - well, in that case you first need to **think about why it doesn't**, and understand the underlying problem.
Comment: What error are you getting?
Comment: I thought there would be another option, because you will have to use try except everywhere
Comment: That said, you have already tagged the question with `loops`, and the obvious answer is to write a loop; I don't see where you're stuck? I assume you have heard of both `for` and `while` loops; which seems more appropriate here? Then, think about: **how can the program know** whether the click succeeded or not?
Comment: Please also read [ask] and [mre], and make sure the problem is clear and evident.
Comment: Python can't always find the element and throws the error "Message: no such element"
Comment: Before clicking, the program looks for the element, so it understands if the element was found successfully
Comment: And the "time.sleep()" command does not always help, because the page load speed is always different
Answer: If you use a method that waits for an element to be clickable first, then you can set a default timeout, and then use that, as shown below with this partial code example that uses WebDriverWait:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

def wait_for_element_clickable(
    driver, selector, by="css selector", timeout=10
):
    try:
        return WebDriverWait(driver, timeout).until(
            EC.element_to_be_clickable((by, selector))
        )
    except Exception:
        raise Exception(
            "Element {%s} was not visible/clickable after %s seconds!"
            % (selector, timeout)
        )

# ...

element = wait_for_element_clickable(driver, "button#id")
element.click()


Prove that a linear transformation is invertible if and only if its associated matrix is invertible.

Question: Let $V$ be a finite dimensional vector space, $\beta$ an ordered basis of $V$, $T$ a linear operator on $V$ and $A$ the associated matrix of $T$ in the basis $\beta$. I have to prove that $T$ is invertible if and only if $A$ is invertible.
I was thinking that I only need to consider $T^{-1}$ and its associated matrix $A^{-1}$, but I don't know if it's that easy because this problem is supposed to be not too easy. Maybe there's something I'm not considereing, which makes the problem a not too easy problem, but I don't see it. Do you?
Thanks in advance.
Comment: If $\dim_K V=n$, this follows from the fact that the mapping $T\longmapsto A_T$ is an isomorphism from the $K$-algebra $L(V)$ onto $M_n(K)$.
Answer: The problem in considering $A^{-1}$ is that, at that point, you haven't yet established the fact that $A$ is invertible. You have assumed that $T$ is invertible, so you can take the associated matrix $B$ of $T^{-1}$, but you have to prove that $AB = BA = I$.
Now the actual proof depends a bit on what you already know. It would be nice if you already knew that the associated matrix of the composition of two linear maps is the product of the associated matrices. Then it follows from $T \circ T^{-1} = T^{-1} \circ T = I$ that $AB = BA = I$. (The other direction of the if-and-only-if goes similarly).


Using a separate but related dataset for feature extraction (transfer learning)

Question: I have two datasets of MRI images: a larger one of Altzheimer's paitents (AD), which is about 3 times the size of a smaller dataset of brain tumor paitents (BT). My aim is to make use of the AD data with some form of transfer learning to help with the classification of brain tumor images.

Question: Would it be viable to train a feature extractor unsupervised (likely a stacked
  convolutional autoencoder) using only the AD data, and then use the
  encoder as the first few layers of a new network which has
  fully-connected layers trained on the BT data?

My thinking is that it may be possible to have the autoencoder 'learn' the general features of the brain from the AD data, and then use this as a basis for a BT network. I have not seen this done before (which maybe for a good reason).
Perhaps there is some issue with overfitting/general transferability between the datasets. Would fine-tuning the encoder when the fully-connected layers are trained possibly prevent this?
Answer: Yes, this is a totally viable solution and probably it would work.
However in my experience, even CNNs trained on very generic data (e.g. imagenet) that has nothing to do with MRIs can be used as pretrained models and achieve very good enough results. The reason, probably, is that the features they learn to extract in their initial layers (i.e. lines, circles, corners, etc.) are general purpose and can be used for virtually any task.
This has two benefits: 1) you don't have to pretrain the model on your own; you can download weights online and 2) the models are trained on a dataset which most likely is an order of magnitude (or two) larger than the one you're trying to use (which means that it is trained better).
Comment: Thanks for your answer. Using ImageNet (or something similar) has been at the back of my mind given the number of times people have used it in the past for similar applications. You are right about the dataset size difference too, so I will for sure look into this.


Can't register any component in Delphi 11

Question: I have a problem with Delphi 11. I can't register any of my components, I get the attached error when i right click on the package and select Install
<code>unit MyNewComponent;

interface

uses
 System.Classes,
 FMX.Objects;

type
  TMyComp = class(TShape)
  end;

procedure Register;

implementation
procedure Register;
begin
  RegisterComponents('BRTesting', [TMyComp]);
end;
end.
</code>

There is allready registered a bug at embarcadero (https://quality.embarcadero.com/browse/RSP-36334) but I was hoping that I could get help here, because I fear that embarcadero is not going to fix this in the near future. And maybe they have changed something in the way we now have to register own components?
Comment: No problems creating a package, adding a FM component using the wizards and installing here. Only differences compared to what you posted are more units in the uses (`System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Objects;`) and the type definition includes the sections (private, protected etc).  Neither of those differences would lead to the error you are seeing.
Comment: Does the error also appear for components based on a VCL component?
Comment: I don't know if it also appear on VCL components.
But when I uninstall my Devart UniDac package it works in my test app :(
Answer: I have same problem and solution was uninstall Devart Unidac, restart delphi, install new components and finay
Answer: We were also faced with this problem. It actually stems from the DevArt components. But it is not necessary to uninstall the components. It is enough to deactivate them and restart Delphi.
After the installation, the DevArt components can be reactivated without any problems.
Comment: We have already worked on this problem, please write to our support for a quick solution.


(Agglomerative) Hierarchical Clustering: Which linkage for the detection of outliers?

Question: In (agglomerative) hierarchical clustering (and clustering in general), linkages are measures of "closeness" between pairs of clusters.
The single linkage $\mathcal{L}_{1,2}^{\min}$ is the smallest value over all $\Delta(X_1, X_2)$.
The complete linkage $\mathcal{L}_{1,2}^{\max}$ is the largest value over all $\Delta(X_1, X_2)$.
The average linkage $\mathcal{L}_{1,2}^{\text{mean}}$ is the average over all distances $\Delta(X_1, X_2)$.
The centroid linkage $\mathcal{L}_{1,2}^{\text{cent}}$ is the Euclidean distance between the cluster means of the two clusters.
We can clearly see the outliers as "singletons" in a dendrogram:

(From https://www.statisticshowto.com/hierarchical-clustering/)
Which of these linkages is best for the detection of outliers?
Comment: Your question is very incomplete. It misses the description, an idea of how a hierarchical clustering is usable to detect outliers. This is not obvious if it can detect at all and if yes - how.
Comment: @ttnphns What you've just described is what I guess would be included in an answer, no? The question seems very clear and simple to me, so I don't understand what's wrong with it.
Comment: Clustering is a method of producing unsupervised classes. Not of detection of outliers. Your question should therefore describe a path or a trick how clustering could be used to detect outliers. But the Q lacks such a description. So the Q cannot be answered.
Comment: @ttnphns we can clearly see the outliers as singletons in a dendrogram https://www.statisticshowto.com/wp-content/uploads/2016/11/dendrogram.png from https://www.statisticshowto.com/hierarchical-clustering/
Comment: But this is what you ought to _discuss in your Q_ first. In particular, you would enter your definition of an "outlier" (for there are many possible definitions). Then go to consider why singletons are or can be seen (and when?) as instances of such otliers.
Comment: @ttnphns Ok, I have made the edits.
Comment: You equate "outlier" with "singleton". But singleton needs clusters to be outlined. On your pic, F is the singleton in view of ABCDE. C, on the other hand, could be regarded as a singleton towards AB (if A and B joined together not after C joined them). So what singletons are "outliers" for you?
Answer: Let's say an object is a singleton at high level in complete linkage, and say that there are otherwise bigger clusters. This means only that the maximum distances between the object and the other clusters are large; the singleton object can still be close to quite a number of objects of the clusters, and is therefore not necessarily an outlier.
A high level singleton of single linkage is separated from all clusters, its minimum distance to all clusters is large, so its distance to all other objects is large. In this sense it is well qualified to be called outlier. The only issue is that some people would say that there could also be small groups of outliers, which will not normally show up as singletons in any algorithm, but in single linkage an object may not be singleton anymore if it is close to one single other object.
Average linkage is a compromise between these two; it can have the problem that complete linkage has potentially missing outliers, but it is less likely. I don't have much experience with the centroid method, but I'd expect it to behave similarly to average linkage in this respect.
So single linkage is probably most suitable, at least if an outlier in your definition is an object that is far away from all the others.
Answer: Upon trying to work with Lewian's answer above, I found it to be lacking in clarity, so I've attempted to use his answer to write my own version below.
A linkage is a measure of closeness between pairs of clusters. It depends on the distance between the observations in the clusters.
Let's assume that an outlier is defined as an object that is "far" from all the others.
In the case of a complete linkage, we are using the largest value of the distance function over the observations of the two clusters. Therefore, if the other cluster is large (with observations spread), then there might be some observations that are much closer than the observations used for the maximum distance calculation; however, they would not be taken into account when using the complete linkage. Therefore, the singleton would not necessarily be an outlier.
In the case of a single linkage, we are using the smallest value of the distance function over the observations of the two clusters. Therefore, a singleton's minimum distance to all clusters is comparatively (to the complete linkage) large, so its distance to all other observations is comparatively (to the complete linkage) large. Therefore, if even by using the smallest value we find that some observations are classified as singletons, then chances are that they actually are indeed outliers.
The average linkage and the centroid linkage seem to be between the two extremes of the complete linkage and the single linkage. Therefore, I would say that the single linkage is most suitable for detecting outliers.
Comment: My answer wasn't precise because your question wasn't precise in a way. What's your definition of an outlier? What exactly to do depends on that. I have no issue with your "reformulation" of my answer though.


como fazer um select em php para um campo de busca por datas

Question: Estou com um problema para fazer um Select, preciso de ajuda, estou programando em php, para fazer buscas em um banco de dados preciso fazer um campo de busca por datas.
Já consegui fazer o campo de busca por data especifica, mas preciso fazer a busca com intervalo entre as datas. (exemplo: busca de 20/05/2020 a 31/05/2020).
o select que fiz para procurar por uma data foi esse:
case 'pesquisareduroamdata':
        global $linhadataa;
        global $rsdataa;

        $dataa = new dataa();

        $data = $_POST['data'];

        $dataa->pesquisareduroamdata("SELECT * FROM usuarios WHERE data LIKE '%$data%' && ssid = 'EDUROAM' ");
        $linhadataa = $dataa->Linha;
        $rsdataa = $dataa->Result;

se alguém souber me ajude.
Comment: Em seu banco de dados o campo `data` é do tipo string?
Answer: Considerando o seu exemplo, há muitos problemas no seu código além da consulta. Mas focando na sua pergunta e considerando que a coluna data citada é do tipo DATE,
há duas maneiras simples de fazer isso. A primeira é utilizando, no caso do MySql, a cláusula BETWEEN, desse modo:
"SELECT * FROM usuarios WHERE data `BETWEEN` '$data1' AND '$data2' "

E o segundo modo é comparando valores:
"SELECT * FROM usuarios WHERE data >= '$data1' AND data <= '$data2' "

Em caso de a coluna data ser to tipo texto, embora não seja o recomendado, ainda assim dá pra realizar a consulta utilizando a função STR_TO_DATE. Detalhes nesse link


$\mathbb Z[\frac{2+i}{5}]\cap \mathbb Q =\mathbb Z$

Question: As it says in the title I want to show that $\mathbb Z[\frac{2+i}{5}]\cap \mathbb Q =\mathbb Z$.
Set $\omega=\frac{2+i}{5}$. $\mathbb Z[\omega]$ is the smallest ring that contains $\mathbb Z$ and $\omega$. Therefore,
\begin{equation}
  \mathbb Z[\omega] = \{a_0+a_1 \omega+\cdots+a_k \omega^k\mid a_i\in \mathbb
  Z,k\in \mathbb N\}
\end{equation}
Let, then, $q\in\mathbb Z[\frac{2+i}{5}]\cap \mathbb Q$. Since $q\in\mathbb Q$ we can write $q=\frac{m}{n}$, where $m,n$ are relatively prime integers and $m\neq 0$. Now, since $q\in\mathbb Z[\frac{2+i}{5}]$ we have that
\begin{equation}
  q=a_0+a_1 \omega+\cdots+a_k \omega^k
\end{equation}
for some $a_i\in \mathbb Z$. Then,
\begin{align}
  &\frac{m}{n}=a_0+a_1 \frac{2+i}{5}+\cdots+a_k \left(\frac{2+i}{5}\right)^k \\
  \Longrightarrow \ &5^km=5^kna_0+5^{k-1}na_1(2+i)+\cdots+a_kn(2+i)^k
\end{align}
Hence, $n\mid 5^km$ and since $\gcd(n,m)=1$ we have that $n|5^k$.
Thus, every rational number in $\mathbb Z[\omega]$ is of the form $\frac{m}{5^l}$ where $m\in\mathbb Z$, $l$ is a positive integer and when $l\geq 1$ it holds that $5\nmid m$. It suffice then to show that it always hold that $l=0$. I am stuck here. I would very much appreciate some help!
Answer: Hint: Look at the equation $5^km = n(5^ka_0+5^{k-1}a_1(2+i)+ \cdots + a_k(2+i)^k)$ as an equation between Gaussian integers.
Note that $2+i$ is a prime in the ring of Gaussian integers arising from the factorization of the integer prime $5$, namely $(2+i)(2-i)=5$.
You already noticed that $n$ is a power of $5$. In particular, if $m/n$ is not an integer, you may assume that $m$ is not divisible by $5$.
Hence, viewing it as a Gaussian integer, it should not be divisible by $2+i$ or $2-i$.
Can you see the contradiction from here?


Format disk with diskpart if not formatted

Question: I'm trying to write a script to create and format a partition in Windows Server 2008R2.
Now, when disk 1 is selected, I need to format it, only if it is not formatted already. This is what I have now:
Run: diskpart /s script.txt
Content of script.txt
select disk 1
clean
create partition primary
format fs=ntfs unit=65536 quick
active
assign letter=D

Any help?
Comment: You should be using Powershell as opposed to using DOS commands, Powershell allows for greater flexibility and will allow you to evaluate if a disk is not formatted then perform an action on it if the statement equals true. I assume you already know this though as you added a "Powershell" tag into your post. In any case, this command should get you started "Get-Command *disk*"
Comment: You are right, the problem its that in Windows 2008R2 there are no Storage Cmdlets in Windows PowerShell.
Comment: Those diskpart replacements are only for v4 powershell and above.  But don't worry, we can still check drive formatted status via Get-WmiObject cmdlet.  Also look into the `Win32_Volume Format` method to avoid diskpart.
Answer: This works for me.
foreach ($disk in get-wmiobject Win32_DiskDrive -Filter "Partitions = 0"){
   $disk.DeviceID
   $disk.Index
   "select disk "+$disk.Index+"`r clean`r create partition primary`r format fs=ntfs unit=65536 quick`r active`r assign letter=D" | diskpart
}

In this case, i get the disk with NO partitions, and then i create a D drive with all available space
Answer: I did this a while back using here strings to format the complete diskpart commands.  It's a bit goofy looking but it worked at the time when we were trying to automate this quickly for a high number of luns on multi node clusters.  the WMI method is definitely cleaner looking.


Confusing simplification of summation

Question: WolframAlpha simplifies
$$\sum_{z=n+1}^{a-3} {\frac{1}{2} (a - z - 2) (a - z - 1) (a - z)}$$
to
$$\frac{1}{8} (a-n-3) (a-n) (a^2-a (2 n+3)+n^2+3 n+2)$$
which is equivalent to
$$\frac{1}{8} (a-n-3) (a-n-2) (a-n-1) (a-n)=\frac{1}{8}\cdot\frac{(a-n)!}{(a-n-4)!}$$
but I am drawing a blank on how it was first simplified. Any insight would be greatly appreciated!
Answer: Putting $r=a-z$ helps simplify the summation.
$$\begin{align}
&\quad \sum_{z=n+1}^{a-3} {\frac{1}{2} (a - z - 2) (a - z - 1) (a - z)}\\
&=\sum_{r=3}^{a-n-1}\frac 12 (r-2)(r-1)r\\
&=3\sum_{r=3}^{a-n-1}\binom r3\\
&=3\binom {a-n}4\\
&=\frac 18 (a-n)(a-n-1)(a-n-2)(a-n-3)\qquad\blacksquare
\end{align}$$
Answer: Since $a$ is a constant and the summation is over $z$, let us expand
$$A_z={\frac{1}{2} (a - z - 2) (a - z - 1) (a - z)}$$ $$A_z=\left(\frac{a^3}{2}-\frac{3 a^2}{2}+a\right)+\left(-\frac{3 a^2}{2}+3 a-1\right)
   z+\frac{3}{2} (a-1) z^2-\frac{z^3}{2}$$ So $$\sum_{z=n+1}^{a-3}A_z=\left(\frac{a^3}{2}-\frac{3 a^2}{2}+a\right)\sum_{z=n+1}^{a-3} 1+\left(-\frac{3 a^2}{2}+3 a-1\right)\sum_{z=n+1}^{a-3} z+\frac{3}{2} (a-1)\sum_{z=n+1}^{a-3} z^2-$$ $$\frac 12 \sum_{z=n+1}^{a-3} z^3$$ Now, use $$\sum_{z=n+1}^{a-3}z^k=\sum_{z=0}^{a-3}z^k-\sum_{z=0}^{n}z^k$$ I am sure that you can take it from here.
If your are concerned by the simplification of the term $a^2-a (2 n+3)+n^2+3 n+2$, compute the roots and show that they are $n+1$ and $n+2$ which make $$a^2-a (2 n+3)+n^2+3 n+2=(a-n-1)(a-n-2)$$

Confusing simplification of summation


If $m(A) \to 0,$ then $\int_A f\,dx \to 0$

Question:
Let $f$ be an integrable non-negative function defined on a measurable set $E.$
  Then, for $A \subset E,$ if $m(A) \to 0,$ then $$\int_A f\,dx \to 0$$

Very intuitively (cause I'm thinkng of a bounded function defined on a closed domain) I beleive i understand what I'm being asked to prove: If the area of the domain is smaller and smaller, then the integral wil be smaller and smaller, until the interval is just a point, and so the function would also be a point, so the area underneath would be zero.
But formally, I don't know how to use and reason with the hipothesis $m(A) \to 0.$ In the other excercises that I'm supposed to solve, I should use some convergence thoerems available. I have looked at the proofs about some of them, like the monotone convergence theorem, Fatou's Lemma, Lebesgue Convergence theorem, and none of them use explicitly something like the domain is tending to zero. They are using properties about pointwise convergence, or seem to be dealing mainly with images of the functions.
Convergence in measure uses something like: $m\{x : |f(x) -f_n(x)| \ge \epsilon\} < \epsilon .$
Definition: A sequence $<f_n>$ of measurable functions is said to converge to $f$ in measure if, given $\epsilon > 0,$ there is an $N$ such that for all $n \ge N$ we have $m\{x : |f(x) -f_n(x)| \ge \epsilon\} < \epsilon .$
Then, Fatou's Lemma or Monotone Convergence theorem are valid for convergence in measure (it is a proposition, but I have not proved it), and so maybe that is a way to involve a the measure in the domain converging to zero and and integral converging to a funcion $f = 0.$
More overly Im talking to much because it is not clear to me how to relate $m(A) \to 0$ with an integral converging to zero.
I would appreciate some help...
Comment: What does $m(A)\to 0$ mean?
Comment: @JohnGriffin I think the point of this is to prove $\lim_{ m(A) \to 0 } \int_A f = 0$.
Answer: Hint: This is clear if $f$ is also bounded. But given $\epsilon>0,$ there exists a bounded $g\in L^1(E)$ such that $\int_E |f-g| < \epsilon.$
Answer: Say $(A_n)_n \subseteq E$ satisfy $m(A_n) \downarrow 0$. Suppose for some $\epsilon > 0$, $\int_{A_n} f > \epsilon$ for all large $n$. Take a subsequence $(n_k)_k$ so that $\sum_k m(A_{n_k}) < \infty$. Then if $A = \limsup_k A_{n_k}$, $\int_A f > \epsilon$ but $m(A) = 0$ by Borel Cantelli. This is a contradiction.
The motivation for the proof above comes from the fact that $v(A) := \int_A f$ is a measure which is absolutely continuous with respect to $m$. It is a general fact that for measures $v_1,v_2$, if $v_1 \ll v_2$, then for all $\epsilon > 0$ there is a $\delta > 0$ so that if $v_2(A) < \delta$,
then $v_1(A) < \epsilon$, which is your problem statement.
Comment: great thanks! I am not voting the answer with green because I have not seen Borel  Cantelly theorem in the course.
Answer: By Lebesgue Dominated Convergence Theorem we have
\begin{align*}
\int|f|1_{|f|\geq n}dx\rightarrow\int|f|1_{|f|=\infty}dx=0
\end{align*}
since $m(\{|f|=\infty\})=0$ and the convention that $\infty\cdot 0=0$. Or we can consider the sequence $\left(|f|1_{|f|\leq n}\right)$ and apply Monotone Convergence Theorem to get the convergence to $\displaystyle\int|f|dx$, and then we do the subtraction. Given $\epsilon>0$, we have some $n_{0}\in{\bf{N}}$ such that
\begin{align*}
\int|f|1_{|f|\geq n_{0}}dx<\epsilon.
\end{align*}
For any measurable set $A$ with $m(A)<\epsilon n_{0}^{-1}$ then we have
\begin{align*}
\int|f|1_{A}dx&=\int|f|1_{A\cap\{|f|\geq n_{0}\}}dx+\int|f|1_{A\cap\{|f|<n_{0}\}}dx\\
&<\epsilon+\int|f|1_{A\cap\{|f|<n_{0}\}}dx\\
&\leq\epsilon+n_{0}\int 1_{A}dx\\
&=\epsilon+n_{0}m(A)\\
&<2\epsilon.
\end{align*}


How can i find the height of soft-keyboard in a LibGDX application

Question: I'm developing an Android game with LibGDX. And I need to find the height of the soft-keyboard the user is using, as I want to display some objects right above the keyboard.
I have read this thread:
how can i get soft keyboard height on android?
But the comment suggests that it doesn't work, and it also seems to be for using with Android SDK. I'm not sure. Does anyone know a way that will definitely work?
Comment: Hello, its been a year, but i think i found a solution! check out this post: http://stackoverflow.com/questions/21467006/how-to-push-up-the-screen-when-soft-keybord-is-displayed/29981733#29981733
Answer: If your problem is that your textfields are obscured then I suggest using
void Gdx.input.getTextInput(Input.TextInputListener listener,
                java.lang.String title,
                java.lang.String text)
instead because that will generate a native modal text input dialog that moves up and down with the keyboard. I have tried to get the height of the keyboard as well but so far I haven't managed.
See answers for this thread as well:
How do libgdx detect keyboard presence
Answer: Hopefully someone will find this answer helpful:
There is a workout to detect the exact height of the soft-keyboard which involve the Launcher Activity to send screen dimension to the game when a screen resize event occurs.
First, set a layout listener on the ViewTreeObserver of the rootView of your LauncherActivity:
public class AndroidLauncher extends AndroidApplication {
//...
    public void setListenerToRootView() {
        final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);
    }

    private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect visibleDisplayFrame = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(visibleDisplayFrame);
            game.screenResize(visibleDisplayFrame.width(), visibleDisplayFrame.height());
        }
    };
//...
}

If you try to get the height of the root view, it will not work as most of the games are fullscreen.
Don't forget to add and remove the listener on appropriate occurrences:
@Override
protected void onCreate (Bundle savedInstanceState) {
    //...
    setListenerToRootView();
}

@Override
protected void onDestroy () {
    super.onDestroy();
    removeListenerToRootView();
}

public void removeListenerToRootView() {
    final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
    activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(keyboardLayoutListener);
}

Next, declare the screenResize method inside the Game Class which will receive the dimensions and send it to the current screen:
public class YourGame extends Game {
//...
public ScreenBase currentScreen;
//...
    public void screenResize(float width, float height) {
        if(currentScreen != null)
            currentScreen.onScreenResize(width, height);
    }
//...
}

Every screen that involves a change must implement the onScreenResize method. Introduce an Abstract Base Class of screen that has an abstract method onScreenResize. The currentScreen variable must be set in the constructor:
public abstract class ScreenBase implements Screen {
//...

public ScreenBase(YourGame game) {
//...
    this.game = game;
    this.game.currentScreen = this;
//....
}

public abstract void onScreenResize(float width, float height);

Implement these in whichever screen you want:
public class LoginScreen extends ScreenBase {
//...
    @Override
    public void onScreenResize(final float width, final float height) {
        if(Gdx.graphics.getHeight() > height) {
            Gdx.app.log("LoginScreen", "Height of keyboard: " + (Gdx.graphics.getHeight() - height));
        }
    }
}


Piano: quaver triplets in RH v dotted quaver and semiquaver in LH

Question: Towards the end of the first movement of Beethoven's Piano Sonata Op 27 No 2 (Moonlight) the right hand is playing triplet quavers while the left has a dotted quaver and semiquaver.
If we are naively mathematical then the right hand should move to the third of its quavers (2/3 of the beat) slightly ahead of the left moving to its semiquaver (3/4 beat).
This is beyond my amateur abilities so I play the left hand's semiquaver a little early in step with the right hand's last quaver.
I just experimented with it in MuseScore and it is precisely mathematical and it sounds quite weird.
Of course, I have listened to recordings (e.g. Barenboim 1984). They certainly don't sound like MuseScore but I wouldn't dare say that they sound like me either.
Do we know what Beethoven intended?  Is there a commonly agreed interpretation?
Comment: As a mathematician, you may be interested in improving your polyrhythms by taking Adam Neely's 7:11 challenge. https://www.youtube.com/watch?v=U9CgR2Y6XO4
Comment: It is strange that you ask about the left hand at the end since this problem actually appears in the right hand early on in the movement. The left hand at the end is a repetition of the motiv that was presented in the right hand in the beginning. In my opinion it is important to play the sixteenth note after the triplet without being overly concerned about the exact math.
Comment: I'll work on Beethoven first.  One case in which I have learned to ignore the mathematical meaning of a term is irrational time signatures.  I don't go looking for music in pi / 4 time.  https://en.m.wikipedia.org/wiki/Time_signature#Irrational_meters
Comment: Similar 4-vs.-3 tactics are used in Schubert's Impromptu in C Minor, Op. 90, No. 1, as well as Elgar's Pomp and Circumstance March No. 2 in A Minor. (Of course, it's a lot easier to have dotted 8th-16th against triplets when separate instruments play them a la the Elgar march.)
Comment: @LarsPeterSchultz One example seemed sufficient and that one was easy to describe.  Also, for some reason. I find it easier the other way around.
Comment: @Dekkadeci I have not tried that yet.  I have all of the Beethoven sonatas and some Mozart.  That will keep me busy for plenty of time. When I want something completely different, I go to Satie.
Comment: @badjohn I think it is important to focus on the melodic line where the sixteenth note works as an upbeat to the next bar. You can play the melodic line a couple of times without playing the triplets in order to get the hang of the melody. Then have the melody in mind when you play all notes.
Comment: @LarsPeterSchultz Thanks.  I have been practising ambidexterity (not just for the piano) but I guess that I have some work to do.
Comment: @LarsPeterSchultz I have done some more practising and listening.  You mention that the same problem occurs the other way around towards the beginning.  It sounds just as weird in Musescore but I think that I manage it better.  So, maybe I can do better since I seem to do so in the earlier case.
Comment: There are many very useful answers here.  It is very hard to pick one as best and mark it as the accepted answer.
Comment: @badjohn play it as a melodic line as I suggested, don't be overly concerned about the exact math of the sixteenth note but certainly play it after the triplet and as an upbeat to the next bar. The Musescore probably sounds mechanical while you can play in a musical way.
Answer: The normal interpretation is to play the dotted rhythm distinctly from the triplets. I've never heard a recognized pianist merge it into the triplets.
Anecdotally, I want to say it is often shortened in performance. Some celebrated performers are closer to a double dot - I'll add some examples when I track them down.
There are two issues at play here. One is the combination of dotted notation with triplets. In former times this was used conventionally rather than putting a quarter note and an eighth note under a triplet. In my opinion, it doesn't apply here. The other issue is how accurately rhythms in general should be observed. The literalist view is obvious. Another view, reading between the lines, is that Beethoven was expressing a contrast of rhythm and the degree is up to the player. A comment by Claudio Arrau springs to mind, from Dean Elder's interview book "Pianists at Play":

Do you think of rhythmic figures that often are not played precisely enough?
Sometimes figures are played too precisely. Rhythm should be very
  elastic, the notation of rhythm being only approximate. Otherwise,
  rhythm becomes motoric, which I hate. In such a rhythm as the fourth
  Variation of the Schumann Symphonic Etudes, a variation built mostly
  on rhythm - you should of course be very precise. But, on the other
  hand, there are cases in romantic music where the slight distortion of
  the rhythm will help the expression.

I wouldn't expect it to sound acceptable in MuseScore without tinkering, as the software won't be phrasing and balancing the parts as a human would.
Answer: People do strange things to the 'Moonlight'.  My feeling is that the unifying element is the constant triplets which, while a degree of flexibility is always allowable, should not have their flow BROKEN.  Many performers disagree!  This version, the first that Google threw up for me, hesitates after each of the dotted quaver-semiquaver pairs.

This keeps the triplets rather more steady

This one chooses a brighter tempo and lets the triplets flow almost un-interrupted

And don't forget Benjamin Zander's opinion that we generally play it half-speed. View this from 23'00"

The one thing they all agree on is that the semiquaver falls after the triplet.  No, you can't cop out of this!  (It really isn't that hard to play.)
Comment: One-and-two-and-a-three-and-a-four-and-ardi-
Comment: As I mentioned in a comment above, I find that I cope better in the earlier section when the dotted quaver / semiquaver is in the right hand.  So, I just need my left hand to catch up with my right.  It is a little disappointing since I have worked hard at ambidexterity in life in general (e.g. I can use chopsticks in either hand) but I have some way to go with my left hand when playing the piano.  I won't be performing Ravel's piano concerto for the left hand any time soon.
Answer: Don't count too much. Make music! let it flow:
The  quietest it would sound if you give the 16th note half the value of a triplet eighth. But of course that's not mathematically correct. The exact note value would be 4/12 resp. 3/12t:
The triplets each with 4/12
The dotted eighths with 9/12
The 16th with 3/12
So mathematically correct would be, if the 16th note is not played halfway between the last triplet eighth and the new bar, but very soon after the triplet quaver, said to be one quarter of the triplet value.
Try to see the sixteenth note in a different way: as a "sound movement to the next note"!
Don't play it like a computer program, even some of these softwares have a humanizer that makes the "mathematical correct" played music groove.
Comment: Thanks.  Despite being more of a mathematician than a musician, I resist imposing too much maths into music.  The precise way that MuseScore played it just made me curious.  An example of my resistance to bringing maths into music is saying "quaver" rather than "eighth note".
Comment: @badjohn to my American ear, your use of "quaver" rather than "eighth note" sounds more like the normal thing that anyone would say who also says "maths" rather than "math."
Comment: @badjohn Oh dear, now I feel particularly slow and boring.  I do note that the US use of mathematical note names seems to be derived from German practice, and Albrecht seems to be German speaker.  Albrecht, does German have a short name for "mathematics," and, if so, is it plural or singular in form?
Comment: Yes, teachers and students say "Mathe": die Mathe is sing., fem. and stands for *Mathematik.*
Answer: Other answers have made a good case for the common interpretation.  I have always thought that the ideal should approximate two independent voices played by different people.  That can be particularly difficult for a player of "amateur abilities," but I encourage you not to give up.  I despaired of ever being able to achieve that, but with some practice (less than I had thought), I was able to do it, at least to my own satisfaction.
But the reason for this answer is to address this part of your question, about Beethoven's intentions:

Do we know what Beethoven intended?

If you look at the first surviving page of the manuscript, at the end of the third line of music, in the right hand, you will see the triplet written directly below the dotted rhythm, and the head of the second note of the dotted figure is placed distinctly after that of the last note of the triplet.  This seems like very strong evidence that the dotted rhythm should not be assimilated to the triplet.
There's a case to be made that this layout is not significant, especially if you see how quarter notes and half notes are not generally aligned with the first note of the corresponding triplet figure, but in the other place where the dotted figure appears in the upper staff with a written-out triplet (as opposed to the slash abbreviation), on page 5, the spacing is the same.
On the other hand, when the figure appears in the bass, at the end of the movement, the 16th notes do appear to be aligned with the third triplet notes.  In two of the four cases, though, the triplet is on the other staff, with a bit of crossing out and correcting/editing in one of those spots.  In the two cases where the triplet is on the lower staff, the stems and beams are colliding with one another, so everything is a bit crowded, and the alignment might have suffered because of that.  I would be inclined to conclude that the alignment on the last page is less likely to reflect Beethoven's intentions.


Quartz intermittently triggering the job multiple times when using JobStoreTX

Question: I'm using java quartz(2.3.1) and I have a setup where I'm using postgres as the job store and I have 3-4 machines all running the scheduler (vertical scaling). I want the rds to act as a source of truth and if I have a job with the schedule of repeat every 1 hour, I want it to run on any one of the machines. I don't care which one it runs on as long as it is one machine triggered in that hour.
I noticed that this works really well most of the time but I have recently had a trigger which runs once ever hour and about once every two days I see two of my machines getting triggered. I have noticed that my isClustered property is false which I have now set to true, but I'm not sure how this would help since if this was the problem, this issue would be happening a 100% of the time rather than rarely. Could anyone tell me what I should be looking into to actually fix this issue?
Comment: This might help https://stackoverflow.com/questions/58513804/does-quartz-support-execute-once-on-multiple-node/58534137#58534137 .Also be sure to assign separate instanceId for all the clustered nodes.
Comment: Because clustering work on instance group and instance I'd.If you use the same instance id ,quartz scheduler will overwrite the entry made in the database from other instance with same I'd.Therefore, to overcome such scenerio using different or auto generated instance id is advisable.Note, quartz does clustering using database
Comment: Why is a separate instance ID something that's required?
Answer: org.quartz.jobStore.isClustered = true
ensures proper database row locks are applied to the trigger before picking it, if that property was false both instances can pick up one trigger(race condition) before one could change status of that trigger.
http://www.quartz-scheduler.org/documentation/quartz-1.8.6/configuration/ConfigJDBCJobStoreClustering.html


OCaml syntax error in type declaration

Question: I'm new to OCaml and I have no clue why this is giving me a syntax error:
type ('nonterminal, 'terminal) pe =
| Empty
| T of t
| N of n
| Seq of list
| Choose of list
| Star of e
| Not of e;;

type ('nonterminal, 'terminal) pe_tree =
| Is_empty
| Leaf of t
| Node of (n,tree)
| Sequence of list
| Repeat of list
| Is_not of e;;

All it's saying is that there's a syntax error on line 14 characters 0-1 (which is where | Sequence of list is) and I can't figure out why!
Answer: type ('nonterminal, 'terminal) pe_tree =
  | Is_empty
  | Leaf of t
  | Node of (n * tree)
  | Sequence of list
  | Repeat of list
  | Is_not of e;;

You use * to define product types, as in 'a * 'b. Although probably not too important now, you should know that Node of 'a * 'b and Node of ('a * 'b) are different. You can think of them as a variant type with two parameters, and the other a variant type with one parameter (a tuple), respectively.
There are a few other things,

you need to define what Sequence and Repeat are a list of.
'nonterminal and 'terminal aren't used; unless they are for phantom types, which i doubt it, they probably should be used in part of the signature.
Comment: Thank you! I'm confused though, because I have another type declaration before it (which I just added in to my original question) and it's compiling just fine :/
Comment: there has to be more then just those type definitions; `t`, `e` are not defined, along with the other things I've mentioned. Neither of those definitions should compile as you've displayed them.
Comment: Ohh ok, I see. It's obvious now haha I don't know why I was having so much trouble - thank you!

OCaml syntax error in type declaration


If $g(\cdot,\cdot)$ is linear in the second argument, is it necessarily $g(x,u) = f(x)u$ for some $f$?

Question: Let $g: \Omega \times \mathbb{R} \to \mathbb{R}$ be a function which is linear in the second argument. Does it always follow that $g(x,u) = f(x)u$ for some $f:\Omega \to \mathbb{R}$?
$\Omega$ here is a bounded domain.
Comment: $f(x)+au+b$ is also linear in $u$.
Answer: Yes. Set $f(x) := g(x,1)$ and use linearity.
Answer: Write $f(x)=g(x,1)$, $g(x,u)=g(x,u.1)=g(x,1)u$
Answer: Yes. For a given $x\in\Omega$, consider $g_x:\mathbb{R}\to\mathbb{R}$. This is a linear map, hence there is some $f_x\in\mathbb{R}$ such that $g_x\left(u\right)=f_xu$ for all $u\in\mathbb{R}$. Then define $f\left(x\right)=f_x$, and you get the desired function.
(I assume that linear means $g\left(x,au+bu'\right)=ag\left(x,u\right)+bg\left(x,u'\right)$).


How do I avoid caching a redirect response from a form?

Question: I have a Drupal 8 form used by authenticated users which sometimes needs to redirect based on the presence of absence of something in session. I don't want the redirect to be cached.
My form is displayed directly with a route. i.e., the route has a _form default pointing to the form class.
My buildForm method starts like this:
public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['#cache'] = ['max-age' => 0];

    if (some value not in session) {
        $response = new TrustedRedirectResponse($some_url);
        $response->setMaxAge(0);
        throw new EnforcedResponseException($response);
    }

    // build the form.
}

I have not been able to avoid the redirect response being cached. It redirects as expected if the session variable does not exist but continues to redirect next time when the session variable does exist.
Users are authenticated so it is the dynamic page cache. drush cr or uninstalling the dynamic page cache "fixes" the problem.
Comment: See related: https://drupal.stackexchange.com/questions/278698/disabling-page-cache-for-redirect-response/278703
Answer: I just discovered that it's related to the TrustedRedirectResponse.
A standard Symfony\Component\HttpFoundation\RedirectResponse is not cached.
Comment: Yes, and you can simply return the response `return new RedirectResponse($some_url);`, the Form API knows what to do with it.
Comment: Thanks @4k4 I also now see that if I really need a TrustedRedirectResponse for an external url then it's $response->getCacheableMetadata()->setCacheMaxAge(0) to disable caching, not $response->setMaxAge(0) as I was trying. That only sets an http header.
Comment: Redirect response also gets cached with Internal dynamic page cache module.


Markov chain for in-flow and out-flow of mass?

Question: I think the problem that I'm dealing with has some connections to Markov chain, second-order recurrence equation, and flow of mass. I was struggling to know with which keywords I should search for further references.
Suppose there is countable infinite number of toilets, of which position is denoted by $s = \{ -L, ..-1, 0,1,...,\infty \}$. At each period in discrete time, the probability of moving to one-step forward is given by $p^{up}$ and to one-step behind is $p_{down}$. When customers reach $s=-L$, they stay there forever. Lastly, at each period, customers die exogenously with some probability $D$, regardless of their position (including $-L$). When customers die, new customers replace them coming at $s=0$.
Given this structure, suppose at the first period, $M \in R^{+}$ of customers come into the chain of toilets at $s=0$.
With this simplified example, I would like to know the followings:
(1) when time goes to infinity, I speculate that the stationary fraction of customers at each position with resect to the total number of customers $M$ exits and that it equals to the stationary distribution from a corresponding Markov chain multiplied by $M$.
(2) I could write the flow changes of mass at each position. Given the stationarity condition that the flow change is $0$, I could get second-order relation condition except for $s = -L$ and $s=0$. However, the initial condition seems a bit odd (it doesn't start from the lowest index) and I was wondering if I can get even a closed-form solution of the stationary fractions.
Answer: Firstly, let us assume that the customers don't die and that we have only one customer. Then, you have a semi-infinite absorbing Markov random walk. That is, your customer walks through the states $$-L, -L+1, \dots, 0, 1, \dots$$ From the properties of the Markov walk we know that this process is recurrent - that means that the probability of returning to the starting state is equal to $1$ - only if $p_{up}=p_{down}$. So for any $p_{down} \leq p_{up}$ the customer will end up in the absorbing state $-L$ with probability one.
Now, let us reintroduce dying. However, instead of thinking that our customer dies and a new customer at $s=0$ shows up, we can think of our consumer teleporting from its state to $s=0$. That means that regardless of where the customer is, there is a probability $D$ that they will start over. Now, even when $p_{up} > p_{down}$, at any time the customer can land in $-L$ in a finite number of steps. More formally, at any time there is a probability $p$ that the consumer lands in $-L$ in exactly $L+1$ steps equal to:
$$p = d\cdot (p_{down})^L$$
That means that after a sufficient number of restarts, any customer will eventually end up in $-L$. So, answering directly to the first question, after a sufficient finite number of turns, all $M$ customers will be in $-L$ regardless of the values $p_{down}, p_{up}, D$, assuming that $p_{down}$ and $D$ are positive.
Now, to comment on the second part, you can generate the transition matrix of the process. Assuming $p_{up}+p_{down}+D = 1$, the row corresponding to a state $i$ in the matrix $M$ will have three nonzero elements:
$$M_{i, i+1} = p_{up}$$
$$M_{i, i-1} = p_{down}$$
$$M_{i, 0} = D$$
The above won't be true only when we consider the row corresponding to $-L$, as it will have only one nonzero entry equal to $1$, and for states $-1$ and $1$, where you need to add the respective probability values. Let $v$ be an infinite vector having only one nonzero entry equal to $1$ on the position corresponding to the state $0$. Then, the probability that a customer is in the state $i$ after exactly $n$ turns is equal to:
$$(M^n\cdot v)_i$$
This allows you to calculate mass out- and in-flows, as the change in mass in the state $i$ between turn $n$ and $n+1$ is equal to
$$((M^{n+1} - M^{n})\cdot v)_i$$
While the above matrices are infinite, you can easily approximate them with sufficiently long finite random walk transition matrices.
Comment: Thank you very much for the detailed answer. I really appreciate it. Maybe I wasn't clear at the dying part. I assume that customers at $s= -L$ also dies. This part is being super tricky to me indeed.


In ajax success message through php comes in unwanted text

Question: I want an alert message if Item is successfully inserted into cart. But the result show unwanted charterers why? like this
In last shows my desire message.
Here is the code:
 Ajax:
function myFunctionguest(val) {
  var itemid = val;
  $.ajax({
        type: "POST",
        data: {temp: itemid},
        url: "listhelpguest.php",
        dataType:"text",
        success:function(data)
        {
            window.alert(data);
        }
    });
}

PHP:
<?php
  include 'dbconfig.php';
  echo $guestuserid = $_COOKIE["guestuser"];
  $itmid = $_POST['temp'];
  $sq ="SELECT * from item where item_id ='$itmid'";
  $re =mysqli_query($conn, $sq);
  $ro =mysqli_fetch_assoc($re);
  $name = $ro["name"];
  $sp = $ro["selling_price"];
  $sql = "SELECT * FROM cart WHERE item_id = '$itmid' and gid ='$guestuserid'";
  $res1 = mysqli_query($conn,$sql);
  $rows = mysqli_num_rows($res1);
  if ($rows >=1) {
        echo "Item Already in Your Cart";
    }
  else {
    $sql = "INSERT INTO cart (email,gid, item_id, qty, itotprice) VALUES ('$guestuserid','$guestuserid', '$itmid', '1', '$sp')";
    if (mysqli_query($conn, $sql)) {
         echo $name . " Successfully Added to Cart";
    }
    else {
          echo "Try Again";
    }
  }
?>

Comment: Open your Devtools and go to Network tab, see what response the server is sending you when you make this request. Probably something weird about the `$name` variable, or maybe the encoding isn't right
Comment: Nevermind. You're echoing the user's cookie `echo $guestuserid = $_COOKIE["guestuser"];`. That's why you're having this extra stuff.
Comment: Try debugging each line till you find the issue. You've got a better chance of fixing it
Comment: sorry thaks its works now
Answer: Those unwanted characters are showing up there because you're echoing a key from the $_COOKIE array, in the following line:
echo $guestuserid = $_COOKIE["guestuser"];

Remove the echo and you should be good to go.


Does Charpit's method gives general solution to first order non linear partial differential equations? What about this counter example?

Question: Using Charpit's method, the solution to the PDE
$\frac{\partial z}{\partial x}+\frac{\partial z}{\partial y}=0$
comes out in the form:
$z=ax-ay+c$,
as claimed by many textbooks.
But consider this alternate unaccounted solution to the same problem:
$z=\frac{x^2}{2}-xy+\frac{y^2}{2}$
Similar approach can yield a class of different solutions in the form of polynomials of higher degree in $x$ and $y$.
Charpit's method does not yields these solutions. (Does it?). So, how can we call it a general method to solve first order PDEs?
Answer: $z=ax-ay+c$ isn't the general solution.
The general solution, thanks to Charpit's method or other methods is :
$$z=F(x-y)$$
where $F(X)$ is any differentiable function.
For example with $F(X)=aX+c \quad\to\quad z=a(x-y)+c=ax-ay+c$
Other example, with $F(X)=\frac{1}{2}X^2 \quad\to\quad z=\frac{1}{2}(x-y)^2 = \frac{x^2}{2}-xy+\frac{y^2}{2}$
You can obtain an infinity of solutions of the PDE with other functions $F(X)$


Problemas com radiobutton em tabela(TR para cada um) - Aceita que todos estejam clicados

Question: Tenho essa tabela e esses radios buttons. Acontece que eu seleciono mais de um radiobutton, ele não obedece a questão, de um selecionado o outro não.

                    @Html.RadioButton("Improdutivo-Reagendar","Improdutivo-Reagendar")Improdutivo-Reagendar

                    @Html.RadioButton("Improdutivo-PDV Não Apto","Improdutivo-PDV Não Apto")Improdutivo-PDV Não Apto

                    @Html.RadioButton("Improdutivo-Comercial","Improdutivo-Comercial")Improdutivo-Comercial

                    @Html.RadioButton("Improdutivo-Infra Estrutura","Improdutivo-Infra Estrutura")Improdutivo-Infra Estrutura

                    @Html.RadioButton("Finalizado","Finalizado")Finalizado

Comment: você pode explicar um pouco melhor o que esta acontecendo, talvez adicionar print algo do genero ?
Comment: Eles devem possuir o mesmo nome e os valores representando cada um.
Comment: Otto, eu posso, por exemplo clicar e checar todos de uma vez. Quanto ao FCCDias, como eu atribuo um nome a RadioButton criados por Helpers(@Html.RadioButton)?
Answer: Todos devem possuir o mesmo nome e o valor são diferentes para que você recupere tal valor, ou seja, para que você selecione somente um dos valores o nome é obrigatóriamente iguais. Se você for produzir outro grupo de radio coloque outro nome e assim por diante

        @Html.RadioButton("selecao", "Improdutivo-Reagendar")Improdutivo-Reagendar

        @Html.RadioButton("selecao", "Improdutivo-PDV Não Apto")Improdutivo-PDV Não Apto

        @Html.RadioButton("selecao", "Improdutivo-Comercial")Improdutivo-Comercial

        @Html.RadioButton("selecao", "Improdutivo-Infra Estrutura")Improdutivo-Infra Estrutura

        @Html.RadioButton("selecao", "Finalizado")Finalizado

Referência

HTML Forms and Input
Comment: Quando falei no comentário, ainda não estava para mim a resposta. Agora resolveu tudo.


How to add 100 contributed modules into git repository fast?

Question: I use a git repository, and Drush to manage Drupal projects.
What I would like to do now is to add more then 100 contributed modules to the git repository to keep track on these modules as well.
If I am forced to add contributed modules manually, I have to do the following steps over 100 times:
drush dl <contributed module name>
git add .
git commit -m "<contributed module name> <contributed module version> imported"

I would like to avoid or limit this manual task.
Is there any automated way to do this?
Comment: I am looking for a linux shell script to automatically download contributed modules and add these modules to git repository and commit changes module by module. The script should contain a list (or array) of contributed module names and preferably automatically choose the latest stable contributed module version as described above.
Comment: Why can't you add them all in the same commit? I don't find pushing 100 different commits adding modules particularly useful.
Answer: You can use submodule on if you want keep tracking all latest commit for each project, but that means that your project can have development code from one of these modules.
Or, you can also download all your 100 modules with Drush and just do a git add . in the parent directory (git add all files recursively).
Comment: Yvan, thank you for your hints. Actually I do not need to track every single commit for these contributed modules' projects however I would like to keep track of what module version was installed and when. I would like to keep commits separated for each contrib modules download and only make this process more automated mainly to avoid errors and to be able to repeat it.
Comment: To keep track of all installed modules and their dependencies check Features and [Master](https://drupal.org/project/master) modules
Answer: I wrote a short bash script (below) that simplifies this process a bit but is not perfect.
Can someone suggest a more flexible solution ?
function drush_dl_add_commit()
{

    dr_module=${1}
    dr_version=${2}

    drush dl "${dr_module}-${dr_version}"
    git add .
    git commit -m "${dr_module} (${dr_version}) imported"

}

drush_dl_add_commit profile2 7.x-1.0
drush_dl_add_commit progress 7.x-1.0
drush_dl_add_commit purr_messages 7.x-2.0-beta2

How to automatically select the latest stable module version so the following would work without errors/warning messages ?
drush_dl_add_commit profile2
drush_dl_add_commit progress
drush_dl_add_commit purr_messages

Comment: ```drush dl ``` automatically downloads the latest stable version.
Comment: Yes, thank you. I could also use drush dl -y "${dr_module}" to skip interactive messages.


Rolles theorem word problem - find the c - double checking my answer

Question: Problem:
Find the relationship of $a$ and $b$ so that Rolles theorem applies for the function $f(x) = ax^2 + b(\ln x)$ on $[1,e]$. Find the value of $c$ for which it is verified.
Answer:
the relationship between $a$ and $b$ is $b = a(1 - e^2)$
the value of $c$ is $c = \pm\frac 1 2\sqrt{e^2 - 1})$
I would like to double check my answer on this problem
Any feedback would be appreciated.
Thank you
Comment: As long as $a$ and $b$ are opposite in sign, the first derivative would be $2ax + \frac{b}{x}$.  To make it zero, multiply $x$ on both sides, so that $x = -b/2a$ will give the extremum.
Answer: Since $f(1)=a$ and $f(e)=ae^2+b$, one condition is $f(1)=f(e)$, so $b=a(1-e^2)$.
The function is indeed differentiable on $[1,e]$, so for $b=a(1-e^2)$, Rolle's theorem applies.
Since
$$
f'(x)=2ax+\frac{a(1-e^2)}{x}
$$
you just need to find $x\in(1,e)$ such that $2ax^2+a(1-e^2)=0$.
If $a=0$, there is obviously no problem. If $a\ne0$…