Comparison of returns of two investment strategies. Can some kind of randomization help?

Question: My task is to compare the returns of two investment strategies using historical quarterly returns calculated from S&P 500 Index data.
Example: If I chose 10 year horizon of an investment, then for strategy A I have a time series of returns 1930q1-1940q1, 1930q2-1940q2 ... 2005q1-2015q1, and the same for strategy B. So I need to compare these two time series in order to determine which strategy gives significantly higher returns.
Both autocorrelation and non-stationarity are present.
I can't use paired t-test, since time series is not a random sample. There is significant autocorrelation of higher orders.
By differencing I just lose information about how high the returns were. And my goal is really just to say something like "based on historical data, returns from strategy A were significantly higher than returns from strategy B". I don't need to analyze trend of these series nor to make predictions.
I haven't found any solution to this problem. There were few similar questions on the internet but the asnwers recomended either to do something else than just pure comparison or to use t-test which I consider incorrect.
My idea is to use some kind of randomization. If I randomly chose say 30 values from the whole time series (the example above has 300 values), is it possible to consider these 30 values as a random sample? I assume that I could get rid of autocorrelation by this so to have justification to use t-test. I could repeat this 100 times and look how often I get significant difference.
Is my idea correct in any way? Or does anyone have any other idea? Thank you very much for reading and any suggestions.
Tom
Comment: Your question could be considered a duplicate of [this](https://stats.stackexchange.com/questions/137462/how-to-determine-if-the-mean-of-1-time-series-is-significantly-greater-than-that/252035#comment535114_252035), except for the randomization part. Does that thread help? Also, do you think the returns are nonstationary (you seem to say so)? If so, are you refering to the level (the conditional mean) or the volatility (the conditional variance)?
Comment: Thank you Richard, your answer really helped. I completely forgot about the HAC SE option. Yes, the returns are nonstationary. Yes, I was refering to the level (cond. mean) and you helped me with that. Next step would be comparing return/risk profile. I think that under homoscedasticity I can estimate risk by standard deviation and just create time series as return/SD values and repeat the procedure you mentioned.

The other thread also helped to clarify the issue. I am in the situation described there by having just one observation from each population, because the mean changes with time.
Comment: Under homoskedasticity, there is no need to transform the returns by dividing by the standard deviation. It would make sense under conditional heteroskedasticity, though. Hmm, so do you still have a question? I couldn't quite understand that from your comment.
Comment: So, what do you think? Does my answer solve your problem, or do you need further clarifications?
Comment: It does solve my problem. Thank you again. And you are right, dividing returns by constant would make no sense, my bad.
Answer: You could take the difference between the two time series, $z_t:=y_t-x_t$ (where $x_t$ and $y_t$ are the two original series), and test whether $z_t$ has zero mean.
You could implement this by running a regression of $z_t$ on a constant and either (1) allowing the error to follow and ARMA process or (2) using heteroskedasticity and autocorrelation robust standard errors.
You would look at the statistical significance of the intercept of the model to see whether $z_t$ is statistically above or below zero, which corresponds to $y_t$ being above or below $x_t$.
This is simpler than randomization, and the problem of autocorrelation is handled in a more proper way (whereas I think it is not handled properly in randomization as you describe it).


Secondary dominants

Question: I saw this progression as an example on an article about secondary dominants:

    C Am B7 C

Is the idea here to have B7 as the dominant of E which is the dominant of Am?
Comment: Missing some key info. Is the key supposed to be C? Am? G? Em?
Answer:
Is the idea here to have B7 as the dominant of E which is the dominant
  of Am?

Am -> B7 -> E -> Am would be a commonly used example of a secondary dominant, yes. But having C come after the B7 seems like either a mistake or just a bad example.
The fact that the B7 isn't actually followed by an E7 doesn't make the B7 any less a secondary dominant though. During the B7 you may have expected an E chord ... but, surprise? C! Then again, you could stop the song before the C, and then we could only guess if that was supposed to be the real end of it.
(You may disagree on the previous paragraph, and there are many points of view... see this question: What Constitutes a Secondary Dominant?)
Comment: You can analyze it as I -> vi -> V7/iii -> VI/iii, where VI/iii = I is a deceptive resolution of the dominant chord.
Answer: If this is an introductory example to secondary dominants, then it is a bad one. It should be saved for later lessons.
You are correct to assume that B7 is secondary dominant to E. So, as piiperi said
Am B7 E Am

would be a better/simpler example.
Just to expand on the topic, I'd like to point two things out:
There are secondary dominants to other degrees of the scale (not only to the dominant). So you could have
Am C7 F Am

or even
Am A7 Dm Am

and still remain on the tonality of A minor. Also, the example you posted could be explained as secondary dominant leading to a simple deceptive cadence: C is VI of E minor. This would also work if it led to C#m (vi of E major). Then again, if you want to stay on Am, this would lead to a more distant chord. Using this example as an introductory one is a bit too much.
Comment: I was going to write an answer explaining it as a deceptive cadence (the final C chord being both I and VI/iii, with the B7 being V7/iii), and I almost missed that you had already said this right at the end, hence this comment to point others to this.
Answer: There are no secondary dominants in that example!
Secondary dominants are chords which lead to diatonic chirds, not actually being diatonic themselves. So, if the sequence shown is in Am, that B7 should be leading to E or Em. If the sequence is in C, the same applies.
The clue is in the name. There is only one dominant of a key - that chord built on the 5th note. Thus, in key C, it's G (or G7).
A secondary dominant is the dominant of another chord from the relevant key. Here, it's C.. Were that other chord Dm, its secondary dominant is A. Were it Em, its secondary dominant is B (or the quoted B7). Were it F, the secondary dominant is C7. Were it G, it's D(7), and Am would need E(7). Each secondary dominant includes notes which are non-diatonic - called chromatics.
Comment: @piiperi - I understand the 'real time' analysis, but analysis usually, with most things, is done retrospectively - 'so what exactly happened'. As such, if , in key C, an E chord is followed by an F, it's unexpected, so makes interesting listening, as we're sort of programmed to expect an A/Am, but whether this gives the E claim to be sec. dom. - is another question - about to be posed!
Comment: Do you mean that in an Am context if you hear B7 all of a sudden, you won't be able to call it a secondary dominant until you know what actually happens after it? So, secondary dominants only exist in hindsight? And even if there's an E7 after the B7, even then you have to get an Am after it or otherwise the E7 wasn't a dominant and so the B7 wasn't a secondary dominant either? I think you should be able to listen to music, analyze and describe your feelings in real time, not only in hindsight. IMO, "leads to" is better understood as "points to".
Comment: @piiperi - interesting point. I just feel that it gets called a secondary dominat as it leads to a particular place. As in key C, if there's E7>Am it's a sec. dom., but if there's E7>F it won't be *called* a sec. dom., as it's not performing that particular role at that time. Will double check, though! According to Wiki, a sec.dom is usually, but not always, followed by a tonicised chord.
Comment: There seem to be different schools of thought. We've had some discussion about the use of the term "dominant seventh" as a description of a chord type, as opposed to "major seventh". Some people think that you shouldn't use the word "dominant" unless its tonic actually happens - which of course assumes a pre-defined progression, basically a written score of the tune. But IMO it's better to have a real-time perspective, so you describe different _possible_ interpretations - it's all just potentials for something. That way lends itself to understanding ambiguities in harmony, in jazz etc.
Comment: @piiperi I agree with Tim. Taking you "real time" POV seriously, you can't really analyse anything at all because all chords could have a whole lot of different functions. It's the context – and specifically the "what comes next" – that actually narrows it down and makes the concept of functions meaningful. Sure, some ambiguity is fine and can be desirable, but if everything is _completely ambiguous_ then you might as well not bother classifying anything at all.
Comment: @leftaroundabout Yes, it's about the context. In one context you have the future available as given, in another you don't. In one context you analyze the past, in another you plan for the future. Something is wrong if you cannot call a chord dominant, unless given the next chord too. Analysis in hindsight is only one thing and it isn't everything. Do you watch football? You can often tell what the players are trying to do even if they don't succeed. But if you don't understand the game well enough, you have to be shown a video of a successfull attempt to see what the plan was. :)

Secondary dominants


php function to extract link from string

Question: i want to extract href link from text or string. i write a little function to do that but this is slow when a string to transform is large. My code is
function spy_linkIntoString_Format($text) {
    global $inc_lang; $lang = $inc_lang['tlang_media'];
    $it = explode(' ' ,$text);
    $result = '';
    foreach($it as $jt) {
        $a = trim($jt);
        if(preg_match('/((?:[\w\d]+\:\/\/)?(?:[\w\-\d]+\.)+[\w\-\d]+(?:\/[\w\-\d]+)*(?:\/|\.[\w\-\d]+)?(?:\?[\w\-\d]+\=[\w\-\d]+\&?)?(?:\#[\w\-\d]*)?)/', $jt)) {
            $pros_lis = str_replace('www.','',$jt);
            $pros_lis = (strpos($pros_lis, 'http://') === false ? 'http://'. $pros_lis : $pros_lis);
            $urlregx = parse_url($pros_lis);
            $host_name = (!empty($urlregx['host']) ? $urlregx['host'] : '.com');
            if($host_name == 'youtube.com') {
                $string_v = $urlregx['query']; parse_str($string_v, $outs); $stID = $outs['v'];
                $result .= ''.$lang['vtype_youtube'].' ';
            } elseif($host_name == 'vimeo.com') {
                $path_s = $urlregx['path']; $patplode = explode("/", $path_s); $stID = $patplode[1];
                $result .= ''.$lang['vtype_vimeo'].' ';
            } elseif($host_name == 'travspy.com') {
                $result .= ''.$pros_lis.' ';
            } else {
                $result .= ''.$pros_lis.' ';
            }
        } else {
            $result .= $jt.' ';
        }
    }
    return trim($result);/**/
}

Can i do this run fast?
Answer: You should rewrite this to use preg_match_allinstead of splitting the text into words (i.e. drop the explode).
$regex = '/\b((?:[\w\d]+\:\/\/)?(?:[\w\-\d]+\.)+[\w\-\d]+(?:\/[\w\-\d]+)*(?:\/|\.[\w\-\d]+)?(?:\?[\w\-\d]+\=[\w\-\d]+\&?)?(?:\#[\w\-\d]*)?)\b/';
preg_match_all($regex, $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $url = $match[0];
    // your link generator
}

Answer: You seem to be breaking the text into words separated by spaces, and then matching each word against a regular expression. This is very time consuming indeed.
A faster way to do this is to perform the regular expression search on the entire text and then iterate over it's results.
preg_match_all($regex, $text, $result, PREG_PATTERN_ORDER);
foreach($result[0] as $jt){
    //do what you normally do with $jt
}

Comment: this ok but i want to return text that not contain link. how to do this with a Regex
Comment: You can do preg_replace_all($regex, "", $text) which will delete all patterns that match $regex. However this is a little dangerous as it may delete more than you were counting on.


React StrictMode useEffect got wrong state from wrong render cycle

Question: Before Ask, I already:

I understand StrictMode will make render -> unmount -> render, which will make my component renders twice
I understand in StrictMode I need to use keep my component pure function to make it work
Most related to my question is this. It's exactly the same problem I'm facing, but no answers I expected.

The Problem:
My function will make a network call with abortController.signal as useState. Upon unmounting, it'll abort the controller by useEffect.
But, when react render(0) -> unmount(0) -> render(1), the umount(0) actually read the state already from render(1), which lead to my render(1) got cleaned up, leading to unexpected result.
My expectation:
React's first umount(0) will see state from render(0) so my cleanup function works as expected.
Code:
import { Suspense, useEffect, useMemo, useState } from 'react';

// make promise suspendable
enum Status {
  Pending,
  Fulfilled,
  Rejected,
}

const Suspendable = <T,>(promise:Promise<T>): (() => T) => {
  let status: Status = Status.Pending;
  let error: Error;
  let result: T;
  const suspender = promise.then((r: T): void => {
      status = Status.Fulfilled;
      result = r;
  })
      .catch(err => {
          status = Status.Rejected;
          error = err;
      });

  return () => {
      switch(status) {
          case Status.Pending:
              throw suspender;
          case Status.Rejected:
              throw error;
          case Status.Fulfilled:
              return result;
          default:
              throw Error(`Unexpected arg ${status}`);
      }
  }
};

// make fetch a promise
const Req = (uri: string, config: RequestInit={}): Promise<string> =>   new Promise<string>((resolve, reject) => {
  fetch(uri, config)
      .then(resp => resp.text())
      .then(resolve)
      .catch(reject);
      // using this catch lead to page stuck at loading forever as promise never resolved
      // .catch(e => {
      //   if(e.name === "AbortError") {
      //     return;
      //   }
      //   return reject(e);
      // });
});

// do actual render content
const Renderer = ({ getResponse }: { getResponse: () => string }) => {
  console.log(`Renderer start`);
  const response = getResponse();
  console.log(`Renderer get response, return component`);
  return
{response}
;
}

// state interface
interface Result {
  suspendable: () => string;
  abortController: AbortController;
  retryKey: number;
}

const App = () => {
  const [controller, setResult] = useState<Result>((() => {
    const abortController = new AbortController();
    const retryKey = Math.floor(Math.random() * 100000);
    console.log(`create controller ${retryKey}`)
    return {
        abortController,
        retryKey,
        suspendable: Suspendable<string>(Req(`/`, { signal: abortController.signal }))
    };
  })());

  useEffect(() => {
    return () => {
      console.log(`clean up ${controller.retryKey}`);
      controller.abortController.abort();
    }
  })

  // ErrorBoundary wont help (
  return <>
  {/* <ErrorBoundary> */}
    <Suspense fallback={
Loading
}>
        <Renderer getResponse={controller.suspendable} />
    </Suspense>

-- Parent Node

  {/* </ErrorBoundary> */}
</>;
}

export default App;

Expectation:

StrictMode runs the first time, page error out, or catch by errorBoundary
StrictMode unmount, useEffect runs cleanup, connection aborted
StrictMode runs a second time, starts Suspense loading, and renders page content after fetch finished

Unexpected, actual Result:
StrictMode clean up my second state on the first render, making my second render aborted on the loading process.
Unexpceted logs:
create controller 8343  # first render
create controller 69996  # second render? no clean up called?
Renderer start
clean up 69996  # first unmount finally happend? but cleanup my second render?
Renderer start
Uncaught DOMException: The operation was aborted.   # expected
Renderer start
Uncaught DOMException: The operation was aborted.   # unexpected
clean up 69996  # again?

Version:
"react": "^18.2.0"

Edit:
the code from this works as:
  const hasUnmounted = useRef(false)

  useEffect(() => {
    return () => {
      if(hasUnmounted.current){
          // do my cleanup
      }
      hasUnmounted.current = true;
    }
  })

But,

I don't understand why my old code can't work
Why I need to manually check using ref.
Answer: I dont think react documented its strict mode correctly, but here is the way to avoid it without dirty hacking (without using a ref):
if you clean up something, then create it inside the same useEffect
to say, the code should be:
const [controller, setController] = useState<AbortController | null>(null);
useEffect(() => {
    setController(new AbortController());
    return () => {
        // don't assert this is non-null.
        controller?.abort();
    }
}, []);

// Now listen to the controller changes
useEffect(() => {
    if(controller) {
        // do some setState to know it's loading/finished/error
        fetch(..., {signal: controller.signle});
    }
}, [controller]);

// this is the dirty part. Always deal with the not-created (yet) situation.
// or you have some other state to indicate, e.g. `isLoading`
if(controller === null) {
    return <>loading...</>;
}

return <>Your logic here...</>;


On boot firmware request for intel GMA 3100 chipset timing out

Question: I am currently in the process of installing a Gentoo linux box with a Vanilla 2.6.29-r5 kernel with gentoo-xen-kernel patches in order to run the Xen Hypervisor.
After rebooting with the new kernel, the booting process seemed to hang on:
<code>[    0.863005] platform microcode: firmware: requesting intel-ucode/06-0f-07
[   60.863442] Microcode Update Driver: v2.00-xen <firstname.lastname@example.com>, Peter Oruba
</code>
Apparently the firmware request times out after 60 seconds (<code>/sys/class/firmware/timeout</code>) and booting just continues.
I have done some research and have found that on RHEL-4 this problem was related to the mount of /sys changed and the firmware.agent hotplug script couldn't parse the line correctly.
However I am having some difficulty tracking down how to fix this on Gentoo.
Any and all ideas are greatly appreciated!
Thanks
Comment: This bug is still valid with gentoo xen-sources 2.6.34-r4.
Answer: Try to compile "/dev/cpu/microdode - microcode support" as a module in your kernel and load it later


Significance testing when the treatment group was only partially treated (an unknown set of individuals did not receive the treatment)

Question: I have a somewhat messy experiment that has already been conducted with large test and control groups, and have measured the response variables (sales / individual, etc). A known percentage of the 'test group' (supposed to be exposed to a treatment) did not actually get exposed to the treatment, and I have no way of separating them in the data. I can see whether someone was 'supposed to receive a treatment' and 'definitely did not' (control).
I can directly observe:

Z = Intended test group (composed of X and Y) - only some received treatment
C = Control group
w = proportion of X that makes up Z (but cannot tie to individual records) - e.g. 60% of the intended test group actually recieved the treatment.

I cannot observe:

X = 'Actual test group' that recieved treatment
Y = People who were supposed to recieve treatment but did not.

I would like to be able to make statements of significance about whether X differs from C (e.g. with 2-sample t-test)
Intuitively, Y 'should' look like C (they both represent sales/customer for customers who have not received the treatment, though they have different/known sizes), and I want to subtract it out to get an estimate of X I can use in a t-test or similar. Subtracting the means proportionally I think should be fine, but I'm concerned that doing the same for the variance is not correct.
I know 'when random variables subtract, the variances add', but wonder if that will screw up my t-test since I only have the sample variances and not the population parameters.
How should I be trying to make this adjustment?
Comment: I should add:

Don't necessarily need an exact answer for this situation (though it would be interesting to know). Even if there is a relatively simple adjustment I can make and know whether it will be a 'slight over or underestimation', I think that would work at this point.
Comment: Do you think that the response variables (sales / individual, etc) follow normal distribution for control group?
Comment: Yes. There is one that I guess is binomial (#of conversions), but I would think since we are talking very large sample sizes (hundreds of thousands) the CLT would kick in and everything would be approximately normal.
Comment: the response variables (sales / individual, etc) is how much $ sold, # of deals, sold not not sold?
Comment: yes - $ sold, number of items sold (basket size), sold vs not sold
Answer: I disagree with the other answer by @mkt that no inference is possible, but yes, inference, like hypothesis testing, might be difficult.  But there are some possibilities.
In the treatment group, where only about 60% of the subjects/items actually received treatment, we might model the distribution of the outcome as a mixture distribution, of the form
$$
0.6 \cdot \text{distribution when treatment given}+0.4 \cdot\text{distribution when treatment not given}
$$ Using regression with such a model is called mixture regression (search this site, many posts!) and there are for instance some R packages, like flexmix and fpc.   But our situation is simpler, since the mixing probabilities is given, known, and not to be estimated. So we can just write down a model, find the loglikelihood function, and use mle (maximum likelihood estimation.)
Since little context is given, we will use a very simple model as illustration. We assume independence and normal distributions. In the control group (and the non-treated in the treatment group) we have $Y_i \sim \mathcal{N}(\mu,\sigma^2)$ while among the treated we have $Y_i\sim\mathcal{N}(\mu+\Delta,\sigma^2)$. So in the "treatment group" we have $Y_i \sim w\cdot\mathcal{N}(\mu+\Delta,\sigma^2)+(1-w)\cdot\mathcal{N}(\mu,\sigma^2)$. For your data you told us $w=0.6$. The same principles could be used with other error distributions, covariables, etc. The interest or focus parameter is $\Delta$, so we will ultimately use the profile likelihood for $\Delta$ to construct a confidence interval.
With simulated data I construct this model in R, and the resulting confidence interval based on the profile likelihood is below:
Note that in this proposed model we have assumed constant variance. This might be a critical assumption (as it always is, but maybe more so here.) This is because, in the "treatment" group, a higher empirical variance could be because of either a large $\Delta$, or because the variance actually is larger than in the control group (maybe because the treatment, somehow, also increases variance.)  So this model should be taken as tentative, it would be wise to investigate it further before use. I tried to search for papers on this issue, could not find any.
The R code used:
    n <- 100 # "treatment" sample size
    m <- 100 # control sample size
    mu <- 10; sigma <- 3; delta <- 0.8
    w <- 0.6 # fraction of treatment data really treated
    # Simulating some data:
    set.seed(7*11*13) # My public seed
    Y <- rnorm(n+m, c(rep(mu, m), rep(mu+delta, w*n),
            rep(mu, (1-w)*n)), sigma)
    G <- c(rep(0L, m), rep(1L, n)) # 1 is treatment group
    mydf <- data.frame(Y=Y, G=G); rm(Y, G)

    # loglikelihood function:

    loglik0 <- function(mu, delta, sigma) {
        loglik <- sum(ifelse(mydf$G==0L, dnorm(mydf$Y, mu, sigma,
            log=TRUE), log(w*dnorm(mydf$Y, mu+delta, sigma) +
        (1-w)*dnorm(mydf$Y, mu, sigma))))
        -loglik  # we use bbmle::mle2 which requires the
                 # negative loglik
    }

    library(bbmle)# on CRAN
    mod <- bbmle::mle2(loglik0, start=list(mu=8, delta=0,
                 sigma=2))

    mod.prof <- bbmle::profile(mod, which=2)

    confint(mod.prof)
        2.5 %    97.5 %
    -0.571204  1.704091

    plot(mod.prof)

Comment: (+1) Very nice, this makes a lot of sense. I had only encountered mixture modelling in zero-inflated models and did not make the connection to this type of situation.
Answer: EDIT: kjetil b halvorsen's new answer has persuaded me that my answer below is incorrect.

+1, this is an interesting question
To summarize: the goal is to try to compare people who did receive treatment ($X$) with those who were controls ($C$). However, $X$ is a subset of the population supposed to receive treatment ($Z$), and we only know that $X$ is $w$% (60% here) of $Z$, with the remainder (100 - $w$)% being called $Y$.

Unfortunately, I do not think there is any legitimate way to make a strong statistical claim from this data. Therefore, I think estimating statistical significance is out of the question.
However, it might be possible to do a useful exploratory analysis with this dataset instead.
I would start by examining $Z$, the people supposed to have received treatment. If you run a clustering algorithm on this, you might find that the data falls into two natural groups with a ~60/40 split, as expected. These would correspond to the subgroups that did receive treatment ($X$) and those that were supposed to but did not ($Y$). You could then calculate the means of the 3 groups - $X$, $Y$ and $C$ - and with caveats, make some weak statements about possible differences between them. You could also exclude $Y$ from further consideration, or add those points to $C$, but I think keeping them as a separate category is less likely to mislead.
Assuming the above steps work, could you then do a hypothesis test on them? No - because the results are going to be biased to an unknown degree by the uncertainties in the clustering step. Points belonging to $X$ but that are far from its mean/median/centroid (depending on clustering approach) may be grouped with $Y$, and vice versa. This will have the effect of reducing group variances and inflating differences between the groups. Despite these limitations, I think that this approach could provide useful information about the differences between groups.
A few related thoughts:

A clean clustering result like the one I described might seem very unlikely - clusters could be the wrong proportion (i.e. not corresponding well to $w$% and (1 - $w$)%, or more than two clusters might be identified in the data. If either of these happen, I might try a different cluster approach, but my (already low) confidence in this procedure would reduce substantially. But if the treatment has a strong effect, which may be expected based on prior knowledge and experimental design, two distinct clusters of approximately correct proportions are an entirely plausible outcome.
Knowing $w$ is crucial for getting some idea of how well the clustering step has worked.
$w$ being quite different from 50% is helpful knowing which clusters are $X$ and $Y$. However, even if $w$ was exactly 50% and the two groups therefore identical in size, comparing the two clusters against $C$ would help in distinguishing $X$ from $Y$. If one cluster's outcomes are much more similar to those of $C$, it is likely to be $Y$.
I'm setting aside discussion of what type of clustering approach to use because there are a huge range of possibilities, and which one works best depends strongly on details that we do not know.
Comment: I added an other answer, do you have any thoughts?


jQuery .not() problem

Question: I need to do some operations with elements that have class show-all and have no class disabled. My code:
$('.show-all').not('.disabled').click(function() {
    alert('1');
})

But it works too if element has disabled class. Can you help me?
Sorry for my english. Thank you in advance.
My code, that works fine now:
$(document).ready(function() {
    $('.show-all:not(.disabled)').click(function() {
        if (!$(this).hasClass('disabled')) {
            $(this).parent().parent().find('li').removeClass('hidden-item');
            $(this).addClass('transparent-50').addClass('disabled');
        }
    })
});

Comment: this looks like it should work - could you perhaps provide a jsfiddle link, or the full code?
Comment: Looks correct to me. Did you try the `:not` selector instead, i.e. `$('.show-all:not(.disabled)')`?
Comment: @Xion with no space between `all` and `:` unless you want to target the children of `.show-all`
Comment: On jsFiddle it works fine) http://jsfiddle.net/kMrpY/
Comment: @Capsule Right. I edited my original comment.
Answer: not() is a CSS selector. Do like this:
$('.show-all:not(.disabled)').click(function() {
    alert('1');
});

Comment: There's no point of using a jQuery method when there's a selector available.
Comment: In this case, no, but the method can be used on an existing jQuery object. Anyway, this doesn't make not() method disappear ;-)
Answer: Works fine here.
How does your markup differ from the example above?
Answer: It's working the way you have it. Check working example at http://jsfiddle.net/9BSdy/
Answer: The following seems to work:
$('.show-all:not(.disabled)').click(function() {
    alert('1');
});

Live demo.

jQuery .not() problem


How change widget of a "between exposed filter" to combo box?

Question: I have a view that has some exposed filters. One of the filters is on the price of the content type. I want to filter contents by price when price is between two known value. For example I want to filter all the content that their prices are between 0 and 5000. The other thing I want is a select box for this filter. So the filter is a select box with some options like below:
<code><option>0-5000</option>
<option>5000-10000</option>
<option>10000-15000</option>
<option>15000-20000</option>
</code>
I add a filter to the view and mark it as exposed filter, then change its operator to between. Now what should I do to change the widget from two text box to a single select box?
Answer: You're close. After you expose the filter, change it from Single filter to Grouped filters using the radios right below the expose checkbox. Then you can define what each option is and make it a select box.


Opencart - Change header for product page only

Question: Can I initialize some variable in product controller product.php, then load it to header controller header.php and use it in view header.twig, to load certain information based on this variable? If not, how can I determine whether the page with the product is open or not?
Answer: Easiest way determine product page in header.php
if (isset($this->request->get['product_id'])) {
    $product_id = (int)$this->request->get['product_id'];

} else {
    $product_id = 0;
}

if ($product_id) {
//... some code for product page
}

Also you can combine check with product controller route in header.php
if (isset($this->request->get['route']) && $this->request->get['route'] == 'product/product' && isset($this->request->get['product_id'])) {
// some code for product page
}


How to position elements in bootstrap

Question: I am creating a dashboard with the adminlte template and I cannot get the result I expect, my page is shown as follows. enter the description of the image here
I want the web to occupy the width of the browser and there are no spaces left, but for some reason I can't get the result. (The red squares indicate the space I want to eliminate)
Dashboard Image
Code:

<!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>AdminLTE 3 | Dashboard</title>

         <headerprincipal></headerprincipal>

            <menuprincipal></menuprincipal>

Dashboard

Home

Dashboard v1

Eventos

                           More info

150

New Orders

                           More info

150

New Orders

                           More info

150

New Orders

                           More info

         <footermain></footermain>

I appreciate your help.
Note: I am using angular 12.
angular.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "avcangular": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:application": {
          "strict": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/avcangular",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/admin-lte/plugins/fontawesome-free/css/all.min.css",
              "node_modules/admin-lte/plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css",
              "node_modules/admin-lte/plugins/overlayScrollbars/css/OverlayScrollbars.min.css",
              "node_modules/admin-lte/dist/css/adminlte.min.css",
              "node_modules/font-awesome/css/font-awesome.css"
            ],
            "scripts": [
              "node_modules/admin-lte/plugins/jquery/jquery.min.js",
              "node_modules/admin-lte/plugins/jquery-ui/jquery-ui.min.js",
              "node_modules/admin-lte/plugins/bootstrap/js/bootstrap.bundle.min.js",
              "node_modules/admin-lte/dist/js/adminlte.js",
              "node_modules/admin-lte/dist/js/demo.js",
              "node_modules/admin-lte/dist/js/pages/dashboard.js"
            ]
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "avcangular:build:production"
            },
            "development": {
              "browserTarget": "avcangular:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "avcangular:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        }
      }
    }
  },
  "defaultProject": "avcangular"
}
Answer: It seems these below mentioned classes css might be causing the issue.
hold-transition,sidebar-mini, layout-fixed or wrapper
Check if any of the class has some left and right margin or left and right padding defined. If it's defined try removing it and check the result.

