Basic question but what is the best way to compare averages?

Question: Fairly basic math question so apolgies.. say i have the following clusters, i calculate the avrage across all clusters so it's 363.33(100+450+540), would it then make sense to do the calculation 100-avg, 450-avg, 540-avg to see how above or below each segment is above average?
Just wondering what best way is to compare the spend. Is it not e.g. row 2 did 450-363.33 better than average, does such a statement make sense. Should i divide by standard deviation of the column and compare the z scores?
Answer: It is hard to tell what you are doing, so I will make an assumption that "CHASERS", "DEALERS", and "RICH" each stand for one unit.
Yes, it would make sense to say that "CHASERS" was \$263.33 below average and that the other two were above average. You also can calculate the z-score by dividing that value by the standard deviation of those three numbers, giving you a z-score of $-0.6983416$. With so few observations, I have difficulty interpreting this, but a z-score should give some idea of how far from the mainstream of the rest of the data a given point is.
Comment: I'm not sure that the z-score helps you much. You have a clear interpretation that if a group spends $\$263.33$ less than average, the group spends $\$263.33$ less than average. What does it mean to be $0.6983416$ standard deviations below average? Sure, you can calculate that it means the group is $\$263.33$ below average, but you already know that.
Comment: CHASERS, DEALRES etc are the name of the segments, so for example the amount is the total amount people in that segment have spent who have been classed as that
Comment: What I wrote makes sense if you are interested in the three groups. If you are interested in the people who make up the groups, then the problem is harder, particularly if you don't have more data (subject-level rather than group-level).
Comment: thanks i guess using the zscore would be ideal, but my complete number of groups is only 7, so would it not be unreliable


Error, Lcobucci\JWT\Signer\InvalidKeyProvided: It was not possible to parse your key

Question: I hope you are doing fine. I was working on Oauth passport laravel, it was working fine on my previouse machine but i had to switch machines.My new machine has php 8 and my laravel project is of 7.30.0 version and my lcobucci/jwt version is 3.3.3. When i try to hit register route on postman i get the following error
Lcobucci\JWT\Signer\InvalidKeyProvided: It was not possible to parse your key, reason:  in file C:\Users\user\Documents\GitHub\myproject\vendor\lcobucci\jwt\src\Signer\InvalidKeyProvided.php on line 17
Answer: As you can see on https://packagist.org/packages/lcobucci/jwt#3.3.3, that JWT package is officially not compatible with PHP 8. You should upgrade it to a compatible version (at least v4), or downgrade your PHP version to v7
Answer: This is coming super late.
For anyone still experiencing this, just generate a new jwt secret.
This command will generate a new key that fits the new requirement
php artisan jwt:secret
Comment: The error I encountered with is "Lcobucci\JWT\Signer\InvalidKeyProvided  Key cannot be empty." And running above command resolved the error.
Answer: I'm using ronvanderheijden/openid-connect, the plugin is develop based on lcobucci/jwt and laravel passport, and I met the same issue ,too.
In my case, I found that problem is, lcobucci/jwt use key path to get oauth-private.key for issuing token, when you had set private key in .env file, the key path could not be found.
so, just set the private key in storage/oauth-private.key, it works for me.


Notes with special sound effect

Question: Please refer to this video on YouTube for this question.
There are certain passages on the right hand the played notes seemed to have some special effect.
Am I right?  If so, how do you tell from the sheet music.
I personally like the sound without that special effect better.
Comment: I'm voting to close this question because the subject matter — identifying an "effect" — is off-topic here. The question could instead be asked on SE Music Fans, but would need to be rewritten to include more information. The help pages on that site will explain what more is needed.
Answer: The video has a string sound doubling the right hand piano line. From about 1:21 the string sound changes to oboe. There's nothing in the notated music to indicate this.
Comment: @user1079505 Or the video of the hands was computer generated :)
Comment: @EmilyJ Two possibilities: either she's using a foot pedal to switch sounds, or (more likely) the audio is pre-recorded and the video is of her miming to the audio.
Comment: @EmilyJ there are other possibilities, e.g. piano was recorded as MIDI and then edited, or patch changes were pre-recorded, or someone else was changing them...
Comment: At beginning 0:05, how did she change the instrument  with both hands visible on the piano keys as you can see.

Notes with special sound effect


Javascript update functions

Question: I'm getting into game developing online. I am trying to make an online FPS game, and I've only gotten to the point where I need to update my character. I am trying to keep my code simple, using only a draw and update function. When the html loads, I execute both: (Is this necessary?)

The draw function draws the player to the screen, and the update is supposed to check for a keypress to move the character. I am trying to make the script update using this:
function UPDATE()
{
    update = setInterval(UPDATE, 60);
}

and to my knowledge, it is working fine because when I try and edit code in my online IDE (c9.io) which I use to test the site, it freezes when the site is running. I am also calling eventListeners in the draw function. (Is this proper if I want to test for a key down every frame?)
function DRAW()
{
    window.addEventListener('keydown', function (e) {
        keys.keys = (keys.keys || []);
        keys.keys[e.keyCode] = true;
    });
    window.addEventListener('keyup', function (e){
        keys.keys[e.keyCode] = false;
    });
}

My questions are:

Is there an easier way to make a script update every frame?
Is there    a JavaScript addon (like Three.js) I can use to make
developing this    easier on myself?

Any knowledge is greatly appreciated.
Answer: This makes everything crash:
function UPDATE()
{
    update = setInterval(UPDATE, 60);
}

You are recursively creating a new interval every 60ms; the first time you call UPDATE, you create an interval that creates a new interval every 60ms. All newly create intervals do the same. Don't really know what you actually want to do here.

I am also calling eventListeners in the draw function. (Is this proper
  if I want to test for a key down every frame?)

It's fine to create eventlisteners in the draw function, provided you only call this function once. Which I guess you don't. Each time you call DRAW() a new set of eventlisteners will be added, and you really don't want that.
What you need is a form of game loop. Explaining how to create an FPS game is a bit more than I can do, but you can start by looking at this article Anatomy of a video game
Comment: DRAW() should only be calling once in the  part of the HTML (to my knowledge), thanks for the info on the setInterval though. I knew it was crashing it, I just couldn't figure out why. I'll check on the article
Comment: @TaylorBrown Think of it as equivalent to a nuclear chain reaction. After running for just 960ms you already have 65536 intervals running in parallell, and it just keeps on doubling every 60ms. Your computer can't handle that, and the browser crashes.
Comment: Good analogy, makes a lot more sense now.

Javascript update functions


Can someone prove this inequality?

Question: I am trying to prove the following inequality, but I cannot.
Can someone help me?
I'll appreciate any small hints.
$$
\sum_{k=2}^{n-1}k\log_2k \le \frac12 n^2 \log_2n - \frac18 n^2
$$
Comment: I think you try induction first and see some properties through it, then you rework the proof.
Comment: you mean, mathematical induction? 1. base 2. assume k 3. k+1? okay thank you!!
Comment: Note that $\int x \log_2(x) dx = \frac{x^2\log(x)}{2} -\frac{x^2}{4} + C$