How to position elements in bootstrap


Javascript Selenium Chrome WebDriver - proper way to handle alert

Question: I'm trying to close alert that sometimes appear when me selenium script running. It is block a click option for specific div that I'm handling in try catch options. When this exception occure, 'm trying to use driver function but it generates ,,NoSuchAlertError".
This some part of my code:
let driver = await new Builder()
    .withCapabilities(options)
    .forBrowser("chrome")
    .build();

// .. some other logic like get website etc. ... //

    try {
        let dataFromButton= await getDataFromButton(driver); // it fails when alert appear on screen
    } catch (e) {
        let alert = await driver.switchTo().alert(); // it throws NoSuchAlertError
    }

Here is my alert popup, that I'm trying to remove - click on cancel button or call escape key would be enough solution for me
Is there any special ,,alerts" that should be handled in other way than my example ?
Comment: Are you sure it's an alert and not just a popup wiindow? See https://www.guru99.com/alert-popup-handling-selenium.html
Comment: Yes, I have tried methods from your link and it always return the same one window (the same id).
Comment: Is alert is displayed on screen load?
Comment: @YaDavMaNish when it first time appear, it is still visible (my script loading the same page for diffrent resources and it is still visible on every changing of pages - so it is also visibile when page is loading but it dissapear when i open a new tab in browser)
Comment: I mean, it doesn't appear in another tab browser, when I open the same page.
Answer: I have finally found solution for chrome I use this code:
await driver.executeScript('window.stop();');