The asymptotic expansions  using [Euler-Maclaurin formula](https://en.wikipedia.org/wiki/Euler%E2%80%93Maclaurin_formula) should be useful here.
Comment: Thank you for a good idea.
Answer: hint:
Follow the professor's hint and the above comment: $\displaystyle \sum_{k=2}^{n-1} k\log_2k\leq \displaystyle \int_{2}^n x\log_2xdx$. The right side should come out from this.
Comment: Thank you very much. I got a lot of help.
Answer: I am really appreciate many hints and advice.
Thanks to them, I could success proving this proposition state.

Prove that
$$
\sum_{k=2}^{n-1}k\log_2k \le \frac12n^2 \log_2n-\frac18n^2
$$

Proof:
\begin{align*}
\sum_{k=2}^{n-1} k \log_{2}{k} &\le \int_{2}^{n} x \log_{2}{x} {dx}\\
&=\left[\frac{x^2}{2}{\log_2x}\right]_{2}^{n} - \int_{2}^{n} \frac{x^2}{2}\frac{1}{x\ln2}dx\\
&=\left[\frac{x^2}{2}{\log_2x}\right]_{2}^{n} - \int_{2}^{n} \frac{x}{2\ln2}dx\\
&=\left[\frac{x^2}{2}{\log_2x}\right]_{2}^{n} - \left[\frac{x^2}{4\ln2}\right]_{2}^{n}\\
&=\left[\frac{x^2}{2}{\log_2x} - \frac{x^2}{4\ln2}\right]_{2}^{n}\\
&=\left[\frac{n^2}{2}{\log_2n} - \frac{n^2}{4\ln2}\right] - \left[2 - \frac{1}{\ln2}\right]\\
&=\frac{1}{2}{n^2}{\log_2n} - \frac{n^2}{4\ln2} - 2 + \frac{1}{\ln2}\\
&=\frac{1}{2}{n^2}{\log_2n} - \frac{1}{8}n^2\left(\frac{2}{\ln2}+\frac{16}{n^2}-\frac{8}{n^2\ln2}\right)
\end{align*}

\begin{align*}
\frac{2}{\ln2}+\frac{16}{n^2}-\frac{8}{n^2\ln2} &\ge 1\\
\frac{2n^2+16\ln2-8}{n^2\ln2} &\ge 1\\
2n^2+16\ln2-8 &\ge n^2\ln2\\
(2-\ln2)n^2 &\ge 8(1-2\ln2) = 8\left(\ln\frac{e}{4}\right)\\\\\\
\therefore \frac{2}{\ln2}+\frac{16}{n^2}-\frac{8}{n^2\ln2} &\ge 1\\
\big(\because (2-\ln2)n^2 &\gt 0 , \ \ \  8\left(\ln\frac{e}{4}\right) \lt 0\big)
\end{align*}

\begin{align*}
\sum_{k=2}^{n-1}k\log_2k &\le \int_{2}^{n} x \log_{2}{x} {dx}\\
&= \frac{1}{2}{n^2}{\log_2n} - \frac{1}{8}n^2\left(\frac{2}{\ln2}+\frac{16}{n^2}-\frac{8}{n^2\ln2}\right)\\
&\le \frac12n^2 \log_2n-\frac18n^2
\end{align*}
Answer: Try bounding the sum by an integral.  Note that $k \log_2 k$ is an increasing function on $[2,\infty)$
Comment: can you explain a liitle more about the bounding sum by an integral? you meean $\displaystyle\int_a^bf(x)dx$ ?
Answer: Summation by parts gives:
$$ \sum_{k=1}^{n}k\log_2 k = \frac{n(n+1)}{2}\log_2(n) - \sum_{k=1}^{n-1}\frac{k(k+1)}{2}\left(\log_2(k+1)-\log_2(k)\right) $$
but since $\log_2(1+x)$ is a concave function on $[0,1]$, we have:
$$ \sum_{k=1}^{n}k\log_2 k \leq \frac{n(n+1)}{2}\log_2(n)-\sum_{k=1}^{n-1}\frac{k+1}{2} $$
hence:

$$ \sum_{k=2}^{n-1}k\log_2 k \leq \frac{n(n-1)}{2}\log_2(n) - \frac{(n+2)(n-1)}{4}.$$

Can someone prove this inequality?


What does Theta mean?

Question: I am a newbie to statistics and found this.

In statistics, θ, the lowercase Greek letter 'theta', is the usual
  name for a (vector of) parameter(s) of some general probability
  distribution. A common problem is to find the value(s) of theta.
  Notice that there isn't any meaning in naming a parameter this way. We
  might as well call it anything else. In fact, a lot of distributions
  have parameters which are usually given other names. For example, it
  is common use to name the mean and deviation of the normal
  distribution μ (read: 'mu') and deviation σ ('sigma'), respectively.

But I still don't know what that means in plain English?
Comment: $\theta$ is just a mathematical symbol and means different things in different contexts. Sometimes $\theta$ is used to refer to a parameter to be estimated but there is no real answer to the question "What is $\theta$?". That's like asking "What is the letter A?". Your link even hints at this when it says *"Notice that there isn't any meaning in naming a parameter this way. We might as well call it anything else."*.
Comment: Most of us would take this quotation to be extremely plain English, indeed, but to make any progress we have to accept that the question is *not* about how to read English. What, then, could it be about? I submit that it is asking us to explain the *technical terms* in the quotation: the ones with which we are so familiar that we no longer see how strange they might be to the statistically uninitiated. This calls for us to address the meanings of *distribution* and *parameters* (of a distribution that is; *not* of a fitted curve or other deterministic model).
Comment: Its just a way to name a statistical parameter(which defines the distribution of the quantity associated with this 'parameter') with   a special letter (other than English letters).
Answer: It is not a convention, but quite often $\theta$ stands for the set of parameters of a distribution.
That was it for plain English, let's show examples instead.
Example 1. You want to study the throw of an old fashioned thumbtack (the ones with a big circular bottom). You assume that the probability that it falls point down is an unknown value that you call $\theta$. You could call a random variable $X$ and say that $X=1$ when the thumbtack falls point down and $X=0$ when it falls point up. You would write the model
$$P(X = 1) = \theta \\
P(X = 0) = 1-\theta,$$
and you would be interested in estimating $\theta$ (here, the proability that the thumbtack falls point down).
Example 2. You want to study the disintegration of a radioactive atom. Based on the literature, you know that the amount of radioactivity decreases exponentially, so you decide to model the time to disintegration with an exponential distribution. If $t$ is the time to disintegration, the model is
$$f(t) = \theta e^{-\theta t}.$$
Here $f(t)$ is a probability density, which means that the probability that the atom disintegrates in the time interval $(t, t+dt)$ is $f(t)dt$. Again, you will be interested in estimating $\theta$ (here, the disintegration rate).
Example 3. You want to study the precision of a weighing instrument. Based on the literature, you know that the measurement are Gaussian so you decide to model the weighing of a standard 1 kg object as
$$f(x) = \frac{1}{\sigma \sqrt{2\pi}} \exp \left\{ -\left( \frac{x-\mu}{2\sigma} \right)^2\right\}.$$
Here $x$ is the measure given by the scale, $f(x)$ is the density of probability, and the parameters are $\mu$ and $\sigma$, so $\theta = (\mu, \sigma)$. The paramter $\mu$ is the target weight (the scale is biased if $\mu \neq 1$), and $\sigma$ is the standard deviation of the measure every time you weigh the object. Again, you will be interested in estimating $\theta$ (here, the bias and the imprecision of the scale).
Comment: +1 FWIW, I recently posted a worked example along the same lines at http://stats.stackexchange.com/a/34894. Although it would be misleading to construe it as "plain English"--it does not shy from using technical terms--I made an effort to explain as clearly and briefly as possible what is going on, what assumptions are made, and how one works with a parameterized family of distributions to produce an estimate based on data. For some, this might be an informative adjunct to your answer here.
Comment: Great answer! I am confused when you state the scale is biased if mu != 1, though.  In fact, upon "normalizing", the standard normal distribution becomes x ~ N(0, 1).  Or, in English, the mu = 0 and the variance = 1.  See e.g., http://en.wikipedia.org/wiki/Normal_distribution#Standard_normal_distribution
Comment: I just mean that the instrument has a bias if it indicates something else than 1 kg when it measures a 1 kg object. Perhaps the word "scale" is confusing. Here it just designates the instrument.
Comment: I had no idea why would one throw a thumbtack, but then I saw [How to Throw Push Pins like a NINJA!!!](https://youtu.be/71B75mfKEww?si=aijssGuz2073-kM8&t=46)
Comment: Good point. I used a thumbtack and not a coin because nobody really knows the probability that it lands point down. This is what justifies the introduction of the parameter $\theta$ (it makes little sense to introduce a parameter if you know that the probability is 1/2).
Answer: What $\theta$ refers to depends on what model you are working with. For example, in ordinary least squares regression, you model a dependent variable (usually called Y) as a linear combination of one or more independent variables (usually called X), getting something like
$Y_i = b_0 + b_1x_1 + b_2x_2 + ... + b_px_p$
where p is the number of independent variables. The parameters to be estimated here are the $\beta s$ and $\theta$ is a name for all the $\beta s$. But $\theta$ is more general can apply to any parameters we want to estimate.
Comment: This explanation, although it is clear and technically correct, does not explicitly involve any distributions whatsoever, and thus appears not to be relevant to the quotation in the question.
Comment: Peter, although you didn't say this exactly, I'm afraid this answer may give a novice the incorrect impression that the symbol $\theta$ will _always_ refer to a parameter vector and, conversely, that this is the only way to refer to a parameter value. As my comment above indicates, I think the answer is nothing more than "$\theta$ is a mathematical symbol", making it not really a statistical question.
Comment: @Macro I think, in this context, it's clear that this is the meaning of $\theta$ that Kamilski wanted. Sure, any symbol can refer to anything.  But in this paragraph, Macro means you, and not a course in Economics or a part of SAS or whatnot.
Comment: ok well I don't think that analogy is really apt but I will take it as an attempt at hyperbole. In any case, I'm really referring to something very basic which is that mathematical novices often mistake _notation_ as something inherently meaningful and as something other than what it is - simply a label. My point was that this answer (I think unintentionally) does nothing to dispel that idea. As you know, $\theta$ can refer to other things a statistician may encounter. For example, angles are often denoted by $\theta$.
Answer: In plain English:
Statistical distribution is a mathematical function $f$ that tells you what is the probability of different values of your random variable $X$ that has the distribution $f$, i.e. $f(x)$ outputs a probability of $x$. There are different such a functions, but for now let consider $f$ as some kind of "general" function.
However, for $f$ to be universal, that is, one that is possible to apply to different data (that share similar properties), it needs parameters that change its shape so that it fits different data. A simple example of such a parameter is $\mu$ in normal distribution that tells where is the center (mean) of this distribution and so it can describe random variables with different mean values. Normal distribution has another parameter $\sigma$ and other distributions also have at least one such a parameters. The parameters are often called $\theta$, where for normal distribution $\theta$ is a shorthand for both $\mu$ and $\sigma$ (i.e. is a vector of the two values).
Why is $\theta$ important? Statistical distributions are used to approximate the empirical distributions of data. Say you have dataset of ages of a group of people and on average they are 50 years old and you want to approximate the distribution of their ages using a normal distribution. If normal distribution didn't allow for different values of $\mu$ (e.g. had a fixed value of this parameter, say $\mu=0$), then it would be useless for this data. However, since $\mu$ is not fixed, normal distribution could use different values of $\mu$, with $\mu=50$ being one of them. This is a simple example, but there are more complicated cases where the values of $\theta$ parameters are not so clear and so you have to use statistical tools for estimating (finding the most appropriate) $\theta$ values.
So you could say that statistics is about finding the best $\theta$ values given the data (Bayesians would say: given the data and priors).

What does Theta mean?


Proper way to finger Flugelhorn

Question: Today, I was playing Holst's Second Suite in F (Movement 1) on my Flugelhorn. It sounded great, but I feel that some particular sequences are a bit muddy in the fingering. I usually play with the middle of my fingers rather than the fingertips, is that the problem? What would be the proper way to finger these awkward sequences?
Answer: Unfortunately the design of most piston-valve flugelhorns encourages that kind of playing technique, but it really should be avoided if possible. Actuating the valves with the middle of your fingers actually makes you work a lot harder since the movement of the tip of your finger is amplified as though it were a lever over a fulcrum.
You should try to keep the same posture fundamentals on flugelhorn as you would on any other bell-front valve instrument:

Support the weight of the instrument primarily with the left hand
Keep the right hand relaxed, with the fingers curved
Anchor the right hand with the thumb between the 1st and 2nd valve casings.
Center the tip of each finger on the appropriate valve's finger button
Keep the fingers curved, the wrist relaxed, and the thumb anchored as you actuate each valve with a short, clean finger motion

This does take a bit of finger strength, and you may have to adjust things for certain hand sizes or instruments, but the basic tenants should stay the same: keep the fingers curved with the fingertips resting on the valve buttons, and don't add unnecessary tension to your posture, grip, or technique.
Comment: @NReilingh: oh... I am so tired. Klocka is the swedish word for bell. Sorry.
Comment: I have tiny hands, but find I play much more expressively with the meat of my fingers rather than the tips.
Comment: As you become more experienced, you'll find that that's an illusion. It's a fallacy to think that good technique and expression are mutually exclusive. You have more control over your expression when you develop good technique. Not without reason, it is very easy to mistake bad technique for expression in certain musical contexts, which unfortunately gives rise to the misconception detailed above.
Comment: Agreed with supporting the instrument with the left hand. The hook for the right pinky should be used only for wah-wah or plunger action. I actually practiced a while with my pinky on top of the hook rather than inside, and a champagne cork in my hand. It has the further advantage of lessening the possibility to press the mouthpiece against the lips :)
Comment: But I think the valve flugelhorn rather discourages this technique. The clock being on the right of the valve group, and quite large, your right hand can't get as close to the valves as with a trumpet. Maybe some are tempted to grip the clock tighter than they would a trumpet lead pipe...
Comment: @Gauthier Haven't heard 'clock' used that way before. Do you mean the bell throat?

Proper way to finger Flugelhorn


Recovery from i8042 no controller found during boot?

Question: I have a set of identical hardware, Dell R210s.  To replicate their configuration, I use a method to image /dev/sda from a working machine, and then apply that image to a new machine.  It has been accomplished many times without a hitch.
As root on the machine to be cloned...
dd if=/dev/zero of=/tmp/0bits bs=20M; rm -f /tmp/0bits

Boot from a DVD (I use knoppix 6.7) and image the disk...
dd if=/dev/sda | gzip - | ssh user@hostname dd of=image.gz

Then boot the destination with the DVD, and overlay the image...
ssh user@hostname dd if=image.gz | gunzip - | dd of=/dev/sda

All of the success to date has been with RHEL 5.x and RHEL 6.x.  I attempted the same method for RHEL 7.x for the first time and have received the following error when I boot from /dev/sda afterward...
[       1.659252] i8042: No controller found

I do not receive the error if I reboot using the knoppix DVD, but I do receive the error if I attempt to boot using a RHEL 7 installation DVD or the internal hard drive.
I've seen "solutions" on Ubuntu forums which suggest the you add nomodeset to the boot parameters.  This does not affect the error in my case.
Comment: The i8042 was the chip on the old PCs that took care of the keyboard interface (PS/2). I think it's a dummy message, please use `debug` and try to catch the true kernel error that prevents booting.
Comment: I am getting the same error. @kubanczyk will you please explain how to debug? thanks
Comment: Try to wait longer. My machine takes >3 min to pass through this message.
Answer: I don't think that this message is fatal.  I have a CentOS 7 installation that throws this message (onto the boot screen and the kernel log) but continues, completing the boot successfully.  On my system, the keyboard and mouse are USB, not PS/2, and (I imagine) not USB-emulating-PS/2.
Have a look at the kernel log.  It may show that booting stops elsewhere.  That may require editing the boot parameters: remove "rhgb" and "quiet".
Emulation of PS/2 devices for USB keyboards and mice is technically quite tricky.  It is done by the firmware behind the scenes, using SMM.  Usually there is a firmware ("BIOS") configuration option to enable or disable it.  Perhaps this set differently on your two computers.
Comment: I  confirm. I've also the message  ̀i8042 no controller found` and the machine boots well.


How to assign table name for dataset tables

Question: I create three stored procedure in MySQL. It's working fine. Now I read the third procedure using C#. It returns the two tables named table, table1. How can I assign name of the each tables? I'm really confused the tables name while using more than 8 or 10.
create procedure dbo.GetPeople
as
begin
    select * from dbo.Person;
end;

create procedure dbo.GetCars
as
begin
    select * from dbo.Car;
end;

-- This gives the same result as before
create procedure dbo.GetSomething
as
begin
    exec dbo.GetPeople;
    exec dbo.GetCars;
end;

Comment: where is your c# code? Can you share your c# code?
Answer: In c# you you will get table from dataSet by index, because when we fill a dataSet from a dataBase then we never recieve table names from db.
One thing is passible as i used for reporting when i returning multiple tables by sp is that:
select an extra colum in each select statement that reprent table name.
e.g
your sp
create procedure dbo.GetData
as
begin

select '' as 'Person', * from dbo.Person;
select '' as 'Car',* from dbo.Car;

end;

And do foreach loop on you dataSet to get firstColumn Name of each table as your DbTableName.
Following is dumy code please verify, i did't compile.
foreach(DataTable tbl in dataSet.Tables)
 {
       if(tbl.columns[0].name=="Person")
       {
        //your code to do with table Person
       }esle if(tbl.columns[0].name=="Car")
        //your code to do with table Car
       }
 }

Comment: I am using sqlServer, working in sql server. re structure for you mysql
Comment: Suppose we have more than thousand means it show the first columns of thousand records show the table name right
Comment: Its not a right way, but just a possible way. I search more for my own but finally i work to apply this approach. 2nd is just access datatable by their index, perhaps already you are accessing like ds.Tables[0] ..ds.Tables[1] .. ds.Tables[2]
Answer: DataSet _ds=new DataSet();

DataTable _dtEmployee=new DataTable();

_dtEmployee=_ds.Tables["employee"];

or
_dtEmployee=ds.Tables[0];


Breakeven Bet: Expected Value and Simulation

Question: Here is the problem:

A bet is known to have a win rate of 25%.
Upon winning, the bet pays $100.
Player can choose the cost of the bet.

My understanding is that the breakeven bet size would be 25% times \$100 = $25, equal to the expected value of each bet.
However, I simulated this game with a short Python script:

The simulation results in a profit, even after 100 million trials. It seems to always result in a profit, I've ran the simulation many times. It appears that ~$33 is closer to the actual breakeven bet size (not shown, I just manually adjusted the bet size higher until the resulting profit converged to about zero).
What am I missing here? Am I calculating the breakeven bet size wrong or is there something wrong with the simulation?
Thanks in advance!!
Comment: It can help to make the code look as much like the problem description as possible.  At the head of the loop, then, subtract the cost of the bet from `total_value` (you will want to create a constant `cost_of_bet = 25` to do this clearly) to model the cost of the bet. Upon success, add `win_value` to `total_value` to model the gain from winning.  You don't have to do anything when success does not occur!  BTW, why do you use`np.random.normal`? That's obscure and inefficient compared to `np.random.ranf`.
Comment: @whuber Thanks for the useful feedback.  I don't have a really good reason for using `np.random.normal`. I found it [here](https://docs.scipy.org/doc/numpy/reference/routines.random.html) and thought it made sense to specify the distribution from which the randoms were being created ([I compared the distributions here](https://github.com/def-mycroft/shared-ipynb/blob/master/Breakeven%20Bet%20-%20Expected%20Value%20and%20Simulation.ipynb))
Answer: Your simulation is wrong.  If the cost of placing the bet is 25, and the bet pays out 100 when you win, then the net payout is 75.  Right now, you are only charging the player the cost of placing the bet when he/she loses, but not when he/she wins.
Comment: That was exactly the problem - [here is the updated simulation](https://github.com/def-mycroft/shared-ipynb/blob/master/Breakeven%20Bet%20-%20Expected%20Value%20and%20Simulation.ipynb)


In Laravel, mocking an eloquent query on a model

Question: I'm stuck on Laravel 4.2 for now (with phpunit and mockery) but the same should apply to later versions.
I have a Repository for my FxRate model. It has a method to get an FX rate vs GBP which contains this eloquent call:
$query = \FxRate::where('currency', $currency )
    ->where('fx_date', $fxDate->format('Y-m-d') )
    ->first();

return $query->rate_to_gbp;

In my unit test I'd like to mock this call so I can define the query result that would be returned by this call rather than relying on the database to have a value within it.
My attempt goes something like this:
$mocked_query_result = (object) ['rate_to_gbp' => 1.5];

FxRate::shouldReceive('where')
       ->once()
       ->andReturn($mocked_query_result);

But I'm fairly sure this won't work as the initial static call to FxRate should return some query object that accepts a further where() call and a first().
Is there a clean way of mocking this?
Answer: You should pass an instance of your model into the repository in the constructor:
public function __construct(FXRate $model)
{
    $this->model = $model;
}

Then your query becomes:
$query = $this->model->where('currency', $currency)...etc

Then you pass a mocked model to the repo when you instantiate it:
$mockModel = Mockery::mock('FXRate');
// This could be better, and you should use correct with() calls but hey, it's only an example
$mockModel->shouldReceive('where')
    ->twice()
    ->andReturn($mockModel);
$mockModel->shouldReceive('first')
    ->once()
    ->andReturn($mocked_query_result);
$repo = new Repo($mockModel)
$this->assertEquals($mocked_query_result, $repo->testableMethod());

Further edit following comments. You can return a mock of any model but I find mocking the real model helps with readability:
$mockFXRate = Mockery::mock('FXRate');
$mockFXRate->shouldReceive('where')
    ->once()
    ->andReturn($mockFXRate);
$mockFXRate->shouldReceive('first')
    ->once()
    ->andReturn($mocked_query_result);
FXRate::shouldReceive('where')
    ->andReturn($mockFXRate);

Comment: If you do not care about the arguments passed to the `where` calls you can use `$mockFXRate->shouldReceive('where->where->first')->andReturn($mocked_query_result);`. http://docs.mockery.io/en/latest/reference/demeter_chains.html
Comment: [The docs](http://laravel.com/docs/4.2/testing#mocking-facades) say it's possible to mock the facade; that's not the problem - and I'm happy using the facade in this case. The difficulty is the chained methods which looks as if I'd need to return a new mock object for each method in the chain.
Comment: @harryg - got you. I take the approach in the edit. Maybe not the best so someone might suggest something else. There is a Mockery::self() object to return but I had problems getting that to work and never persevered with it, so could be worth looking at.
Comment: Hmm I'm still not sure that works as `FxRate::where(...)` doesn't return an instance of `FxRate`; it returns an `Illuminate\Database\Eloquent\Builder` instance which accepts the further chained mothods. `first()` then returns the result.
Comment: @harryg - IME, andReturn() can return anything you want as long as what it returns provides the chained methods. I would use FXRate as the mock here for readability and continuity. Not sure if I've done this from a Facade like you're wanting to, but this approach of a mock returning the same mock and having multiple shouldReceive() works for me. Pending a more elegant solution.
Comment: @Petter - I saw that the other day, and it's definitely relevant here, so good call!


Qt installer stuck

Question: I'm running the Qt Open Source installer on Windows 7.
It's at 46% during the "Retrieving meta information from remote repository" step. It quickly got there and got stuck there 55 minutes already.
I tried restarting the installer and this time it got stuck again at the same step, but at 64%.
Any ideas?
Notes:

The installer name is qt-unified-windows-x86-2.0.3-1-online.exe
I believe the Qt version it's going to install is Qt 5.7, as that's the latest Qt version as of now
I'm going to try the offline installer now
Comment: In case anyone else runs into this question due to the Qt installer hanging at a slightly different phase - in my case, `qtwebinstaller` - note that (at least the open-source installer) is pathetic in terms of feedback and it will literally seem to hang while it unzips a massive file. In my case, it seemed to hang on the noted package for a solid 20 minutes - no feedback whatsoever provided - but doing a file count on the associated folder in the file system revealed that, in fact, it was slowly unzipping the files there, and after all that time the installation resumed.
Comment: I haven't seen this myself. Is your network connection stable, maybe there's disconnection (and them some reconnection bug in the installer)? Or maybe it was a temporary server problem, or problem with your ISP, I suppose these are possible reasons. Anyway, unless it is for something like a single project, I'd try to get it done with the online installer, because you can get new versions and Qt Creator updates with it too.
Comment: I was having the same issue some time ago (few weeks). Just chose another distro (or options).
Comment: I advise to build Qt from source. You'll have way more control over what goes on, and you'll be able to do source-level debugging within Qt itself. The prerequisites are rather simple: MSVC 2015, python27 (not 3!), ruby, perl, with the latter 3 added to the path, and also add `\qt-everywhere-opensource-src-5.7.0\gnuwin32\bin` to the path.
Comment: @QtRoS: What do you mean by another distro? And the only options provided by the installer are network proxy ones.
Comment: @hyde: Thanks, but my connection is stable. If all else fails, I'll try the online installer again tomorrow, ruling out server problems.
Comment: @StefanMonov - the online installer is slow (to download data) and unreliable, just get an offline installer, this way you can install the same download multiple times and even without internet connection. Alternatively, if you have MSYS2 you can get the build from its repo, although they are sometimes a little behind the latest version. I strongly reccomend MSYS2 thou, it is a great build environment for windows and a source for a ton of prebuilt libraries.
Answer: The solution that worked for me was to download and use the offline installer instead of the online one.
Comment: @PredragManojlovic: Then I guess just DL several offline installers and install each one.
Comment: Well that is far from a solution. What if I need several versions of Qt?
Comment: it is still a workaround due to huge overhead and making final development on several versions quite complicated.
Answer: I had the same problem and added this as custom repo in the Maintenance Tool Settings -
http://download.qt-project.org/online/qt5/windows/x86/online_repository/
After this it updated all the build-in repos and synced.
But I too really really think Qt should fix it, I have this problem every time on every machine.
Answer: It is probably due to some network issues, as mentioned by some other users.
Just play around with your network and it should work.
In my case, I disconnected my WiFi and connected again and it worked.

Qt installer stuck


How does JavaScript access variables declared outside the function it is used?

Question: Suppose we have a simple print statement within a for loop such as
for (var i = 0; i < 2; i++){
    setTimeout(() => console.log(i));
}

Two questions.
setTimeout is a browser API method, but how does it access i? i is declared inside the for loop, and I am accessing i inside the method setTimeout even though i is not passed through, how?
Why is 2,2 printed, instead of 0,1?
Answer:
setTimeout is a browser API method, but how does it access i? i is
  declared inside the for loop, and I am accessing i inside the method
  setTimeout even though i is not passed through, how?

In javascript, nested functions can access higher order variables and functions.

//global context - any variable declared here will be availabe within any nested function
var someVariable = 0;
var someSecondVariable = 1;

const someFunc = () => {
  //someVariable and someSecondVariable are accessible here
  console.log("someFunc", someVariable, someSecondVariable);

  var someThirdVariable = 2;
  for(let i = 0; i < 5; i++){

    const temp = i;

    //all higher order variables are still accessible
    setTimeout(()=>{
      //all higher order variableds are still accessible
      console.log("settimeout", i, temp);
    }, 4000);
  }

}

const someFunc2 = () => {
  //cant access someThirdVariable
  try {
    console.log("someFunc2", someThirdVariable);
  }catch(e){
    console.warn(e.message);
  }
}

someFunc();
someFunc2();

Why is 2,2 printed, instead of 0,1?

setTimeout is an asynchrounous method and doesn't get called right away. The loop ends before the first timeout is event started. This means, that at the time the setTimeout callback is called i is already equal to 2.

i = 0 -> continue looping
i = 1 -> continue looping
i = 2 -> stop looping because 2 < 2 = false

then your setTimeout callbacks are called
console.log(i) //where i = 2
console.log(i) //where i = 2

Here you can have 0,1

for (var i = 0; i < 2; i++){
    //temp won't get increased in the next iteration
    const temp = i;
    setTimeout(() => console.log(temp));
}

Compared to php, for example, this is different, we have to specifically tell it to use a higher order variable to be able to access it within the scope of the function.
<?php

  $i = 0;
  $func = function() use ($i){
    echo $i;
  };
  $func();

Comment: ohkk, so in your example you have method `first`, and `nested1`. Translating that to my example, is `first` method the equivalent to the `for loop` declaration? Do `for loop` and `method` declaration have a relationship?


Can't install DRUSH

Question: I upgraded my system from Ubuntu 14 to Ubuntu 16.10 and suddenly i can't find the drush command.
I wanted to install it via apt install drush but this is not working and sent me this error:
 Reading package lists... Done
Building dependency tree
Reading state information... Done
Package drush is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package drush has no installation candidate

Is there any solution for that?
Thank you
Answer: I found that on the drush documentation:
php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > drush
php drush core-status

chmod +x drush
sudo mv drush /usr/local/bin
drush init

And it's working, Thank you very much..

Can't install DRUSH


how to wrap drupals taxonomy term node list in a div

Question: i need to wrap the nodes teaser in a div for my taxonomy term page but cant figure out how.
this is my page , this is a list of nodes for the products taxonomy term, using node--product.tpl.php i warped the individual node in

 but now i need to wrap the list of nodes in

 and just for the products taxonomy term page listing ...
how can i do this ???
Answer: One option you have is to override page.tpl.php and wrap the "content" render:

        <?php print render($page['content']); ?>

This will encapsulate your whole taxonomy-term.tpl.php, where your node list is.


Unusual (to me) Phrasing of Power Analysis Objective; Interpretation Requested

Question: I am reading a field biology manual that is directing me to do a power analysis, and I find the phrasing very confusing. It says:
Determine sampling requirement to be 80% confident you are within 10% of the objective. (More concretely: how many survey plots do I need to be 80% confident of whether I am within 10% of having 65 trees per hectare?)
It's phrased like a power analysis, but is confidence a synonym for power, and is being with 10% an indication of the alpha?
*Can anyone suggest what the statement means mathematically (e.g., B = 0.8)?
*Can anyone recommend an R package for this?
Answer: You are asked to find out how many survey plots are needed to make the confidence interval (CI) equals 56.5 ~ 71.5 with the confidence level (CL) equals 80%. In other words, how many survey plots are needed in order to be able to claim with 80% confidence that there are 56.5~71.5 trees per hectare on average.
Comment: I doubt this is correct, because no amount of sampling could assure the CI will be $[56.5,71.5]$ unless the true mean really is $65.$
Comment: Thanks for that point whuber. What if I did indeed switch the question around to: "how many plots do I need to be 80% confident I am within 10% of the true mean?", regardless of if the true mean is 65 or not. In that case, does the 80% refer to power and the 10% to alpha/significance?
Comment: The number (denoted as n1) of samples used to obtain  the mean (of the number of trees per hectare, i.e. 65 in this case)  and the number (denoted as n2) of samples needed to obtain the specified CI with a specified CL are two different things. Here you are asked to find out n2 which is unknown. This does not necessarily mean "n1 is unknown". A possible situation is that the mean of 65 has been obtained based on n1 samples, and now ask you what is the value of n2 needed to achieve the required CI with specified CL.


How to disable VS2010 script debugging

Question: How does one disable script debugging with Visual Studio 2010?  For VS2008 I used:

reg add HKLM\SOFTWARE\Microsoft\VisualStudio\9.0\AD7Metrics\Engine{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {4FF9DEF4-8922-4D02-9379-3FFA64D1D639} /f

Thanks!
EDIT
Used Shoban's answer.
You have to have the Silverlight Developer Runtime package installed for this to work.  See: http://go.microsoft.com/fwlink/?LinkID=188039 for version 4.
Answer: When debugging a Web App script debugging is always enabled with VS2010 and IE8 (note same issue with VS2008) eventhough script debugging has been disabled in IE8.
Note you can work around it by setting Silverlight debugging on.
Here is how you can do it.

How to disable VS2010 script debugging


How to add a service account (sp_c2wts) to local security policy using powershell?

Question: Is there a powershell way to achieve this? I have to do this for 40 servers.
Set the following permissions on all SharePoint servers in the farm (All must be done) – this is completed under Local Security Policy (gpedit.msc as administrator -> Windows Settings -> Security Settings -> Local Policies > User rights assignment) on each server
print shot
Grant Log on as a service
Impersonate a User
Act as part of the operating system
Comment: This may be the solution. I will post my findings in few minutes. https://gallery.technet.microsoft.com/scriptcenter/Grant-Revoke-Query-user-26e259b0
Answer: This solution worked perfectly.
https://gallery.technet.microsoft.com/scriptcenter/Grant-Revoke-Query-user-26e259b0
Comment: Please do not post link-only answers to prevent link rot. Instead, add the most relevant information from the link to your answer or alternatively, post the link as a comment instead of an answer. See [this](http://serverfault.com/help/how-to-answer) help center article for further information.


Proof of a certain proposition on sheaves without using cohomology

Question: Definition
Let $\mathcal F$ be a sheaf of abelian groups on a topological space $X$.
We say $\mathcal F$ is quasi-flasque if it satisfies the following condition.
For every exact sequence of sheaves $0 \rightarrow \mathcal F \rightarrow \mathcal G \rightarrow \mathcal H \rightarrow 0$, $\Gamma(X, \mathcal G) \rightarrow \Gamma(X, \mathcal H)$ is surjective.
Proposition
Let $0 \rightarrow \mathcal F \rightarrow \mathcal G \rightarrow \mathcal H \rightarrow 0$ be an exact sequence of sheaves of abelian groups on a topological space. Suppose $\mathcal F$ and $\mathcal H$ are quasi-flasque.
Then $\mathcal G$ is quasi-flasque,
My question
Can we prove the proposition without using cohomology?
Comment: Proof using cohomology: Is easy to see that a sheaf is quasi-flasque iff the first cohomology group vanish. To prove this just take an exact sequence as above with $\mathcal{G}$ injective (there are enough injectives) and use the long exact sequence in cohomology. Then the result follows easily by using again the long exact sequence in cohomology.
Answer: I think so, but this could just reflect my lack of understanding of sheaves.
Forgetting the script, write $H = G/F$. Let $0 \to G \to G' \to G/G' \to 0$ be an exact sequence of sheaves; we want to show $G'(X) \to (G/G')(X)$ is surjective.
Composing the injections $F \to G \to G'$, we can form an exact sequence $0 \to F \to G' \to G'/F \to 0$, and since $F$ is quasi-flasque, the last map is surjective on global sections.
Since $F$ includes into both $G$ and $G'$, we get an exact sequence $0 \to G/F \to G'/F \to (G'/F)/(G/F) \to 0$. By the assumption that $H = G/F$ is quasi-flasque, the last map is again surjective on global sections.
Now I want to say $(G'/F)/(G/F) \cong G'/G$. It's true on stalks, by group theory, so I think it should be true since quotient sheaves are all sheafifications anyway.
Now we know $G'(X) \to (G'/F)(X)$ and $(G'/F)(X) \to (G'/G)(X)$ are surjective, so we should be done.
Comment: This is great. Thanks.


What does #markup mean?

Question: I meet this array key all the time in Drupal (for example in Symphony's dpm()) yet I am not able to find any documentation about it, what it does, how can I use it? How do I display something that is given as #markup value in Twig?
Comment: Take a look a the documentation for render arrays: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/theme_render/9.3.x
Answer: By using #markup in render arrays you can output raw HTML (passed through XSS filter to ensure security).
Here's an advanced example, with optional #allowed_tags and placeholders.
/**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_foobar(&$variables) {
  $variables['video'] = [
    '#markup' => '@video_label: <video><source src="v.webm" type="video/webm"></video>',
    '#allowed_tags' => [
      'video',
      'source',
    ],
    '#attached' => [
      'placeholders' => [
        '@video_label' => t('Sample label'),
      ],
    ],
  ];
}

In Twig you just do:
{{ video }}

And in your browser you get the HTML with replaced placeholder and stripped :
Translated label: <video><source src="v.webm" type="video/webm"></video>

Comment: I would use a longer name instead of `@label`, this is a global placeholder replacing everything on the page it can find. Or use FormattableMarkup: `'#markup' => new FormattableMarkup('@label', ['@label' => $label])`
Comment: You are right here, I just wanted to show how attached placeholders work here. I've changed the name of the label to more specific one.
Answer: Just by using the regular print twig syntax: {{ variable }}
The #markup is the html that will be on the final page sent from the server.
You can use a preprocess function to intercept and change the #markup if you need to.

What does #markup mean?


Can a double bar line begin a repeated section?

Question: Please see the following:

I assume that the repeat sign should refer back to the double bar line?
Answer: Double bar lines are used to mark beginnings and ends of sections but they are not the same as repeat signs. If there is no forward facing repeat sign then it repeats all the way to the beginning of the piece.
Comment: There's always a chance the double bar line is an engraving error, but a point in favor that everything should be interpreted as-written is to consider what happens in the measure after the repeat sign: the introduction once again, but with a final measure for the ending chords.
Comment: @KyleMiller An engraving error? Perish the thought! Haha, we all have encountered way too many I'm sure. Your logic is sound, examining the before and after, good call.
Answer: The repeat should go back to the beginning, actually.
If the notation wanted to indicate going back to the double bar, they would have put an opening repeat barline. In the absence of such an opening repeat, the default is to return back to the beginning.
Alternatively, one could notate this with a dal segno marking, putting it at that double barline if that's where one is intended to return.
Answer: As the other answers say, music should be repeated from the beginning.
This is a simple arrangement of a melody by Prokofiev. It is preceded by 4 bars of chordal introduction. The double bar line separates the introduction from the main theme. The intention of the arranger is to repeat both the introduction and the theme.
It might be a good idea to learn the arrangement as it is, for educational purposes, but also to listen to original composition, recognize what was modified by the arranger, and possible change the arrangement to your liking.
Answer: The double barline after bar 4 shows the end of the introduction, and the beginning of the theme.Lacking any 'backward' repeat sign (!!:) means go back to the very beginning.
The way it's all written forms a big sandwich.
Intro.4 bars.Theme.8 bars.
Theme in another key.8 bars.(Repeat sign here):!!
Intro.4 bars.
Theme.8 bars.
Theme in another key.8 bars.
Outro.4 bars.


Re-rendering KMLLayer in google maps api

Question: Having issues with a mapping application I am building. When a kml layer is rendered on the map and then removed, and another layer is added it does not appear on the map until the map is panned slightly.
Workflow

Load google map
Load KML Layer
Call to PHP page to generate new KML
Layer Original layer is removed
kmlLayer = new google.maps.KmlLayer({
                                url: KML,
                                preserveViewport: true
                            });
new KML layer is applied to map with following call
kmlLayer = new google.maps.KmlLayer({
                                url: KML,
                                preserveViewport: true
                            });

For some reason after step 5 I will not see the new kml layer rendered on the map unless I move the map ever so slightly. Has anyone seen this behavior?
I apologize for this question. Had a brain fart and forgot to call
kml.setMap(map);
Answer: I apologize for this question. Had a brain fart and forgot to call kml.setMap(map);


Locality in COA/Vertex Operator Algebras

Question: I am trying to understand CFT from the viewpoint of both math(in particular using VOA) and physics. Now, in Math, we use the VOA to make sense of fields corresponding to certain states. We define for each state, $\lvert a \rangle $, in the Fock space, a field say $V(\lvert a \rangle, z )$ and we then expect these fields to be local, i.e.
\begin{equation}
(z-w)^k \ [ \ V(\lvert a \rangle, z), V(\lvert b \rangle, w ) \ ] = 0
\end{equation}
where they are treating $V(\lvert a \rangle, z)$ and $V(\lvert b \rangle, w)$ to be formal series and both the products, $V(\lvert a \rangle, z)V(\lvert b \rangle, w )$ and $V(\lvert b \rangle, w)V(\lvert a \rangle, z )$ are defined.
This is the standard treatment in texts such as
Vertex Algebras and Algebraic Curves by David Ben-Zvi and Edward Frenkel
Christoph A. Keller - Introduction to VOA - https://www.math.arizona.edu/~cakeller/VertexOperatorAlgebras.pdf \
However, in physics we treat $z$ in Riemann sphere and $V(\lvert a \rangle, z)V(\lvert b \rangle, w )$ is only defined when $\lvert z \lvert \ > \ \lvert w \lvert$. Further, by locality we mean that  $$\langle c \lvert V(\lvert a \rangle, z)V(\lvert b \rangle, w )\lvert d \rangle = \langle c \lvert V(\lvert b \rangle, w)V(\lvert a \rangle, z ) \lvert d \rangle, \  \forall \ \lvert c \rangle,  \lvert d \rangle \in \mathcal{F},$$ after analytic continuation of these functions into regions where they were not defined.
Such definitions can be found for example in https://arxiv.org/abs/hep-th/9410029.
Now, how are these two definitions of locality equivalent. Further, I haven't seen where exactly in Math references they start treating $z$ as complex variable.
Answer: Since this question is more than a year old I'm sure you found what you were looking for, but since I stumbled across this question I'll answer in case anyone else happens to do the same. Section 1.2.8 of Vertex Algebras and Algebraic Curves by Frenkel and Ben-Zvi gives the complex-analytic reformulation of locality of fields that culminates in Proposition 1.2.9, which gives the equivalence between the two definitions. The whole of chapter 1 is a very useful resource for giving analytic meaning to the standard algebraic definitions in math references.


"+having+" in $GET/$POST causes server to return 403 Forbidden

Question: One of my clients has a PHP script that kept crashing inexplicably.  After hours of research, I determined if you send any PHP script a variable (either through GET or POST) that contains " having t", or escaped for the URL "+having+t", it crashes the script and returns a "403 forbidden error".  To test it, I made a sample script with the entire contents:
<?php echo "works";

I put it live (temporarily) here: http://primecarerefer.com/test/test.php
Now if you try sending it some data like: http://primecarerefer.com/test/test.php?x=+having+x
It fails.  The last letter can be any letter and it will still crash, but changing any other letter makes the script load fine.  What would cause this and how can it be fixed?  The link is live for now if anyone wants to try out different combinations.
PS - I found that if I get the 403 error a bunch of times in a row, the sever blocks me for 15 minutes.
Comment: Does it only happen on PHP files? Can you try a HTML file?
Comment: How do you know it's *crashing the script* and that 403 isn't being returned on purpose?
Comment: FYI, the characters around *"having"* seem to be mostly irrelevant. If I was to hazard a guess at a matching regular expression it would be `\bhaving\b.+`
Comment: Sounds unrelated to PHP. I'd be checking the web server's error log as well as any URL rewriting / access control rules that may be in place
Comment: and without the plusses? could htaccess be blocking special chars?
Comment: @HarshitShrivastava what do you mean?  I did show all of the code!
Comment: @Jorg The original post had a story several hundred characters long with tons of plusses, I had to edit it down character by character until I found the couple characters that are causing the problem.
Comment: @Phil, I checked the web servers error logs and it only complains about not being able to find a custom 403 page.  I also checked the .htaccess, and there's nothing questionable there.
Comment: I would expect a 'PHP crash' to result in a 5xx, not a 403.. how is the PHP being hosted? Which version? What mods/additions are in effect? Are there other server handlers?
Comment: @Phil, did you find any other letters besides "+" and "%20" cause it to crash?
Comment: @DanGoodspeed I tried `.`, `,`, `_` and `:` before the StackOverflow hug of death killed your test site. You sure you're looking at the error log and not the access log. Usually a 403 response will log why it was blocked
Comment: @user2864740, It's a LAMP-based Cloudflare site, if that answers your question.
Comment: @Phil it wasn't the stackoverflow hug... the site blocked your IP address (as it did mine several times).  And YOU'RE RIGHT!  I just tried a regular html file and it causes the same issue!  http://primecarerefer.com/test/test.html?x=+having+t
Answer: I had this type of issue on a webserver that ran apache mod_security, but it was very poorly configured, actually mod_security has very bad default regex rules, which are very easy to trip with valid POST or GET data.
To be clear, this has nothing to do with PHP or HTML, it's about POST and GET data passing through mod_security, almost certainly, and mod_security rejecting the request because it believes it is an sql injection attempt.
You can edit the rules yourself depending on the server access, but I don't believe you can do anything, well, if it's mod_security, I know you can't do anything via PHP to get around this.
/etc/httpd/conf.d/mod_security.conf (old path, it's changed, but it gives the idea)
Examples of the default rules:
SecFilter "delete[[:space:]]+from"
SecFilter "insert[[:space:]]+into"
SecFilter "select.+from"

These are samples of the rules
https://www.howtoforge.com/apache_mod_security
here they trip the filter:
http://primecarerefer.com/test/test.php?x=%20%22%20%20select%20from%22
Note that the article is very old and the rules actually are quite differently structured now, but the bad regex remains, ie: select[any number of characters, no matter how far removed, or close]from will trip it, any sql that matches these loose rules will trip it.
But since editing those default files requires access to them, and also assumes they won't be altered in an upgrade of apache mod_security at some point, it's not a good way to fix the problem I found, moving to a better, more professionally setup, hoster, fixed those issues for us. But it does help if you talk to the hosting support to know what the cause of the issue is.
In fact 'having' is not irrelevant at all, it's part of sql injection filters in the regex rules in the security filters run on POST/GET. We used to hit this all the time when admins would edit CMS pages, which would trigger invariably some sql filter, since any string of human words would invariably contain something like 'select.*from' or 'insert.*into' etc.
This mod_security issue used to drive me bonkers trying to debug why backend edit form updates would just hang, until I finally realized it was badly done generic regex patterns in the mod_security file itself.
In a sense, this isn't an answer, because the only fix is going into the server and either editing the rules file, which is pretty easy, or disabling mod_security, or moving to a web hoster that doesn't use those bad generic defaults.
Comment: http://primecarerefer.com/test/test.php?x=%20%22%20select%20zowder%22 yes, it's clearly the mod_security, there's another one. I can't find my copy of the security filter rules, but I recognize this because I fixed the rules to be less sloppy. I was actually surprised to see Apache ship defaults that were so bad that most users would just turn them off rather than try to fix them, which defeats the purpose.
Comment: I've tried a bunch of SQL keywords and so far, nothing else trips the error.
Comment: I'll see if I can find the file that had that data on it, but as noted, we left that hoster because of such issues, among many others, so I may not be able to find it. Our case was the same by the way, it was only one or two sql key words, which is why it was so darned hard to figure out.
Comment: http://primecarerefer.com/test/test.php?x=%20%22having%20zowder%22 I was curious, and you can clearly see the pattern: space plus having plus space plus any characters. The real question is if this filter is running via mod_security or if it's some manual set of rules they created. Either way you probably have to call the hoster to find out.
Comment: http://primecarerefer.com/test/test.php?x=%20%22%20%20union%20zowder%22 there's more. https://www.howtoforge.com/apache_mod_security shows some of the filters used. This is definitely mod_security.
Comment: Believe me, this issue used to drive me up the wall, lol, until I actually looked at the regex for the rules and realized that almost any human english text of any complexity will trip them. It's easy to fix them, and I'm amazed at this late date that they remain profoundly broken, ie, the POST/GET filters only work if you have no POST / GET data, sigh.
Comment: The web host company just disabled mod_security to make it work.  Good enough, I guess.  Thanks for your help!
Comment: As I noted, a security rule that is so badly written that it leads you to turn security off is a serious bug in the security rule, I find it odd that Apache, who tend to do great work, have not corrected the sloppy regex in in these filters years ago, so that they actually work as intended, rather than forcing one to turn the rules off to get functioning POST/GET. This is so non intuitive that it's very hard to figure out when you hit it, since normal english in a post/get request should NOT trip any filter, but it does.


Get only declared methods of a class in PHP

Question: Hello I need to get only the methods declared in a class, and not the inherited methods. I need this for cakePHP. I am getting all the controllers, loading them and retrieving the methods from those controllers. But not only are the declared methods coming, but also the inherited ones.
Is there any method to get only declared methods.
Comment: I know no method except complicated reflection stuff. What do you need this for?
Comment: Can you let me know why you are doing this?  Is it for documentation or for use within the application?
Comment: I need to add all the public methods in controllers to my permissions table. I am using cakePHP's, and their ACL component isn't working with the existing model that I have.
Comment: @Joe- I need to add all the methods to a table in database. I am using cakePHP and their ACL component isn't fitting my existing model.
Comment: you can edit comments you know :)
Answer: You can do this (although a little more than "simple") with ReflectionClass
function getDeclaredMethods($className) {
    $reflector = new ReflectionClass($className);
    $methodNames = array();
    $lowerClassName = strtolower($className);
    foreach ($reflector->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
        if (strtolower($method->class) == $lowerClassName) {
            $methodNames[] = $method->name;
        }
    }
    return $methodNames;
}

Comment: why are you using `ReflectionMethod::IS_PUBLIC`?
Comment: It should be mentioned though, since it makes the answer incomplete to the question.
Answer: From an architectural point of view, I think that reflection should be avoided if possible, but take a look at ReflectionClass->getMethods() if you think you know what you're doing.
<?php

class A {
    public function x() { }
    public function y() { }
}

class B extends A {
    public function a() { }
    public function b() { }
    public function x() { } // <-- defined here
}

$r = new ReflectionClass('B');
print_r($r->getMethods());

?>

You will get a list of methods defined by B and A, along with the class that last defined it. This is the output:
Array
(
    [0] => ReflectionMethod Object
        (
            [name] => a
            [class] => B
        )

    [1] => ReflectionMethod Object
        (
            [name] => b
            [class] => B
        )

    [2] => ReflectionMethod Object
        (
            [name] => x
            [class] => B
        )

    [3] => ReflectionMethod Object
        (
            [name] => y
            [class] => A
        )

)

Comment: Hm, I guess it's personal preference. To me, reflection is similar to patching executables in-memory and *can* be unexpected (or expose such behavior) unless well-documented and can make your code more convoluted or introduce side-effects. However, it may prove useful for writing frameworks and meta-programming / extending a language's features.
Comment: "From an architectural point of view, I think that reflection should be avoided if possible" why is that?
Answer: Came across a comment : "ReflectionClass::getMethods() sorts the methods by class (lowest in the inheritance tree first) then by the order they are defined in the class definition" here - http://php.net/manual/en/reflectionclass.getmethods.php#115197
I verified this and it seems to be true. Based on the fact, we can add a little optimization to ircmaxell's solution to avoid iterating over other inherited methods. Also added some clean up to avoid constructor\destructor:
public function getMethods($className)
{
    $methodNames = [];
    $reflectionClass = new ReflectionClass(className);
    $publicMethods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC);
    $lowerClassName = strtolower($className);
    foreach ($publicMethods as $method) {
        if (strtolower($method->class) == $lowerClassName) {
            // You can skip this check if you need constructor\destructor
            if (!($method->isConstructor() ||
                $method->isDestructor())) {
                $methodNames[] = $method->getName();
            }
        } else {
            // exit loop if class mismatch
            break;
        }
    }
    return $methodNames;
}


The Riemann hypothesis as a statement about natural numbers

Question: In this answer it is claimed that the Riemann hypothesis can be expressed as a statement about natural numbers.  How would that look like?
Answer: He's probably referring to either Robin's theorem (most likely), which establishes that Riemann hypothesis is equivalent to the fact that for all $n\ge5041$, $$\sigma(n)<e^\gamma n\log\log n$$ where $\sigma(n)=\sum_{d\mid n} d$ and $\gamma$ is Euler-Mascheroni constant, or to this result by Lagarias which establishes that Riemann hypothesis is equivalent to the statement that, for all $n\ge2$, $$\sigma(n)<H_n+e^{H_n}\log H_n$$
where $H_n=\sum_{k=1}^n\frac1k$.
Added: For instance, refer to the Theorem 3.2 in Lagarias' paper (an improvement on prop. 1 section 4 of Robin's paper):

The negation of Riemann hypothesis implies that there are some $C>0$ and some $0<\beta<\frac12$ such that $\frac{\sigma(n)}{n\log\log n}\ge e^\gamma+\frac C{(\log n)^\beta}$ holds frequently as $n\to\infty$.

As a consequence, Riemann hypothesis is false if and only if there is some integer $m\ge5041$ (in fact, infinitely many) such that $\sigma(m)>e^\gamma m\log\log m$. A purported such number $m$ may be (theoretically) checked to satisfy this inequality in finitely many passages of arithmetic involving rational numbers.


How to define $\lambda$ as an eigenvalue of an $n \times n$ matrix

Question: I do not exactly understand what this question is asking.
So, it is given to let $A$ be a $n \times n$ matrix. Then, I must "define that $\lambda$ is an eigenvalue of this matrix.
I currently understand that in order to solve for a matrix's eigenvalues (at least how my professor describes it), one must use the following equation:
$$ 0 = \det(A- \lambda I) $$
How does one go about proving this? I do not understand how i can take the determinant this matrix, let alone solve the equation above.
Comment: I'm nit sure what you mean. For any given $A$ and $\lambda$ the matrix $A-\lambda I$ is just a matrix of numbers, and you can take the determinant of that. Just like the formula $x^2$ represents a number, but is only a number when you give a specific value for $x$.
Comment: Also, I very much apologize for all the mistakes in the post. First time posting here and I ruined the formatting.
Comment: $\lambda$ is an eigenvalue of $A$ **iff** there is some $v \neq 0$ such that $A v = \lambda v$ **iff** $(A-\lambda I) v  =0$ **iff** $\ker (A-\lambda I)$ is non trivial **iff** $\det (A -\lambda I)$  is zero.
Comment: I don't know why you write that you cannot take the $\det$ of the matrix.
Comment: That is what was confusing me the most. The fact that you cant take a determinant of a matrix with no numbers. We have not been introduced to kernels yet, so I do not think i could use the technique you posted. This professor will most definitely take off points for notusing "his" method.  Thank you for the effort though.
Answer: Given a square matrix $A$ we say $\lambda$ an eigen value for $A$ if associated with $\lambda$ atleast one vector $v \neq 0$ such that
$$Av = \lambda v$$.
Suppose that the eigen value $\lambda$ is known then we have a nonzero $v$ such that
$$(A-\lambda I)v=0$$.
Since we assumed $v$ is non zero the new matrix $A_{\lambda}:= A-\lambda I$ is not invertible. Thus we must have
$$\det A_\lambda=\det (A-\lambda I)=0$$.
Comment: Thanks! Seeing this written out neatly makes it a lot less complicated for my linear-algebra-lacking mind. Really appreciate it.


If an integer $a$ is not divisible by an integer $b$, could this imply that $b = 0$?

Question: I am working on a proof in advanced mathematics, and I believe my professor may have overlooked something. The proof is that if $d|a$, $d|b$, and $d\not|c$, then  $ax+by=c$ has no integer solutions for $x$ and $y$. However, if $x$, $y$, and $c$ are $0$, that would be an integer solution.
Comment: Without knowing the specifics, it's very hard to say.  However, it seems unlikely to be the right argument to make.
Comment: b could be zero.  But it is not implied.  And therefore can't be implied by that alone.  So the answer to your question is technically No.
Comment: I can imagine a case where one concludes $b\not \mid a $ but it's never stated b is nonzero.  And I suppose one might have a case where $b\not \mid a $ and b nonzero are incompatible .  I think $\gcd (a,b) = a $ and $b \not \mid a $ and $|a| \ge |b|$ would together imply that $b=0$.  But it's late and I make dumb mistakes when it is late.
Comment: Everything divides 0.
Comment: If $c=0$ then $d|c $.
Answer: $d|0$.  Everything divides $0$.


Is there any clean way to have the Drupal login form create a session for phpBB also?

Question: I've made my peace with having two DB's and two sets of roles, permissions, etc. But I'd like to have just one login.
Is there a simple way to have the Drupal login throw a session cookie for phpBB with the same parameters as the drupal one?
Answer: If what you want is a clean way to integrate phpBB with Drupal, I think phpBB Forum Integration is want you need.
This module will not only "embed" phpBB within a Drupal site (and synchronize account info, such as user names, roles, passwords, emails, signatures, and avatars, with only one login), but it also let phpBB topics be created from Drupal nodes.
The phpBB forum can be displayed in a full window, in a frame inside Drupal, or in a Drupal page.
Comment: Thanks for this answer, and my apologies for the delayed response.

Does the plugin also sync roles? For role restricted content on the forum?


Proper way to count beats

Question: In attempt to improve my crappy sense of rhythm, I've been reviewing how to count beats.  However, I've been having some trouble, since rhythm divisions don't seem to translate "mathematically" into words.
Take the bar below for example.  What is the proper way to count this?

When I try, I get

1 & 2 3 4

but saying 4 at the end instead of & seems misleading, since the last note isn't a full beat.  Am I counting this incorrectly?  I assume I'm just missing something...
Answer: In 4/4, if the shortest note is an 8th, your basic counting matrix is:
one-and-two-and-three-and-four-and
In this example the notes come on:
ONE-(and)-TWO-AND-(three)-AND-(four)-AND
An alternative is the Kodály Method where whole beat notes are 'Ta', half beat notes are 'Ti'. (Two beats are Ta-a, 4 beats are Ta-a-a-a etc.) Once you internalise the length that goes with each syllable, linear counting is possible, ignoring the beats.  Thus, the example would be 'Ta Ti Ta Ta Ti'.
Comment: This is the correct way to count the measure. I'd like to comment that the notation  makes the timing hard to read. The usual suggestion not to use single notes from a weak partial beat to a strong partial beat holds. I'd probably write (as I don't have graphics posting stuff working as of yet and using 8 for an eighth note and 4 for a quarter note and an underscore for a tie) 4 8 8_8 8_8 8. I would probably leave the eighth notes unbeamed (or beamed to 4/4 and having the ties show the off-beat connections.
Answer: Basically you would count it like that:
Answer: To add onto what Laurence said, You have to think of the length of the preceding note. Thinking about the concept of when the note actually ends may help.
Your attempt at counting (1 & 2 3 4) tells me you were thinking "Whole note means one, quarter note means and, so 1-And." However, the length of the first note already takes up the 'and' of 1. So the eighth number STARTS on the two. Then the third note (another quarter length) STARTS on the 'and' of 2, because that's as far as the eighth note took us.
So, (in 4/4 timing) a quarter note will take up the WHOLE number. So correct counting, as Laurence already put it, is One-Two-And-And-And.
Answer: How the count is constructed: (2 Bar count is 1&2&3&4&1&2&3&4) wher the number represents the downbeat and the "&" represents the upbeat:
Proper count for this example: 1 2& & &
Proper count if the bar is repeated: 1 2& & &1 2& & &
VISUAL:

Proper way to count beats


iOS 4 VOIP app responding in the background

Question: I have an iPhone VOIP app that copes with multi-multi transmit and receive (ie teleconferencing) set up using BSD sockets.  I would like it to be able to respond to incoming requests when it is in the background but from what I can understand of the iOS 4 docs I can only do this on an NSStream object (or CFRead/WriteStream) by setting the property to NSStreamNetworkServiceTypeVoIP.  This is a bit of a problem as my system is a UDP BSD sockets based application.  Everything is received and sent on a single UDP socket.
Am I going to need to re-write my audio transmit/receive core to handle NSStreams or is there a way I can get iOS 4 to handle my BSD socket in a similar way to an NSStream?  I assume this may be a problem as an NSStream is event based.
Would it be possible to detect when the application goes into the background and build a temporary NSStream object that will pass the data on to through the relevant handling and then continue as normal?  Is it even possible to create a UDP NSStream?
Any ideas?
Answer: You can create a socket from a file descriptor with CFSocketCreateWithNative(), and then create a pair of streams with CFStreamCreatePairWithSocket(). It might let you use them on a UDP socket. Provided the streams don't read data unless you ask, you might be able to get away with using the FD directly.
Good luck with that though!
Comment: Ok It does seem to work.  Turns out I can't automatically start an audio recording stream in the background but it DOES give me control when data arrives on the UDP port (Which is well worth knowing!)


How to access values of fields from base class?

Question: I want to access fields of a class from base class in Java. I can do it in dot net.
see the example:
public class a{

// here I want to read the value of name or f1 or f2 or every other field values from derived classes
}
public class b extends a{
  public string name;
}
public class c extends a{
  public string f1;
  public string f2;
}

How to do it?
Comment: Don't do it. The super class is not supposed to know base classes attributes. You seem to have a design flaw.
Comment: Flow is like water, should be `------ >`  not like  `<--------`
Comment: Short answer: You cannot. For a better answer, please explain what you are trying to do.
Comment: If this can be done in C# (?), it is rather scary...
Comment: @Thilo That is factually incorrect. It is possible (see Marko's answer), but it also nullifies the purpose of having sub classes.
Comment: @Torben: It was the short answer :-) (And since Marko's answer involves a type cast to the subclass, it is not really the parent class doing the accessing, it is just the normal public access available to anywhere -- and the option will go away if the field is no longer public).
Comment: Man I did it an the dot net framework before. what I want to do is to create a class for creating database methods like insert or select.
I want the top class know the fields from derived class and prepare proper insert command for it.
I can even read the field names in this way but can read the values.
Answer: You cannot read the fields your class doesn't own without explicitly naming the subclass. So, this is doable as follows:
((c)this).f1;

However, doing this would be a bad code smell: you are now tying an abstraction embodied by a to one of its specific implementations/extensions. You should better rethink your design.
An important note on code conventions
In Java it is a must that you name your classes using CamelCase and packages using lowercase, otherwise some quite bad name-resolution anomalies can happen. Not to mention any Java user getting totally lost reading your code.
Comment: Can not emphasize the "You should better rethink your design"-part enough.
Answer: You really don't want to do that as it defeats the idea of inheritance.
You can, however set up abstract functions that are implemented by derived classes. That's good programming style. Those functions can access member data in the derived and base classes.
Doing things like (i) using reflection and(ii) casting to derived classes are hacks and should be avoided. The reason being that changing a derived class should not trigger the necessity for changes in a base class.
Comment: I can read the field names in this way but can read the values.
Answer: What you should do in this case is to define abstract methods in your class a, which class b and c has to implement. You can then call these methods from a to obtain the values set by b and c.
public abstract class a{

// here I want to read the value of name or f1 or f2 or every other field values from derived classes
    abstract String getName();
    abstract String getF1();
    abstract String getF2();
}

public class b extends a{
  private String name;

  @Override
  public String getName() { return name; }

  @Override
  public String getF1() { return null; }

  @Override
  public String getF2() { return null; }
}

public class c extends a{
  public String f1;
  public String f2;

  @Override
  public String getName() { return null; }

  @Override
  public String getF1() { return f1; }

  @Override
  public String getF2() { return f2; }
}

Comment: That's not a great solution either. Now *all* subclasses have to know about all other subclasses' fields.
Comment: @Thilo True, but considering OP's initial code example, I don't think we can avoid it. Having a super class with two seemingly different and unrelated sub classes is not a good idea. We would have to know more about what OP wants to achieve.
Comment: Yes, we need to know what OP really wants to do.
Comment: Considering the OP original request, I see this as the most straight forward and understandable solution. However, I completely agree that its not a great solution and the OPs original design should possibly be reconsidered.
Comment: Man I did it an the dot net framework before. what I want to do is to create a class for creating database methods like insert or select.
I want the top class know the fields from derived class and prepare proper insert command for it.
I can even read the field names in this way but can read the values.
Comment: @EhsanShirzadi Sounds to me like inheritance is not what you want here. What you should do is create a separate class for your insert and create statements (either a class that simply generates the queries, or one that executes them), and it's method should take your domain objects as parameters.


Does Intersector Observer works with Z-indexes?

Question: I am trying to create a frontend logic here, and the requirement is as follows -:

There are 4 UI elements on the screen.
On certian device resolutions, some of these UI elements overflow outside of the screen or get hidden behind the main header component.
I want to prompt the user to change the zoom level of the browser till all of the 4 UI elements are completely visible in their respective position or not.

Initially, I thought of using the Intersection Observer to check the Intersection Ratio of the 4 UI elements. But, I am confused if the intersections observer works when elements are hidden visually, but present on the screen DOM wise?
Answer: You are basically asking two questions:

[how to detect when some element] overflow outside of the screen [or offsetParent…]

That's exactly what intersection observer is for.

[...] or get hidden behind [other positioned element].

Sadly, there is no top-level native API similar to intersection observer for this.
You can only query "what is the topmost element on given coordinates" with elementFromPoint.
So technically it is possible to detect if some element is (partially) obscured by other element, and what obscures it, with combinations of getBoundingClientRect (or getClientRects) and elementFromPoint.  See https://stackoverflow.com/a/1542908/540955 for a simple POC.


Cannot call front() on queue in C++

Question: I am attemtping to access and pop the front element from a queue in C++, but the line
tuple<int, string, future<string>> post = posterVerificationQueue.front();

is underlined in red and gives the error:

function "std::tuple<_This, _Rest...>::tuple(const std::tuple<_This,
_Rest...> &) [with _This=int, _Rest=<std::string, std::futurestd::string>]" (declared at line 320 of "C:\Program Files
(x86)\Microsoft Visual
Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\tuple") cannot
be referenced -- it is a deleted function

I imagine it is an issue with me using a future within a tuple, but not too sure. Here is my code:
#include <iostream>
#include <ctime>
#include <chrono>
#include <thread>
#include <future>
#include <queue>
#include <mutex>
#include <tuple>
#include <map>

#include "TCPClient.h"
#include "ThreadPool.h"
#include "RequestGenerator.h"
#include "ResponseVerifier.h"
#include "Storage.h"

#define DEFAULT_PORT 12345

void readRequest(string serverIp, int threadIndex, double timeDurationSecs);
void postRequest(string serverIp, int threadIndex, double timeDurationSecs);

int readRequests = 0;
int postRequests = 0;

mutex mLock;
map<int, tuple<double, int>> posterThreadMap;
queue<tuple<int, string, future<string>>> posterVerificationQueue;
map<int, tuple<double, int>> readerThreadMap;
Storage* db = new Storage();
RequestGenerator* requestGenerator = new RequestGenerator();

int main(int argc, char **argv)
{
    // Default parameters
    unsigned int posterCount = 5;
    unsigned int readerCount = 0;
    double timeDurationSecs = 10;
    bool throttle = false;
    string serverIp = "127.0.0.1";

    // Validate the parameters
    if (argc != 6) {
        std::cout << "\nUsage (required parameters): server_IP number_of_poster_threads number_of_reader_threads time_duration throttle(0|1)\n\n";
        std::cout << "server_IP - IP of the server\n";
        std::cout << "number_of_poster_threads - number of threads performing POST operations\n";
        std::cout << "number_of_reader_threads - number of threads performing READ operations\n";
        std::cout << "time_duration - duration of test execution in seconds\n";
        std::cout << "throttle(0|1) - 0: do not throttle message speed\n";
        std::cout << "\t\t1: throttle message speed\n\n";

        std::cout << "\nDefault Parameters:\n";
        std::cout << "\tserver_IP - " << serverIp << "\n";
        std::cout << "\tnumber_of_poster_threads - " << posterCount << "\n";
        std::cout << "\tnumber_of_reader_threads - " << readerCount << "\n";
        std::cout << "\ttime_duration - " << timeDurationSecs << "s\n";
        std::cout << "\tthrottle - " << (throttle ? "true" : "false") << "\n\n";

        std::cout << "Enter dev mode using default paramaters?\n";
        system("pause");
    }
    else
    {
        serverIp = argv[1];
        posterCount = (int)argv[2];
        readerCount = (int)argv[3];
        timeDurationSecs = (int)argv[4];
        throttle = (int)argv[5];
    }

    cout << "\nStarting throughput test...\n";

    ThreadPool posterPool(posterCount);
    vector<future<void>> posterFutures;
    vector<tuple<string, int, int>> incorrectPostResponses;
    double posterTotalTime = 0.0; // The total time in seconds that all poster threads took to run

    ThreadPool readerPool(readerCount);
    vector<future<void>> readerFutures;
    double readerTotalTime = 0.0; // The total time in seconds that all reader threads took to run

    for (int i = 0; i < posterCount; i++)
        posterFutures.push_back(posterPool.enqueue(postRequest, serverIp, i, timeDurationSecs));

    for (int i = 0; i < readerCount; i++)
        readerFutures.push_back(readerPool.enqueue(readRequest, serverIp, i, timeDurationSecs));

    for (int i = 0; i < posterFutures.size(); i++)
        posterFutures[i].wait();

    for (int i = 0; i < readerFutures.size(); i++)
        readerFutures[i].wait();

    for (int i = 0; i < posterThreadMap.size(); i++)
    {
        double posterRequestsPerSecond = get<1>(posterThreadMap[i]);
        double threadRunTime = get<0>(posterThreadMap[i]);
        posterTotalTime += threadRunTime;
        std::cout << "\nPoster thread " << i << " (ran for " << threadRunTime << "s) - Average post requests per second: " << posterRequestsPerSecond << "\n";
    }

    // Should verification be optional?
    while (!posterVerificationQueue.empty())
    {
        tuple<int, string, future<string>> post = posterVerificationQueue.front();
        posterVerificationQueue.pop();

        int postIndex = get<0>(post);
        string request = get<1>(post);
        string response = get<2>(post).get();

        tuple<bool, int, int> postVerification = db->addPosterValue(postIndex, request, response);
        bool isValid = get<0>(postVerification);

        if (!isValid)
        {
            int correctResponse = get<1>(postVerification);
            int actualResponse = get<2>(postVerification);
            incorrectPostResponses.push_back(make_tuple(request, correctResponse, actualResponse));
        }
    }

    cout << "\nTotal poster runtime: " << posterTotalTime << "s" << "\n";
    cout << "\nTotal post requests: " << postRequests << "\n";
    cout << "\nAverage post requests per second per thread: " << postRequests / posterTotalTime << "\n";
    cout << "\nIncorrect responses: " << incorrectPostResponses.size() << "\n";

    for (int i = 0; i < incorrectPostResponses.size(); i++)
    {
        tuple<string, int, int> incorrectResponse = incorrectPostResponses[i];
        string request = get<0>(incorrectResponse);
        int correctResponse = get<1>(incorrectResponse);
        int actualResponse = get<2>(incorrectResponse);
        cout << "Incorrect response #" << i + 1 << "\n";
        cout << "Request: " << request << "\n";
        cout << "Expected response: " << correctResponse << "\n";
        cout << "Actual response: " << actualResponse << "\n\n";
    }

    // TODO: Implement the block above for reader threads

    delete db;
    delete requestGenerator;

    system("pause");
    return 0;
}

string sendRequest(TCPClient client, string request)
{
    return client.send(request);
}

void postRequest(string serverIp, int threadIndex, double timeDurationSecs)
{
    TCPClient client(serverIp, DEFAULT_PORT);
    client.OpenConnection();

    int threadPostCount = 0;
    double timeSpan;
    chrono::high_resolution_clock::time_point endTime;
    chrono::high_resolution_clock::time_point startTime = chrono::high_resolution_clock::now();

    do
    {
        /*
            Could limit with
            if (!throttle || (throttle && threadPostCount < (timeDurationSecs * 1000)))
            {}
        */
        string request = requestGenerator->generateWriteRequest();
        mLock.lock();
        future<string> responseFut = async(launch::async, sendRequest, client, request);
        posterVerificationQueue.push(make_tuple(postRequests, request, move(responseFut)));
        postRequests++;
        mLock.unlock();
        threadPostCount++;

        endTime = chrono::high_resolution_clock::now();
        timeSpan = chrono::duration_cast<chrono::duration<double>>(endTime - startTime).count();
    } while (timeSpan < timeDurationSecs);

    double totalRunTime = (endTime - startTime).count();
    double posterRequestsPerSecond = threadPostCount / timeSpan;

    tuple<double, double> returnValues = make_tuple(timeSpan, posterRequestsPerSecond);
    mLock.lock();
    postRequests += threadPostCount;
    posterThreadMap[threadIndex] = returnValues;
    mLock.unlock();

    client.CloseConnection();
}

void readRequest(string serverIp, int threadIndex, double timeDurationSecs)
{
    //return 0.0;
}

Comment: Try to change the initialization to `= std::move(posterVerificationQueue.front());`.
Comment: imho, tuple> post cannot be copied.
Comment: Please remove all unecessary code and add the necessary code to make it as close as possible to being compilable. See [mre]. [Example](https://godbolt.org/z/TPTE8rxKG)
Comment: To clarify, your code is attempting to make two instances of the same `std::future`, which is not permitted.  The error is saying "copy construction has been deleted."
Answer: std::tuple<_This, _Rest...>::tuple(const std::tuple<_This, _Rest...> &)
...
cannot be referenced -- it is a deleted function

Well, that's the tuple copy constructor, right?

I imagine it is an issue with me using a future within a tuple, but not too sure.

Let's check the documentation for the constructors of std::future ...

future( const future& other ) = delete;

std::future is not CopyConstructible.

So I'd say your imagination was correct. You can't copy the tuple, because it can't copy one of its members.
You can use std::move to move construct from the queue element, but remember it would be a problem if you didn't pop the front immediately after (in the code shown, you do this, so it's fine).

Cannot call front() on queue in C++