Comment: nice! glad you were able to figure it out.


Como faço para instalar o pacote Chromium em Delphi?

Question: Eu estava usando o componente TWebBrowser que é baseado no Internet Explorer, porém tenho notado que ele roda de forma desfigurada as páginas HTML5, ouvi falar no pacote do FireFox, mas ele não rodou no Delphi e demonstrou-se ser bem pesado, então minha ultima alternativa foi o pacote do Chromium.
Answer: Independente da versão do IE que vc tiver na maquina o windows sempre irá usar o IE6 dentro de qualquer aplicação desktop que vc colocar um webbrowser. Isso quer dizer que vc não terá vários suportes que as versões mais novar do IE tem, como suporte a JQuery ou mesmo Json.
Para resolver este problema vc deve fazer uma alteração no registro do windows para seu executável, dizendo que quer usar a versão mais atual do browser.
Crie um arquivo .reg com a seguinte estrutura:

REGEDIT4
[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
  "MeuExecutavel.exe"=dword:0

Já utilizei o chromium no Delphi como alternativa a uns 2 anos atraz, e ele era muuuuito instavel.
Comment: Na verdade é o IE 7 Standars Mode não IE 6. E para configurar o modo de compatibilidade do IE 8 o valor da chave é `"MyApplication.exe" = dword 8888 (Hex: 0x22B8)` e não zero. Não sei onde você leu sobre o IE6 mas parece que é incorreto. Minhas referências são: [esse link](http://blogs.msdn.com/b/ie/archive/2008/03/18/webbrowser-control-rendering-modes-in-ie8.aspx) e [esse outro link](http://blogs.msdn.com/b/ie/archive/2009/03/10/more-ie8-extensibility-improvements.aspx)


Adding firewalld to existing infrastructure with minimal downtime

Question: I have a mixed Ubuntu 16.04/Ubuntu 18.04 based infrastructure and would like to set up and configure firewalld on hosts. I am going to use an Ansible role for that (I have a Vagrant-based setup to test the Ansible role).
When I run Ansible playbooks a freshly installed firewalld blocks incoming connections by default although I never specified this explicitly:
[ 2161.574030] FINAL_REJECT: IN=enp0s8 OUT= MAC=08:00:27:f9:00:46:0a:00:27:00:00:00:08:00 SRC=172.16.137.1 DST=172.16.137.182 LEN=60 TOS=0x10 PREC=0x00 TTL=64 ID=36677 DF PROTO=TCP SPT=35098 DPT=455 WINDOW=29200 RES=0x00 SYN URGP=0
[ 4717.718425] FINAL_REJECT: IN=enp0s8 OUT= MAC=08:00:27:f9:00:46:0a:00:27:00:00:00:08:00 SRC=172.16.137.1 DST=172.16.137.182 LEN=60 TOS=0x10 PREC=0x00 TTL=64 ID=55673 DF PROTO=TCP SPT=47624 DPT=456 WINDOW=29200 RES=0x00 SYN URGP=0
[ 4719.682792] FINAL_REJECT: IN=enp0s8 OUT= MAC=08:00:27:f9:00:46:0a:00:27:00:00:00:08:00 SRC=172.16.137.1 DST=172.16.137.182 LEN=60 TOS=0x10 PREC=0x00 TTL=64 ID=60255 DF PROTO=TCP SPT=43836 DPT=457 WINDOW=29200 RES=0x00 SYN URGP=0
[ 4721.358343] FINAL_REJECT: IN=enp0s8 OUT= MAC=08:00:27:f9:00:46:0a:00:27:00:00:00:08:00 SRC=172.16.137.1 DST=172.16.137.182 LEN=60 TOS=0x10 PREC=0x00 TTL=64 ID=42733 DF PROTO=TCP SPT=51850 DPT=458 WINDOW=29200 RES=0x00 SYN URGP=0

Is it possible somehow to start firewalld in a permissive mode then configure everything and then apply the configuration in one shot?
Answer: Recently I converted some Ubuntu boxes from ufw to firewalld, and I use Ansible pretty much exclusively, so I also ran into a bit of this.
First, you should know that out of the box firewalld blocks most incoming traffic. In the default configuration on Ubuntu, no interfaces or sources are attached to any zone, so firewalld considers all traffic to be part of the public zone. This zone permits only incoming ssh and DHCP client response traffic.
There are a couple of ways you can handle this.
In my own Ansible playbooks and roles, I configure firewalld rules along with each service. So, I have a role that installs nginx, and that role also opens the http and https services in firewalld. So, as soon as the web server is installed and running, the firewall is also ready to go. When I converted from ufw to firewalld, I just re-ran the whole playbook and only the ufw and firewalld stuff changed.
If you are doing a one-off and have a lot of ports to open, or some other complex configuration, you might want to open the ports in firewalld on a scratch VM, and then grab the resulting XML file for that zone from the /etc/firewalld/zones directory. You can then copy: that file to any system and restart firewalld to have it use the corresponding configuration.


Get the proportion of rows smaller than a variable

Question: I have a R dataframe like this:
misc data
a    0.0
a    0.1
a    0.2
b    0.0
b    0.2
b    0.3
c    0.0
c    0.4
c    0.6

My goal is to create another dataframe, that will contain, for each possible value of data in a given range (for example seq(0.0, 10.0, by = 0.01)) and each value of misc, the proportion, among the rows with the same misc value, of the rows with a value of data inferior to the given value.
For example, with the given dataframe, I would have:
misc data   proportion
a    0.0    0.0
a    0.05   0.333
a    0.1    0.333
a    0.15   0.666
a    0.2    0.666
a    0.25   1.0
a    0.3    1.0
...
c    0.0    0.0
c    0.05   0.333
c    0.1    0.333
c    0.15   0.333
c    0.2    0.333
c    0.25   0.333
c    0.3    0.333
c    0.35   0.333
c    0.4    0.333
c    0.45   0.666
c    0.5    0.666
c    0.55   0.666
c    0.6    0.666
c    0.65   1.0
c    0.7    1.0

How can I accomplish this ? I'm still very new to R so a simple solution would be preferred
Thanks!
Answer: First, we need the framework with all unique misc and the sequence of data values:
eg <- expand.grid(misc = unique(quux$misc), data = seq(0, 0.7, by = 0.1))
head(eg)
#   misc data
# 1    a  0.0
# 2    b  0.0
# 3    c  0.0
# 4    a  0.1
# 5    b  0.1
# 6    c  0.1

dplyr
Using a two-step join and summarize:
eg %>%
  left_join(quux, by = "misc", suffix = c("", ".y"), relationship = "many-to-many") %>%
  summarize(proportion = sum(data.y <= data) / n(), .by = c("misc", "data"))
#    misc data proportion
# 1     a  0.0  0.3333333
# 2     b  0.0  0.3333333
# 3     c  0.0  0.3333333
# 4     a  0.1  0.6666667
# 5     b  0.1  0.3333333
# 6     c  0.1  0.3333333
# 7     a  0.2  1.0000000
# 8     b  0.2  0.6666667
# 9     c  0.2  0.3333333
# 10    a  0.3  1.0000000
# 11    b  0.3  1.0000000
# 12    c  0.3  0.3333333
# 13    a  0.4  1.0000000
# 14    b  0.4  1.0000000
# 15    c  0.4  0.6666667
# 16    a  0.5  1.0000000
# 17    b  0.5  1.0000000
# 18    c  0.5  0.6666667
# 19    a  0.6  1.0000000
# 20    b  0.6  1.0000000
# 21    c  0.6  1.0000000
# 22    a  0.7  1.0000000
# 23    b  0.7  1.0000000
# 24    c  0.7  1.0000000

base R
Row-wise summing of the conditions:
eg$proportion <- mapply(
  function(m, d) with(quux, sum(misc == m & data <= d) / sum(misc == m)),
  eg$misc, eg$data)
eg
#    misc data proportion
# 1     a  0.0  0.3333333
# 2     b  0.0  0.3333333
# 3     c  0.0  0.3333333
# 4     a  0.1  0.6666667
# 5     b  0.1  0.3333333
# 6     c  0.1  0.3333333
# 7     a  0.2  1.0000000
# 8     b  0.2  0.6666667
# 9     c  0.2  0.3333333
# 10    a  0.3  1.0000000
# 11    b  0.3  1.0000000
# 12    c  0.3  0.3333333
# 13    a  0.4  1.0000000
# 14    b  0.4  1.0000000
# 15    c  0.4  0.6666667
# 16    a  0.5  1.0000000
# 17    b  0.5  1.0000000
# 18    c  0.5  0.6666667
# 19    a  0.6  1.0000000
# 20    b  0.6  1.0000000
# 21    c  0.6  1.0000000
# 22    a  0.7  1.0000000
# 23    b  0.7  1.0000000
# 24    c  0.7  1.0000000


using linq Query how can i update multipul Records

Question: Here im getting Multipul values as 1,2,3 for ENQUIRY_CODE
public void HRUpdateStatus(string ENQUIRY_CODE, int uid)
{
    var x = (from e in db.EMS_ENQUIRYREGISTRATION_MASTER
             where e.ENQUIRY_CODE == ENQUIRY_CODE
             select e).ToList();

    foreach (var abc in x)
    {
        abc.HRowner = uid;
        db.SaveChanges();
    }
    ...
}

Please help me where im doing mistake
Comment: you dont need to call `db.SaveChanges();` each iteration, you can call it after `foreach` once
Comment: Are you getting multiple values as a list?
Comment: @ChetanRanpariya yes i am getting multiple values
Comment: Multiple values come in List? Can you share the code?
Answer: A LINQ statement will never change the source sequence.
 LINQ is not meant to do that.
The proper solution depends on which kind of DbContext you are using. If you use entity framework you'll have to fetch the items before you can update one or more of the properties.
In your case, you want to change one property of all fetched values to the same new value. Consider creating an extension function for your DbContext. See extenstion methods demystified
The following takes an IQueryable sequence of some source class (TSource), and an action that should be performed on each source element.
public void ForEach<TSource>(this IQueryable<TSource> source,
    Action<TSource> action)
{
     var fetchedItems = source.ToList();
     foreach (var fetchedItem in fetchedItems)
     {
         action(fetchedItem);
     }
}

Usage:
using (var dbContext = new MyDbContext())
{
     db.EMS_ENQUIRYREGISTRATION_MASTER
       .Where (registrationMaster => registrationMaster.ENQUIRY_CODE == ENQUIRY_CODE)
       .ForEach(registrationMaster => registrationMaster.HRowner = uid);
     db.SaveChanges();
}

I chose to return void instead of IEnumerable<TSource> to indicate to users of the function that the queried data is materialized and might have been changed. After all the following might have been confusing:
IQueryable<Student> students = ...
var updatedStudents = students.ForEach(student => student.Grades.Add(new Grade(...))
    .Take(2)
    .ToList();

You want to communicate that all students are updated, not just the 2. Consider returning an IReadonlyList<TSource> or similar, so you don't have to materialize the data again.
Comment: "A LINQ statement will never change the source sequence.
LINQ is not meant to do that." Harold stated very accurately here about how Linq should never change the sequence. To read more about the functional philosophy behind Linq here is [Eric Lippert on the topic](https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/)
Answer: I think this is what you mean:
var codes = ENQUIRY_CODE.Split(',').ToList();

var x= db.EMS_ENQUIRYREGISTRATION_MASTER.Where(s => codes.Contains(s.ENQUIRY_CODE)).ToList();


MYSQL - Inserting concatenated string

Question: Table Items

Table Sale

And finally: Table SaleItems

Procedure PLAYER_CREATE_SALE:
IN paramters:

in_player_id int
in_total int
in_items_ids nvarchar(500)
in_items_quantity nvarchar(500)

Basically, the "user" see the list of the Items above, select any item, change the amount and buy. This should works like a "cart".
So, for example: User select bomb(id: 1, quantity: 10) and gear(id: 3, quantity: 2)
The parameters of my procedure would look like this:
in_player_id: 750
in_total: 390
in_items_ids: "1,3"
in_items_quantity: "10,2"
This is how works the procedure actually:
    INSERT INTO Sale(`player_id`, `total_coins_price`)
    VALUES(in_player_id, in_total);

    SET @sale_id = LAST_INSERT_ID();

    SET @squery = CONCAT("INSERT INTO SaleItems(`sale_id`, `item_id`, `quantity`)
SELECT ", @sale_id, ", id, 9999 FROM Items WHERE id IN (", in_items_ids, ")");

    PREPARE stmt FROM @squery;

    EXECUTE stmt;

With the code above the result final will be:

But the quantity is wrong. I don't know how insert the quantity too. Here is how should be:
Comment: Sorry, can you try to clean up the question it is very hard to follow what you are trying to accomplish. For instance, where does VAR_1 and VAR_2 come from or what are they supposed to reference?
Comment: I guess var_1 is the first 2 ids from otiemsbase and var_2 is manually input by the user?
Comment: SQL doesn't do arrays - to get the elements in var_2 you need to split the string and probably put them into table so that you can change your select to be table based.
Comment: var_1 and var_2 are manually input by the user. Sorry, Im going to try to clean up the question
Comment: Hello, I updated and fixed my question.
Answer: Perhaps something like this
DROP PROCEDURE IF EXISTS P;
DELIMITER //
CREATE DEFINER=`root`@`localhost` PROCEDURE `P`(
    IN `instring` varchar(255)
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
begin
declare   tempstring varchar(100);
declare   outstring  varchar(100);
DECLARE   VAR_1 VARCHAR(100);
DECLARE      VAR_2 VARCHAR(100);
declare  checkit int;
DECLARE  LIMITOFFSET INT;

set checkit = 0;
SET VAR_2 = instring;
set tempstring = ltrim(rtrim(VAR_2));
SET LIMITOFFSET = 0;

looper: while   tempstring is not null and instr(tempstring,',') > 0 do
        set outstring = substr(tempstring,1,instr(tempstring, ','));
        set tempstring = ltrim(rtrim(replace(tempstring,outstring,'')));
        set outstring = replace(outstring,',','');
        set checkit = checkit + 1;
        insert into oitems
        select  CHECKIT,10,ID, outstring
         from  OItemsbase
         order by id
         LIMIT LIMITOFFSET,1
         ;
         SET LIMITOFFSET = LIMITOFFSET + 1;

end while;
    set outstring = tempstring;
    set tempstring = ltrim(rtrim(replace(tempstring,outstring,'')));
    set outstring = replace(outstring,',','');
    set checkit = checkit + 1;
    insert into oitems
        select  CHECKIT,10,ID, outstring
         from  OItemsbase
         order by id
         LIMIT LIMITOFFSET,1
         ;

end //

DELIMITER ;

MariaDB [sandbox]> DROP TABLE IF EXISTS OItemsbase;
Query OK, 0 rows affected (0.11 sec)

MariaDB [sandbox]> CREATE TABLE OItemsbase ( id INT, alpha_id INT, created_at VARCHAR(5));
Query OK, 0 rows affected (0.24 sec)

MariaDB [sandbox]> INSERT INTO OItemsbase VALUES
    -> (2, 100, 'today'),
    -> (6, 101, 'today'),
    -> (10, 101,'today');
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> drop table if exists oitemss;
Query OK, 0 rows affected, 1 warning (0.00 sec)

MariaDB [sandbox]> create table oitems(id int, example_id int, item_base_id int, quantity int);
ERROR 1050 (42S01): Table 'oitems' already exists
MariaDB [sandbox]>
MariaDB [sandbox]> truncate table oitems;
Query OK, 0 rows affected (0.23 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> CALL P('20,30');
Query OK, 1 row affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> SELECT * FROM Oitems;
+------+------------+--------------+----------+
| id   | example_id | item_base_id | quantity |
+------+------------+--------------+----------+
|    1 |         10 |            2 |       20 |
|    2 |         10 |            6 |       30 |
+------+------------+--------------+----------+
2 rows in set (0.00 sec)

Comment: Hello, thanks for you answer. That didnt work for me. Can you check my updated question?
Answer: I just added
SET @squery = CONCAT("INSERT INTO SaleItems(`sale_id`, `item_id`, `quantity`)
SELECT ", @sale_id, ", id, 9999 FROM Items WHERE id IN (", in_items_ids, ")");

And is working inserting the ids but the quantity is missing.

MYSQL - Inserting concatenated string


Closed form for $\sum_{n=1}^{\infty}\frac{x^n}{n!\sqrt{n}}$, or an asymptotic for it

Question: In my study I came about the function defined by
$$f(x)=\sum_{n=1}^{\infty}\frac{x^n}{n!\sqrt{n}}$$
and I have not been able to find any sort of closed form for it, nor have I been able to find any sort of assymptotics as $x\to+\infty$. Plotting the function on Desmos I can conjecture that
$$f(x)\sim c\frac{e^x}{\sqrt{x}}$$
for some constant $c$ (possibly equal to 1), but I cannot prove it. In general, is there a way to express the function
$$g(x)=\sum_{n=1}^{\infty}\frac{x^n}{n!n^{\alpha}}$$
where $\alpha\in\mathbb{R}>0$? This function seems to be some sort of exponential analogue of the poly-logarithm $\mathrm{Li}_s(n)$ defined by
$$\mathrm{Li}_s(n)=\sum_{n=1}^{\infty}\frac{x^n}{n^{\alpha}}$$
which does not have any closed form (unless $\alpha$ is a negative integer). If one could express $f(x)$ in terms of $\mathrm{Li}_{1/2}(n)$ then that would be perfect.
Comment: Also see: https://mathoverflow.net/q/264595/454
Answer: The Laplace transform of your function $g$ is
$$\mathscr{L} g(s) = \int_0^\infty \sum_{n=1}^\infty \frac{x^n}{n! n^\alpha} \exp(-sx)\; dx = \sum_{n=1}^\infty \frac{s^{-n-1}}{n^\alpha} = \frac{\text{Li}_\alpha(1/s)}{s}$$
for $s > 1$.
Comment: This is very insightful (+1), but I do not know of any standardized ways of getting asymptotic formulae for a function based off it's Laplace transform


Why IIS 6 gives me error message on each asp request?

Question: I have Windows Server 2003 with IIS6. Every time I request something that ends with .asp server returns a 404 error, but not a usual one, the error response is as follows:
HTTP/1.1 404 Not Found
Content-Length: 93
Content-Type: text/html
Date: Tue, 07 Jun 2011 07:14:27 GMT
Connection: close

<title>Error</title>�� ������� ����� ��������� ����.

What's the origin of this error and how can I fix this?
Answer: Have you tried just using a basic .HTML file to see if the same issue happens?
Also have you added in page.asp into IIS as an allowed document type?
Al
Answer: I would guess that your ISAPI mapping for the .asp extension is broken.  I see the same thing when I'm debugging ISAPI served PHP on IIS6.
Your error code looks like a 'friendly' error.  That's set in IIS6 as well.  Try to get proper error messages.  Also, check the IIS logs and Windows logs.
Answer: Agreed with Dan: also, 404 is a response the Web Service Extensions list will send to a client if the .ASP extension isn't explictly allowed from that interface.
There'll be a substatus code logged in the web logs that you can search on to more closely identify that item.
Check that:

ASP is enabled in SYSOCMGR (Add/Remove->Windows Features)
Active Server Pages is allowed in Web Service Extensions in the IIS MMC
Script permission is granted on the folder you're interested in
There's a script mapping for .ASP at that folder (or any parent folders)


Why aren't my threads running?

Question: <code>// windows_procon.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <windows.h>
#include <process.h>
using namespace std;

HANDLE mutex;
HANDLE emptySlots;
HANDLE filledSlots;

#define BUFFER_SIZE 10

void *producer(void *);
void *consumer(void *);
int produceItem(void);
void printBuffer(void);

int buffer[BUFFER_SIZE];
int head = 0;
int tail = 0;

int _tmain(int argc, _TCHAR* argv[])
{
    DWORD prodThrdID, consThrdID;

    mutex = CreateMutex(NULL,FALSE,NULL);
    emptySlots = CreateSemaphore(NULL,BUFFER_SIZE,BUFFER_SIZE,NULL);
    filledSlots = CreateSemaphore(NULL,0,0,NULL);

    srand(time(NULL));

    _beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))producer,
                    0, 0, (unsigned int *)&prodThrdID);
    _beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))consumer,
                    0, 0, (unsigned int *)&consThrdID);

    return 0;
}

void *producer(void *n)
{
    int item;
    for(int i = 0; i <BUFFER_SIZE+5; i++)
    {
        WaitForSingleObject(emptySlots,INFINITE);
        WaitForSingleObject(mutex,INFINITE);

        item = produceItem();
        //printf("Producing");

        cout << "Producing: " << item << endl;
        //logfile << "Producing: "<< item << endl;
        //fprintf(logfile, "Producing: %d \n", item);
        buffer[head] = item;
        head = (head + 1) % BUFFER_SIZE;
        printBuffer();

        ReleaseMutex(mutex);
        ReleaseSemaphore(filledSlots,1, NULL);
    }
    return n;
}

void *consumer(void *n)
{
    for(int i = 0; i <BUFFER_SIZE+5; i++)
    {
        WaitForSingleObject(filledSlots,INFINITE);
        //Sleep(500);
        WaitForSingleObject(mutex,INFINITE);

        cout << "Consuming: " << buffer[tail] << endl;

        buffer[tail] = 0;
        tail = (tail + 1) % BUFFER_SIZE;
        printBuffer();

        ReleaseMutex(mutex);
        ReleaseSemaphore(emptySlots,1, NULL);
    }
    return n;
}

int produceItem(void)
{
    int x = (rand()%11 + 1);
    return x;
}

void printBuffer(void)
{
    for(int i = 0; i <BUFFER_SIZE; i++)
    {
        printf("%d ", buffer[i]);
    }
    printf("END \n");
}
</code>
My program here is supposed to be an algorithm for the producer-consumer problem. I think I have the algorithm correct my only problem is that I'm having trouble getting the threads to run properly. Can someone tell me what the issue is?
Answer: You need to wait for the threads you create with _beginthreadex to do their work, as it stands you program will exit immediately after creating them. I haven't looked any further at you logic.
Here is an example.
<code>hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
WaitForSingleObject( hThread, INFINITE );
</code>
Comment: How do I wait for them? I'm confused do I use WaitForSingleObject?

Why aren't my threads running?


Create custom field programmatically

Question: I'm trying to re-create a field in my custom form with a date-picker. A dpm of my already existing form learned me the form looks like this:

Is it correctly to assume you can create the field with following code? Because I get an empty result...
$form['my_field_field_periods'] = array(
    '#title' => t('Periode 1'),
    '#type' => 'container',
    '#attributes' => array(
      'class' => array(
        'field-type-datetime', 'field-name-field-periods','field-widget-date-popup')
    ),
    - and so on -
  );

Comment: Do you want a field api field, or a regular form api field?
Comment: A regular form api field, sorry I included a wrong tag
Answer: You can add a regular select box style date field with the form api like this:
$form['date1'] = array(
  '#type' => 'date',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
);

Drupal core doesn't have a date popup FAPI element, but you can add jQuery UI datepicker to a regular text field as well
$form['date1'] = array(
  '#type' => 'textfield',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
  '#prefix' => '
',
  '#suffix' => '
'
);

// Attach JS datepicker library and init js for textfield
$form['#attached']['library'][] = array('system', 'ui.datepicker');
$form['#attached']['js'] = array(
  drupal_get_path('theme', 'my_theme') . '/js/datepicker-init.js',
);

Then in your theme /js/datepicker-init.js
(function ($) {
  // Add calendar popup to date textfield
  Drupal.behaviors.setDatePicker = {
    attach: function(context, settings) {
      var options = {
        'dateFormat':'yy-mm-dd',
        'changeYear':true,
        'changeMonth':true
       };
      $(".datepicker-wrapper input").once('datepicker').datepicker(options);
    }
  };

})(jQuery);

The result is something like this:

Create custom field programmatically


Accessing Drupal array values

Question: I'm noobing my way through countless websites trying to find an answer to accessing a value in a Commerce field array.
I somehow managed to throw together the following code to retrieve a value for a workflow rule I'm writing:
$product_id = $current_line_item->commerce_product;

The result is: array(1) { ["und"]=> array(1) { [0]=> array(1) { ["product_id"]=> string(2) "14" } } }
I can't figure out how to get any deeper into the array than that. I need to return the product_id value in this array.
Can anyone guide me on the best way to do this?
Comment: `$product_id['und'][0]['product_id']` will get you what you need, but I don't think it's the proper/recommended way to do it.  Try this: https://drupalcommerce.org/developer-guide/utilizing-core-apis/working-entity-metadata-wrappers.  And if you can provide some more code (lines before this) it might help.
Comment: "I can't figure out how to get any deeper into the array than that." is a plain PHP question: Drupal doesn't have a special syntax to access PHP arrays. Even if you were using the proper Drupal function, you would still have an array to access. You could use the Entity API module, since that is a requirement for the Drupal Commerce module.
Comment: While researching Patrick's option below, I found here (https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way) that method is not recommended.

The author suggested using this method instead:
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);
Comment: More on the comment above...

Further research found that node_load has been deprecated in favor of EntityFieldQuery.

Would anyone be able to provide some examples of how I can use this to get the "product_id" value I'm trying to get?
Answer: Devel is super useful to help you figure out these type of things.
Once enabled, you can write dpm($product_id) and it will print out a nice organized structure of the array.  From there, you can click on any item and it will show you how you can access the item like ['und'][0]['product_id'] in your example.
Depending on what exactly you're trying to do, there may be different ways to get the info you need.
Comment: The OP knows already the array structure.
Comment: Thanks Patrick.

I prefer not to use UND to get the value as that seems to be the least recommended method from my research.

EntityFieldQuery seems to be the way to go but it's over my head right now. I'm just not clear how to format the query to get the value I need as mentioned in my original post.
Comment: @CraigL. I think you're adding a little unnecessary complexity to a simple task.  The data that you're trying to grab is already loaded - no reason to create another DB query.  If you're worried about using `"und"` because you plan on doing translations in the future, you can simply replace `"und"` with the `LANGUAGE_NONE` constant so when you do add translations, everything still works properly.

Accessing Drupal array values


margin datatable increased by itself after hiding / showing columns

Question: margin table data increased by itself after hiding / showing columns.
This result before show/hide column.

after, I show/hide 10++times

Datatable css set default
table.dataTable {
    width: 100%;
    margin: 0 auto;
}

It start from 5 it is incremented by 1 for every show or hide. after I many click finally no one stop it

my script
var table = $('#table-result').DataTable({
        responsive: true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        dom: 'Blfrtip',
        buttons: [
          {
            extend: 'collection',
            text: 'Export',
            buttons: [
                'copy',
                {
                  extend: 'excel',
                  title: titleExport
                },
                {
                  extend: 'csv',
                  title: titleExport
                },
                {
                  extend: 'pdf',
                  title: titleExport
                }
            ]
          }
        ],
        rowReorder: true,
        columnDefs: [
            { orderable: true, className: 'reorder data-table-custom-font', targets: 0 },
            { orderable: true, className: 'reorder data-table-custom-font', targets: 1 },
            { orderable: false, className: 'data-table-custom-font', targets: '_all' }
        ]
      });

and this script show/hide column
  $('button.toggle-vis').on( 'click', function (e) {
            e.preventDefault();
            // Get the column API object
            let column = table.column( $(this).attr('data-column') );
            console.log($(this).attr('data-column'))
            // Toggle the visibility
            column.visible( ! column.visible() );

          } );

Thank you. Tell me if you want something more.
Answer: My Answer set style width: 100%


Dúvida com Flex-Box CSS

Question: Estou encucado com uma questão do display flex neste trecho de código: https://jsfiddle.net/h6tgnu19/7/
Quero o box fique grudado no topo da página, independente do menu rolar ou não. Que não haja margin nenhuma. Tentei margin: 0 no elemento nav, mas não funfou.
E quanto ao box de pesquisa, não deveria estar também junto com o nav? Como faço para incluir dentro do menu?
Para finalizar. Como poderia fazer o mesmo menu usando block ou inline-block? Tentei e nunca aparecia se quer o box.
Agradecido
Answer: Você precisa tirar a margem padrão do body:
body {
    background: #f9f9eb;
    margin: 0; ← ← ← ← ← ← ← ←
}

Tire também o padding da
, que é a classe .navigation:
.navigation {
    list-style: none;
    margin: 0;
    padding: 0; ← ← ← ← ← ← ← ←
    background: #0b5eec;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row wrap;
    flex-flow: row wrap;
    justify-content: center;
}

A div que segura a sua caixa de busca está fora do nav:

   ...

   ...

Coloque no final do nav e insira no CSS os estilos para centralizar e dar uma margem superior do menu:
.search-box{
   text-align: center;
   margin-top: 15px;
}

Como fica:

body {
   background: #f9f9eb;
   margin: 0;
}

nav{
   background: #0b5eec;
}

.navigation {
   list-style: none;
   margin: 0;
   padding: 0;
   display: -webkit-box;
   display: -ms-flexbox;
   display: flex;
   -webkit-box-orient: horizontal;
   -webkit-box-direction: normal;
   -ms-flex-flow: row wrap;
   flex-flow: row wrap;
   justify-content: center;
}

.search-box{
    margin: 15px 15px 0;
}

.navigation a {
   text-decoration: none;
   display: block;
   padding: 15px;
   color: white;
}

.navigation a:hover {
   background: #000;
   text-decoration: underline;
}

                  <input name="search-box" value="Search..."/>

Index

Products

Gallery

Contact

Comment: Muito obrigado pela ajuda. Realmente esquecido de colocar a classe na div aqui no arquivo, mas não no link que passei rsrs

Bem isto mesmo no margin 0 do body. Sempre me distraio com isto.

Quando ao padding do ul não tinha percebido isto. Senão der o padding, fica um espaço no canto esquerdo. Se mudo o justify-content pra flex-end, então este padding não seria necessário, mas pro canto esquerdo é preciso.

O único problema ainda é a questão da caixa de texto de pesquisa. Quero que fique dentro do box-model dos links da u,. seja ele no canto direito ou esquerdo e não fora do contexto.
Comment: Era isso mesmo que queria como mostrado na resposta?
Comment: Quase isto. Faltou a parte apenas da caixa de texto como expliquei acima.

Quero que a caixa de pesquisa fique dentro do box model como os links. Seja ele no canto esquerdo ou direito. Ele está fora do conteúdo como se iniciasse um novo box model.
Comment: Veja agora.....
Comment: Perfeito. Muito obrigado mesmo.

Se você não se importar, poderia me explicar sobre as mudanças?
1. Você retirou o background da ul e passou pra nav;

Esqueci realmente que a caixa de texto tinha que ser inserido como elemento li.
Comment: Isso mesmo. O background deveria ser na nav e não na UL. Depois centralizei a caixa de busca e coloquei uma margem superior e à direita pra não ficar grudada aos links.
Comment: Realmente muito obrigado.

1. Você disse que o background tem que ser na nav e não na ul .Alguma explicação técnica/semântica?
2. Por fim, acho que finaliza mesmo minhas dúvidas. Se eu quiser posicionar a caixa de pesquisa para o início ou final do box como faria? Tentei modificar as margin, mas alterava a configuração dos links centrais, que não quero. Tentei o align-item para flex-start e não funcionou. Align-content não tem efeito quando o flexbox tem apenas uma linha. Alguma sugestão?
Comment: É porque o fundo azul estava apenas na UL. E isso estava afetando apenas a UL e não a nav. Vc posiciona a caixa alterando a posição da LI onde ela está. No caso do meu exemplo, eu coloque como primeira LI.

Dúvida com Flex-Box CSS


How can a cricket team batting second be automatically eliminated via NRR?

Question: I found this from Cricbuzz and other popular sports site.
I don't understand that last sentence which is "If Pakistan bowl first, they will be out of the semi-final race even before the first ball is bowled at Lord's on Friday.".
Why they can't limit Bangladesh for around 300 runs and make it using just 20 overs or something doesn't qualify for semi, even Pakistan can beat Bangladesh by 311 runs after posting 350 make them semi-final?

For Pakistan to qualify to the semi-final...
Pakistan to beat Bangladesh by 311 runs after posting 350
or
beat Bangladesh by 316 runs after scoring 400
or
beat Bangladesh by 321 runs after scoring 450
If Pakistan bowl first, they will be out of the semi-final race even before the first ball is bowled at Lord's on Friday.

Team
Played
Won
Lost
No Result
NRR

Australia
8
7
1
0
+1.000

India
7
5
1
1
+0.854

New Zealand
8
5
2
1
+0.572

England
8
5
3
0
+1.000

Pakistan
8
4
3
1
-0.792

Sri Lanka
8
3
3
2
-0.934

Bangladesh
7
3
3
1
-0.133

South Africa
8
2
5
1
-0.080

West Indies
8
1
6
1
-0.335

Afghanistan
8
0
8
0
-1.418
Answer: Before the Bangladesh match, Pakistan have scored 1710 runs from 338.5 overs and conceded 2073 runs from 303.4 overs. Even given a very unlikely scenario:

Bangladesh bat first and are all out for zero.
Pakistan score the one run they need to win without facing a legal ball (no ball, wide, etc)

Pakistan's numbers will now be 1711 runs from 338.5 for, and 2073 runs from 353.4 overs against (all out always counts as the full allocation of overs); this gives them a net run rate of 0.036, still less than New Zealand's 0.175 (the table in the question doesn't include New Zealand's loss to England which significantly reduced their NRR).
There is in theory a scenario in which Pakistan can qualify if Bangladesh bat first, but it's so ridiculously stupid that the ICC would definitely get involved:

Bangladesh score a four off every single ball in their innings, giving them 1200 runs.
Pakistan somehow score those 1200 runs without facing a legal ball - e.g. every ball is a wide and hit for four.

Pakistan now have scored 2911 runs from 338.5 overs and conceded 2973 runs from 353.4 overs. This gives them a net run rate of 0.185, above New Zealand's. (The number doesn't quite need to be 1200 runs here, but it's above 1100. Even a vaguely reasonable score like 300 doesn't get the job done).
Answer: Pakistan needs to beat Bangladesh with much more than 300 balls to spare. That is why if Bangladesh chooses to bat first, they cannot qualify as the maximum number of balls is 300.
Comment: According to https://en.wikipedia.org/wiki/Net_run_rate, I don't know how it happens.  It basically differences between the run rate you have and run rate you have given for other teams.
Comment: I think this is basically right, but this would be a much stronger answer if you could show the maths behind it.
Comment: @PhilipKendall I believe that it is too big an answer if I have to give the math about calculating NRR. The wikipedia link in the first comment, explains how it is calculated.


Function set_magic_quotes_runtime() is deprecated in phpmailer

Question: I want to embed an image with PHP Mailer version 5.1.. and my PHP version is 5.4.7
The script execution is a success, and I can receive emails with embedded images, but the problem is warnings appear like this:

Deprecated: Function set_magic_quotes_runtime() is deprecated in C:\xampp\htdocs\form\class.phpmailer.php on line 1480
Deprecated: Function set_magic_quotes_runtime() is deprecated in C:\xampp\htdocs\form\class.phpmailer.php on line 1484

and my script is is
$mail->AddEmbeddedImage('filename', 'cid', 'name');
$mail->AddEmbeddedImage('sgu_logo.gif', 'my-pics', 'sgu_logo.gif');

$mail->Body     =  "Thank you for registering at SGU. For further processing please complete a registration fee before   ". $e['testschedule']."
 For future information please contact us at sgu.ac.id/support

.";

Answer: It's because magic_quotes_runtime functions are deprecated starting from 5.3 PHP version, but 5.1 version of PHPmailer still uses them. Try to upgrade to PHPmailer 5.2, the problem should be solved, more info here: http://code.google.com/a/apache-extras.org/p/phpmailer/source/detail?r=66
Comment: Ya i know, i've solved that problem.. BTW thx antoDippo. Ur name like my minister...
Answer: The developers of the software often make updates. You can install their newest version, and it shall be without this warning.
Answer: add these code into the top of your script
@set_magic_quotes_runtime(false);
ini_set('magic_quotes_runtime', 0);

Comment: No, the [magic_quotes_runtime setting](http://php.net/manual/en/info.configuration.php#ini.magic-quotes-runtime) is deprecated, and so is its [setter](http://php.net/manual/en/function.set-magic-quotes-runtime.php).
Comment: The original question said it works but warnings appear.. using the @ symbol will supress those warnings.


htaccess 301 redirects, not sure about correct regex

Question: Can anyone help me, I am trying to sort out some redirects using htaccess but I am facing a tricky issue.
The part I cannot figure out is this: I have a system which creates 2 urls for some pages of the following pattern:
products/category (what we are using mostly and what we want, regardless of category depth)
products/subcategory/category (better for SEO maybe but not what we want)
How can I write a 301 redirect to strip out the /subcategory part of the url and redirect to the shorter version where we have in the region of 80 subcategories so I don't want to attempt this one by one. I am trying to get to grips with Regex but I am totally green with it, I am assuming matching the subcategory isn't too hard as it always follows /product and always ends with / but how do I redirect it to the shortened version.
I can't think of more information to add but if I haven't given enough detail let me know, I would love some help with this.
Thanks
Answer: Try these lines in your htaccess file :
<code>RewriteEngine on
RewriteRule ^products/[^/]+/(.+)$ /products/$1 [L,QSA,R=301]
</code>
Comment: I will give you this tutorial to regular expressions, you can reed it to understand better how regex works (it is a little long but contains everything) http://www.regular-expressions.info/tutorial.html
Comment: Oh, I should have picked up on it, this matches anything I really need it to match only "products/subcategory" not "anything/anything", I'm trying to adapt your code but struggling, any help?
Comment: I have the book mastering regular expressions, and it's great so I get some of what I see here. It's just a whole new way of looking into code. I am trying to get that first expression to only match if it ends "products" but can't figure it out.
Comment: Any help, honestly I can't see how to match it only when it contains products/ in the url.
Comment: I edited my code so that it only matches urls starting with products if thats what you need
Comment: I will check it when I am back in the office tomorrow but thanks so much for your help.


existence of solution of a degenerate pde with change of variables

Question: I am looking at the pde $$u_t=x^2u_{xx},\; x\in [0,\infty) ,\; t\in (0,T], \; u(0,x)=u_0(x)$$ This is a degenerate pde with a diffusion coefficient which is not bounded from 0, so I can't apply the classic theory of existence and uniqueness since the operator is not uniformly parabolic. However, I can do change of variables as $y=ln(x)$ and arrive at another pde: $$v_t=v_{yy}-v_y,\; y \in (-\infty, +\infty),\; t\in (0,T],\; v_0(y)=u_0(e^y)$$ Now there is no degeneracy and I can state the existence of function $v=v(t,y)$. Thus, I claim that $u(t,x)$ exists as well, however only for $x\in (0,\infty)$(Question 1: What about $x=0$? Does the function exist there, can we additionally define it?).
Question 2: Is that a right line of thought? So, as long as I can find change of variables s.t. it produces non degenerate pde I obtain the existence for the degenerate pde? What should I be careful about?
Answer: $x=0$ corresponds to the limit $y \to -\infty$.  Does your solution $v(y,t)$ have a limit as $y \to -\infty$?  That's a bit of a delicate question.  However, note that if $v(t,y) = e^{y/2 - t/4} V(t,y)$ the equation for $V$ is the classical heat equation:
$\dfrac{\partial V}{\partial t} = \dfrac{\partial^2 V}{\partial x^2}$.  If, for example, $V(0,y)$ is bounded, then $V(t,y)$ has the same bound for all $t > 0$, and $v(t,y) \to 0$ as $y \to -\infty$ for any fixed $t > 0$.
EDIT: actually it would have been better, I think, to use a different transformation:
$v(t,y) = w(t,z)$ where $y = z + t$ so you get $$ \frac{\partial w}{\partial t} = \frac{\partial^2 w}{\partial z^2}$$
and $\lim_{y \to -\infty} v(t,y) = \lim_{z \to -\infty} w(t,z)$.
But I doubt that there will always be a transformation that will act so nicely.
Comment: my original function was defined on $[0,\infty)$, so I want that function to exist there, but for the transformed function this value corresponds to the limit in $y$. However, with a change of variables you have provided it looks like we just set the value to be 0 there and thus obtain the existence for all $x$. So, I wonder then why there so much literature about degenerate equations and issues of existence, can't you always find some suitable change of variables to perform transformation to the "good" parabolic equation? What are possible consequences?
Comment: In fact, if I understand correctly, for the equation $a(x)u_{xx}=u_t$ boundedness from $0$ of the diffusion coefficient is very important as the formula of the fundamental solution has the lower bound in the denominator. So, if there is no lower boundary the fundamental solution blows up? Does it imply anything about the solution itself? As pointed out above with change of variables we can find a perfectly fine solution. So, if the fundamental solution behaves "bad", is that a sign of issues on existence or it doesn't really matter much?
Answer: Let $u(t,x)=T(t)X(x)$ ,
Then $T'(t)X(x)=x^2T(t)X''(x)$
$\dfrac{T'(t)}{T(t)}=\dfrac{x^2X''(x)}{X(x)}=-\dfrac{4s^2+1}{4}$
$\begin{cases}\dfrac{T'(t)}{T(t)}=-\dfrac{4s^2+1}{4}\\x^2X''(x)+\dfrac{4s^2+1}{4}X(x)=0\end{cases}$
$\begin{cases}T(t)=c_3(s)e^{-\frac{t(4s^2+1)}{4}}\\X(x)=\begin{cases}c_1(s)\sqrt{x}\sin(s\ln x)+c_2(s)\sqrt{x}\cos(s\ln x)&\text{when}~s\neq0\\c_1\sqrt{x}\ln x+c_2\sqrt{x}&\text{when}~s=0\end{cases}\end{cases}$
$\therefore u(x,t)=C_1e^{-\frac{t}{4}}\sqrt{x}\ln x+C_2e^{-\frac{t}{4}}\sqrt{x}+\int_0^\infty C_3(s)e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\sin(s\ln x)~ds+\int_0^\infty C_4(s)e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds$
$u(0,x)=u_0(x)$ :
$C_1\sqrt{x}\ln x+C_2\sqrt{x}+\int_0^\infty C_3(s)\sqrt{x}\sin(s\ln x)~ds+\int_0^\infty C_4(s)\sqrt{x}\cos(s\ln x)~ds=u_0(x)$
$C_1\ln x+C_2+\int_0^\infty C_3(s)\sin(s\ln x)~ds+\int_0^\infty C_4(s)\cos(s\ln x)~ds=\dfrac{u_0(x)}{\sqrt{x}}$
$\int_0^\infty C_4(s)\cos(s\ln x)~ds=\dfrac{u_0(x)}{\sqrt{x}}-C_1\ln x-C_2-\int_0^\infty C_3(s)\sin(s\ln x)~ds$
$\int_0^\infty C_4(s)\cos xs~ds=e^{\frac{x}{2}}u_0(e^x)-C_1x-C_2-\int_0^\infty C_3(s)\sin xs~ds$
$\mathcal{F}_{c,s\to x}\{C_4(s)\}=e^{\frac{x}{2}}u_0(e^x)-C_1x-C_2-\mathcal{F}_{s,s\to x}\{C_3(s)\}$
$C_4(s)=\mathcal{F}^{-1}_{c,x\to s}\{e^{\frac{x}{2}}u_0(e^x)\}+C_1\delta'(s)-C_2\delta(s)-\mathcal{F}^{-1}_{c,x\to s}\{\mathcal{F}_{s,s\to x}\{C_3(s)\}\}$
$\therefore u(x,t)=C_1e^{-\frac{t}{4}}\sqrt{x}\ln x+C_2e^{-\frac{t}{4}}\sqrt{x}+\int_0^\infty C_3(s)e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\sin(s\ln x)~ds+\int_0^\infty\mathcal{F}^{-1}_{c,x\to s}\{e^{\frac{x}{2}}u_0(e^x)\}e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds+\int_0^\infty C_1\delta'(s)e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds-\int_0^\infty C_2\delta(s)e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds-\int_0^\infty\mathcal{F}^{-1}_{c,x\to s}\{\mathcal{F}_{s,s\to x}\{C_3(s)\}\}e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds=C_1e^{-\frac{t}{4}}\sqrt{x}\ln x+C_2e^{-\frac{t}{4}}\sqrt{x}+\int_0^\infty C_3(s)e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\sin(s\ln x)~ds+\int_0^\infty\mathcal{F}^{-1}_{c,x\to s}\{e^{\frac{x}{2}}u_0(e^x)\}e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds-C_1e^{-\frac{t}{4}}\sqrt{x}\ln x-C_2e^{-\frac{t}{4}}\sqrt{x}-\int_0^\infty\mathcal{F}^{-1}_{c,x\to s}\{\mathcal{F}_{s,s\to x}\{C_3(s)\}\}e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds=\int_0^\infty\mathcal{F}^{-1}_{c,x\to s}\{e^{\frac{x}{2}}u_0(e^x)\}e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds+\int_0^\infty C_3(s)e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\sin(s\ln x)~ds-\int_0^\infty\mathcal{F}^{-1}_{c,x\to s}\{\mathcal{F}_{s,s\to x}\{C_3(s)\}\}e^{-\frac{t(4s^2+1)}{4}}\sqrt{x}\cos(s\ln x)~ds$
The function not only exist for at least $x\in(0,\infty)$ , but also has one arbitrary function left.
To determine whether the function exist at $x=0$ or not, we just need to consider $\lim\limits_{x\to0}\sqrt{x}\sin(s\ln x)$ and $\lim\limits_{x\to0}\sqrt{x}\cos(s\ln x)$ .
Since both $\sin(s\ln x)$ and $\cos(s\ln x)$ are bounded,
$\lim\limits_{x\to0}\sqrt{x}\sin(s\ln x)=0$ and $\lim\limits_{x\to0}\sqrt{x}\cos(s\ln x)=0$
So the function not only also exist at $x=0$ , but also equals to $0$ when $x=0$ .
Comment: thanks for the detailed answer, however I was interested in the theory behind possible change of variables. I expected the solution to exist, so I just considered a simple example. I wanted to know if it is true in general, that is if the existence for the function with changed variables is equivalent to the existence of the original function.
Comment: The aims of changing variables of the equations are transforming the equations to the different forms, so the properties of the transformed equations should be equivalent to that of the original equations, otherwise they should be unreasonable or contradictious. The only things between the original equations and the transformed equations are the easiness of determining the properties.
Comment: even for the regularity properties? Because when I think of the first derivative, for example, $u_x=v_y*y_x$, so even if new function $v$ is perfectly smooth, $y_x$ might destroy the smoothness of the original problem, or am I wrong?


Is there a way to obtain information about the instrument to which a Logic Pro X Script is attached?

Question: Is it possible for a Logic Pro X midi script to query information about the instrument to which it is attached? For example, find out if it is transposed or has a particular midi range filter?  I have been all through the Apple documentation on the scripter and just don't see that this is possible. https://support.apple.com/en-md/guide/logicpro/lgce728c68f6/mac
Answer: Can Scripter plug-in of Logic Pro X query information about the instrument of its channel strip?

NO

Scripter is a built-in MIDI FX plug-in of Logic Pro X.
MIDI FX are plug-ins inserted in software instrument channel strips that process or generate MIDI data —played from a MIDI region or a MIDI keyboard— in real time.
MIDI plug-ins are connected in series before the audio path of a software instrument channel strip and hence act as a modulator (using MIDI/CC/PC data) for various parameters of a software instrument.

As the signal flow is simplex (one directional), Scripter cannot query information about instrument.
Comment: Thanks, this makes sense technically.  It would be neat if the script could at least see the track name (and/or the MIDI name), which I imagine exists somewhere "above" the scripter intake? Then a single script could behave a little differently for different instruments.


$L^p$ Norm of product of two bounded functions

Question: If $f$ and $g$ are bounded functions in $L^p[a,b]$, does the following inequality hold in $L_p$ spaces?
$$\|fg\|_p\leq\|f\|_p\|g\|_p$$
Comment: No. Counterexample for $p=1$: let $f(x) = g(x) = x$ on the interval $[0,1]$. Then $\|fg\|_1 = 1/3$ whereas $\|f\|_1 \|g\|_1 = 1/4$.
Comment: is there any possibility for$ L^2[a,b]$?
Comment: Again using $f(x) = g(x) = x$ on the interval $[0,1]$, we have $\|fg\|_2 = 1/\sqrt{5}$, whereas $\|f\|_2 \|g\|_2 = 1/3$.
Answer: Let $\varepsilon$ be smaller than $\min\{b-a,1\}$ and $f(x)=g(x):=\mathbf 1_{[a,a+\varepsilon]}(x)$. Then
$$\lVert fg\rVert_p=\left(\int_{[a,b]}\mathbf 1_{[a,a+\varepsilon]}(x)\right)^{1/p}=\varepsilon^{1/p}$$
and
$$\lVert f\rVert_p\lVert g\rVert_p=\varepsilon^{2/p}.$$


Date format change SSRS

Question: I have a view with a date column with this format :  YYYY-MM-DD and I am using that column in a SSRS report but the final user wants to have something like this:

December 31, 2018

I am using this expression:
=FormatDateTime(Parameters!prmReportDate.Value,DateFormat.LongDate)

But I am getting this:

Monday December 31, 2018

I don't need the day.  Is there a way to remove it?
Answer: You could simply format the textbox as a date and specify the correct format.  You'll just need to set the expression in the textbox as:
=Parameters!prmReportDate.Value

And you should be able to set the Number format property as:

And this should give you the output you expect.  If it doesn't work as expected(which actually seems to be the case as I test it), should be able to apply the following expression:
=Format(Parameters!prmReportDate.Value, "MMMM dd, yyyy")

Just remove one of the ds from the expression to remove a leading zero on single digit dates.
Answer: Try something like this:
=MonthName(Month(Parameters!prmReportDate.Value),false)
& " " &
day(Parameters!prmReportDate.Value)
& "," &
year(Parameters!prmReportDate.Value)

Comment: I mean, that works but why get so complicated and hard code it like that?  Just seems unnecessary considering the alternatives.

Date format change SSRS


PHP XPath and Line Numbers

Question: The following xpath works, but how can i get the line number at which the xpath finds the p element with class 'blah'?
<?php
$doc = new DOMDocument();
$doc->loadHTML('

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

some text here

');
$xpath = new DOMXPath($doc);
$xpath_query = "//*[contains(@class, 'blah')]";
?>

Answer: XPath and DOM have no concept of a line number. They only see nodes, and the linkages between them.
The DOM object itself may have some internal metadata which can relate a node back to which line it was on in the source file, but you'd have to rummage around inside the object and the DOM source to find out. Doesn't seem to be anything mentioned at http://php.net/dom.
Alternatively, if the node you're looking at, and/or the surrounding HTML is fairly/totally unique in the document, you could search the raw html for the matching HTML text of the node and get a line number that way.
Comment: Cheers Marc, guess i'll have to go with search raw html.

PHP XPath and Line Numbers


How do I find the optimal values for $\beta$ and $\beta_0$ for sparse linear regression model? Where does the mean of $\lambda$ come into account?

Question: If someone could point me in the right direction that would be greatly appreciated!
Consider the sparse linear regression model:
$\min_{\beta_{0},\beta} \left \{ \frac{1}{2}\left \| \beta _{0}e + X\beta -y \right \|^{2} +\lambda\left \| \beta\right \|_{1}+\frac{\mu}{2}\left \| \beta  \right \|^2\right \}$,
where $\mu \ge 0$ and $\lambda > 0$ are the parameters, and $e$ is the all-ones vector.
Let $\bar{\lambda} = \left \| X^{^{T}} \left ( \frac{e^{T}y}{n}e-y \right )\right \|_{\infty}$ Show that $\left ( e^{T}y/n,0 \right )$ is an optimal solution of the model for any $\lambda \geq \bar{\lambda}$
Comment: It should be "$\lambda \geq \bar\lambda$", not vice versa. And here $\bar\lambda$ is the value you've defined, not the mean.
Comment: Symbols mean whatever you define them to be.  $\bar \lambda$ is explicitly defined after the word "Let."
Comment: Yes, you are correct. Also, I thought the line above lambda denotes the mean?
Answer: This answer uses the notion of subgradients (see e.g. these notes [PDF]).
The subgradient is
$$\begin{bmatrix}e & X \end{bmatrix}^\top (\beta_0 e + X \beta - y) + \lambda \partial(\|\beta\|_1) + \mu \beta. \tag{$*$}$$
where $\partial(\|\beta\|_1)$ is the set of vectors $(v_0, v)$ satisfying $v_0=0$ and $v_i \in \begin{cases} \{1\} & \beta_i > 0 \\ \{-1\} & \beta_i < 0 \\ [-1, 1] & \beta_i = 0 \end{cases}$ for $i \ne 0$. The above set ($*$) is this set $\partial(\|\beta\|_1)$ scaled by $\lambda$ and shifted by
$\begin{bmatrix}e & X \end{bmatrix}^\top (\beta_0 e + X \beta - y) + \mu \beta$.
A $\beta$ is optimal if $0$ lies in the above set ($*$).

When $\beta_0=e^\top y / n$ and $\beta = 0$, the above set ($*$) becomes
$$\begin{align}
&\begin{bmatrix}e & X \end{bmatrix}^\top \left(\frac{e^\top y}{n} e - y\right) + \lambda (\{0\} \times [-1, 1] \times \cdots \times [-1, 1])
\\
&= \begin{bmatrix}0 \\ X^\top \left(\frac{e^\top y}{n} - y\right)\end{bmatrix} + \lambda (\{0\} \times [-1, 1] \times \cdots \times [-1, 1]).
\end{align}$$
where we have used the fact $e^\top e=n$.
For $0$ to lie in this set is the same as asking that every element of $X^\top \left(\frac{e^\top y}{n} - y\right)$ lies in $[-\lambda, \lambda]$. This is precisely the given condition involving $\bar{\lambda}$.
Comment: How do you get the subgradient of $\frac{1}{2}\left \| \beta _{0}e + X\beta -y \right \|^{2}$ to be $\left [ e,X \right ]^{T} \left ( \beta_0e + X\beta -y \right )$. I understand how the L1 norm subgradient is determined
Comment: @JeromyTrujillo If you are familiar with how the gradient of $\frac{1}{2} \|A \gamma - y\|^2$ w.r.t. $\gamma$ is $A^\top (A\gamma - y)$, then just note that $\beta_0 e + X \beta = \begin{bmatrix} e & X \end{bmatrix} \begin{bmatrix} \beta_0 \\ \beta \end{bmatrix}$ and think of this as $A \gamma$.


How to set applicationID using Android.mk

Question: I have a custom rom based on AOSP and I have intend to make App on a system app that is based on Launcher3.
I would like to change App's packageName(or applicationID) from specified in a manifest.
I can change appliationID when build by gradle.
But I don't know how to set applicationID using Android.mk.
How to set applicationID using Android.mk?
Update:
I want to set applicationID using Android.MK like I set to applicationID using build.gradle.
Answer: I don't think there is a way ( at least that I know of ) to specify applicationId on the makefile.
You can always try to replicate what gradle does, which is changing the package field in AndroidManifest as the last step of the build ( after R class generation is already done with original package name field )
Read more on: https://developer.android.com/studio/build/application-id

One more thing to know: Although you may have a different name for the
  manifest package and the Gradle applicationId, the build tools copy
  the application ID into your APK's final manifest file at the end of
  the build. So if you inspect your AndroidManifest.xml file after a
  build, don't be surprised that the package attribute has changed. The
  package attribute is where Google Play Store and the Android platform
  actually look to identify your app; so once the build has made use of
  the original value (to namespace the R class and resolve manifest
  class names), it discards that value and replaces it with the
  application ID.
Answer: Application package name can be change in AndroidManifest.xml and your application classes.
Android.mk doesn't contain any package name or ApplicationID. it contains your module name to include in source code and add it to build configs.
ApplicationID should set in gradle filer
Comment: I understand about packageName.Cannot set applicationID using Android.mk?


A formal definition of the average and median functions.

Question: In most probability and statistics books, the average of a sequence of numbers is not stated in a formal way. Neither is the median. So, my question is this. Let $S$ be the set of all non-empty finite sequences of real numbers. How does one formally define the functions $average: S \rightarrow \mathbb{R}$ and $median: S \rightarrow \mathbb{R}$?
Comment: What do you mean?  The average of $\{s_i\}_{i=1}^n=\frac 1n\times \sum s_i$.  The median is the middle number if $n$ is odd (and the $s_i$ are in order $s_1≤s_2≤\cdots ≤s_n$). an it is the average of the two middle numbers if $n$ is even.  Was there some particular situation you were concerned about?
Answer: I don't like using the word "average," so I assume you're referring to the arithmetic mean.
In $S$ (which you have specified as a set of all non-empty finite sequences of real numbers), consider an arbitrary sequence of some integer length $0 < n < \infty$, say $s_1, \dots, s_n$. Then the arithmetic mean $a: S \to \mathbb{R}$ is defined by
$$a(s_1, \dots, s_n) = \dfrac{1}{n}\sum_{i=1}^{n}s_i\text{.}$$
Now for the median - suppose we order the sequence $s_1, \dots, s_n$ in ascending order, yielding values $s_{(1)}, \dots, s_{(n)}$ so that $s_{(1)} \leq \cdots \leq s_{(n)}$. (These are known as order statistics.) Then the median $m: S \to \mathbb{R}$ is defined as follows:
$$m(s_1, \dots, s_n) = \begin{cases}
s_{\left(\frac{n+1}{2} \right)}, & n \text{ odd} \\
\frac{1}{2}\left[s_{(n/2)}+s_{(n/2 + 1)}\right], & n \text{ even.}
\end{cases}$$


Drupal commerce - passing attributes from one module to other

Question: Firstly I am new to Drupal commerce and start learning it on the job as required. So if you see my question as basic functionality in Drupal commerce, please pardon me.
Question: I have a simple commerce site and it look like as follows: Product view -- Shopping cart -- checkout
After checkout, I am adding a new custom module(creating an account for the user and few other things). I need to get the attributes of the product from the shopping cart module. How can I retrieve that information from the shopping cart module to the new custom module that I am building.
Thanks in advance.
Comment: You might also want to consider storing non-sensitive variables such as product nodes in a SESSION variable and that way you can access them across page loads.
Answer: We already have a rule shipped with the drupal commerce core, which creates the user account on checkout process. It might be a good starting point for you in both ways how it is looping through order information to use in your custom module or you can modify the rule as per your requirement.
Rule is "Create a new account for anonymous user."


When should I grab a bag of money?

Question: 100 small bags of coins are placed in a large cauldron. The 99 of these bags that contain pennies have the same size. The single small bag of quarters is twice the size of a single bag of pennies. The probability of grabbing each bag is proportional to its size.
100 people get to each randomly grab a bag from this cauldron. If I want to grab the bag of quarters, when I should I grab a bag? For instance, should I do it first? Second? Last?
My current hunch is that it does not matter. After all, the bags are randomly distributed, so this scenario should be no different from someone just randomly distributing all the bags at the same time. Is this reasoning sound?
Answer: If this reasoning were sound, all 100 people should have the same probability $1/100$ of getting the bag of quarters. But the probability for the first person who grabs a bag is easy to calculate; it's $2/101\ne1/100$.
The probability for the $n$-th person to get the bag of quarters is
$$
\frac{99}{101}\cdot\frac{98}{100}\cdot\dotso\cdot\frac{101-n}{103-n}\frac2{102-n}\;,
$$
so the ratio of successive probablities is
$$
\frac{101-n}{102-n}\lt1\;,
$$
so the probability is highest for the first person.
Comment: +1 By the way, this problem is a good example of [Wallenius non-central hypergeometric distribution](http://en.wikipedia.org/wiki/Wallenius%27_noncentral_hypergeometric_distribution).

When should I grab a bag of money?