Como fazer uma consulta mysql semanal

Question: Bom dia a todos! Gostaria de um Help!!!
Estou na duvida de como fazer uma consulta mysql semanal, começando na segunda e finalizando no domingo, sendo que os dados vai ser inserido todos os dias, e a partir que os dados for inserido vai somando um valor e quando for na segunda feira ele começa a soma novamente, sendo que ele não pode somar com a semana anterior
exemplo da consulta que eu fiz, mas não estou obtendo êxito:
SELECT id, data, valor
FROM pagamento
WHERE WEEK(data ,7) = WEEK(NOW())
  AND reftype = 'credito'
  AND status != 99

Comment: Você tentou week(NOW(), 7), para que ambas as contagens tenham o mesmo início?
Comment: ja sim, nao dar certo.
Comment: E você chegou a imprimir o resultado de suas funções e se efetivamente existem dados para os demais dias da semana?
Comment: sim, eu coloquei os dados do dia 27/05/2019 ate o dia 03/06/2019 e ele me retornou ate o dia 02/06/2019, como já inserir um dados de outra segunda feira que no caso é o dia 03, ele era para retornar so o valor do dia 03 ou não?
Comment: Não, dia 03 já não pertence a semana do dia de hoje (supondo que hoje seja 27/05/2019).
Comment: entao quando for na segunda dia 03/06/2019 ele vai somar do dia 03/06 em diante?
Comment: Não, sua query não faz isso, ela apenas lista as linhas da semana corrente (com as restrições acima). Ela também não soma nada.
Comment: Tente um  Group By com Rollup , e diga o que deu errado.
Comment: entao, eu sei que para somar vou ter que colocar sum(valor), quero listar primeiro para ver se esta vindo correto os dados da semana
Comment: Por acaso você quer obter os totais por semana de todos os dados existentes em sua tabela e que o início de cada semana seja considerado a segunda-feira?
Answer: Você pode criar uma função para calcular o primeiro dia da semana:
CREATE FUNCTION PRIMEIRO_DIA_DA_SEMANA(dia DATE)
RETURNS DATE DETERMINISTIC
BEGIN
  RETURN SUBDATE(dia, WEEKDAY(dia));
END

E depois utilizar para pegar os valores entre esta data:
SELECT p.id,
       p.data,
       p.valor
FROM pagamento
WHERE reftype = 'credito'
  AND status <> 99
  AND p.data >= PRIMEIRO_DIA_DA_SEMANA(NOW())
  AND p.data < PRIMEIRO_DIA_DA_SEMANA(DATE_ADD(NOW(),INTERVAL 1 WEEK))

E para  conseguir o total você precisa apenas do SUM do valor:
SELECT SUM(p.valor) AS total
FROM pagamento
WHERE reftype = 'credito'
  AND status <> 99
  AND p.data >= PRIMEIRO_DIA_DA_SEMANA(NOW())
  AND p.data < PRIMEIRO_DIA_DA_SEMANA(DATE_ADD(NOW(), INTERVAL 1 WEEK))

Referência: How do I get the first day of the week of a date in mysql?
Comment: Bom dia, funcionou aqui!!!, obrigado pela o empenho e dedicação.

Como fazer uma consulta mysql semanal


Scoring rules for time series data

Question: I have found quite a lot of articles about scoring rules that seem to first work out theorems and proofs for scoring rules in an iid setting, after which they proceed to apply them to some time series data (such as financial returns). However, I'm unable to find a paper that somewhat rigorously describes how to translate concepts such as (strict) propriety from an iid (or single observation) setting to a time series forecasting context. Do you happen to know any sources on the technical details and use of scoring rules for time series?
For example, what is the usual way to define propriety for a scoring rule in a time series context? Suppose $S$ is some scoring rule. I was thinking about something like defining an 'asymptotic' expectation first. If $A$ is some predictive model, define $S(A, Y_T) = \frac{1}{T}\sum_{t=1}^T S(A_{t|t-1}, y_t)$. For some 'true model' $D$ we then assume $\lim_{T\to\infty} S(A, Y_T) = S(A, D)$ for some constant $S(A, D),$ $D-$a.s. I would then call $S$ proper (or 'asymptotically' proper perhaps?) if $S(A, D)\geq S(D, D)$ for all $A, D$. Is this a sensible definition for propriety of a scoring rule in a time series context, or is a different definition generally used?
I also find it hard to generalize this notion of propriety to strict propriety, since models might differ only for some finite number of observations and be the same after that, which would still result in the same score, while being different. So similarly, does someone here happen to know how strict propriety of scoring rules is usually defined for time series?
Comment: Maybe the initial discussion here is useful? https://www.ecb.europa.eu//pub/pdf/scpwps/ecbwp1017.pdf
Comment: @hejseb: thanks for the suggestion. I indeed read that paper and that is where I originally got the question (and my proposed definition) from. However, they do not really discuss what localness and propriety mean in a time series context, but instead refer to some sources that treat scoring rules in a single observation or iid setting.
Answer: From what I have seen, people will work with the "iid definitions" of (strict) propriety and pretty much work "pointwise", even in time series forecasting contexts.
For examples, see papers of Gneiting and colleagues, who routinely illustrates his papers with meteorological forecasts. I am certainly no expert in meteorological forecasting, but judging from what I have seen, this approach is common there, all the way back to Brier's (1950) original paper.
For a recent example, take a look at Ehm et al. (2016, with discussion). Ehm et al. and discussants also refer to Strähl & Ziegel (2015), who specifically look at calibration in a time series context, and even they (section 5.3) use this "pointwise" approach.
Bottom line: the "pointwise" approach seems to be the state of the art for scoring rules in time series. Of course, that does not mean it is correct.
Answer: I don't see a reason why we would need some extra definition for the time series situation. The definitions of scoring rules and (strict) propriety do not require any assumption on the dependence between different observations, in particular no i.i.d. assumption. Hence, they are perfectly valid, and also commonly applied, in forecast evaluations based on time series data.
To be precise, a scoring rule assigns a score $S(G, y)$ to any pair of probability distribution $G$ and observation $y \in \mathbb{R}^d$. The distribution $G$ could be anything from the success probability $p \in [0, 1]$ of a binary outcome to a density function on the real numbers. $S$ is proper if
$$
\mathbb{E}_{Y \sim F} S(F, Y) \le \mathbb{E}_{Y \sim F} S(G, Y)
$$
for all $F, G \in \mathcal{G}$, where $\mathcal{G}$ is some class of distributions. It is strictly proper if equality of the expectations implies $F=G$. In other words, the true distribution of the observation minimizes the expected score. There is no dependency assumption involved and we could also rewrite this definition such that no random variable appears, at all.
In a time series setting, a forecaster would have some information at time $t-1$ specified by some $\sigma$-algebra $\mathcal{F}_{t-1}$ and would produce some forecast $G_t$ of the distribution of $Y_t \vert \mathcal{F}_{t-1}$. To judge whether one forecaster achieves lower expected scores than a competitor, we would estimate the score difference of their predictions $(G_t)$ and $(H_t)$ via
$$
\frac{1}{n} \sum_{t=1}^{n} \left( S(G_t, y_t) - S(H_t, y_t) \right) .
$$
If the $Y_1, \ldots, Y_n$ are i.i.d. this estimates the expected scores w.r.t. a single $Y$, i.e. $\mathbb{E} (S(G, Y) - S(H, Y) )$. For a general time series we need to add assumptions like stationarity or ergodicity to ensure that we estimate something meaningful. Although we then estimate some mixture of expected scores (since the distribution of the $Y_t$ varies), propriety still ensures that high positive or negative values indicate differences in predictive performance.
For the definition and more background on proper scoring rules see Gneiting and Raftery (2007). Strictly Proper Scoring Rules, Prediction, and Estimation.

Scoring rules for time series data


Transformation of dependent variable for MARS algorithm?

Question: I am just wondering if its necessary to transform a dependent variable as it is a large monetary value? I'm unsure if its necessary with a non-parametric methods such as MARS. When I do a log transformation my Rsq value is improved, is this indicative of a worthy transformation?
Answer: The performance of MARS in terms of $R^2$ is theoretically independent of linear changes in scale.  I frequently use MARS to model potentially large monetary values, and in my experience the log transformation, or Box-Cox or whatever, can be essential to prevent over-fitting.  (This is not a contradiction, since such transformations are nonlinear, which is why they work).  However, an improvement in $R^2$ (especially if on the training set) is not necessarily an indication of that the log model is better.  In fact, there is not a simple relationship between $R^2$ as computed on the original scale and $R^2$ on a log scale.  When comparing predictive models across nonlinear monotonic transformations, you should use order-based statistics such as Spearman's rank correlation coefficient, which are fixed under such transformations.
Finally, as you may be aware, you can't transform your predictions on the log scale back to the original data scale simply by inverting the log transformation.  In general you'll probably need to fit some kind of nonlinear univariate monotone function to get back to monetary scale.


Error:(11, 0) Declaring custom 'clean' task when using the standard Gradle lifecycle plugins is not allowed

Question: Hello i am working now on android application with 2 modules the first is my app with buildgradle like
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.alexvasilkov:android-sign-release:0.8.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'com.alexvasilkov.sign'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "dz.condorpos"
        minSdkVersion 17
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            storeFile file("foldable-layout-release-key.keystore")
            keyAlias "release"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile project(':library')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.squareup.okhttp3:okhttp:3.8.1'
    compile 'com.github.barteksc:android-pdf-viewer:1.4.0'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.alexvasilkov:android-commons:2.0.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.afollestad:easyvideoplayer:0.3.0'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.google.firebase:firebase-database:10.0.1'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
    compile 'com.google.firebase:firebase-storage:10.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'

    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

the second module is a library included to my project here is the buildgradle(module:library):
apply plugin: 'com.android.library'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
    }
}
// New version can be uploaded with 'gradlew clean :library:jar :library:uploadArchives'
apply from: 'gradle-mvn-push.gradle'

dependencies {
}

the project buildgradle is like :
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {

        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects { project ->
    repositories {
        jcenter()
        maven { url 'https://dl.bintray.com/drummer-aidan/maven' }
    }
    // Enabling checkstyle for all sub projects
    project == rootProject || project.afterEvaluate {
        project.apply plugin: 'checkstyle'

        project.extensions.getByName('checkstyle').with {
            toolVersion = '6.15'
            configFile file("${rootDir}/checkstyle.xml")
        }

        task checkstyle(type: Checkstyle) {
            source 'src'
            include '**/*.java', '**/*.xml'
            classpath = files()
        }

        project.tasks.getByName('check').dependsOn 'checkstyle'

        project.extensions.getByName('android').with {
            lintOptions {
                ignore 'GoogleAppIndexingWarning', 'ContentDescription'
            }
        }

    }
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
}

the project was working perfectly till yesterday when i added a compile dependencies of picasso in my app module after the gradle sync failed it show this
 Error:(11, 0) Declaring custom 'clean' task when using the standard Gradle lifecycle plugins is not allowed.

now even if i remove picasso the error still happening Of course I did not ask the question before long research i found some solutions but didnt work like this
note : an old version of my project still working normal with the same clean task but after some gardle syncs i will get this problem.
I would like to thank you in advance for your assistance
Comment: Possible duplicate of [Declaring custom 'clean' task when using the standard Gradle lifecycle plugins is not allowed](https://stackoverflow.com/questions/43933459/declaring-custom-clean-task-when-using-the-standard-gradle-lifecycle-plugins-i)
Answer: After so many research i found we have to just comment the line of clean task in bulid.gradle(Project) like below :
   //    task clean(type: Delete) {
        //        delete rootProject.buildDir
        //    }][1]


When rotating 2D sprite towards cursor via angularVelocity, it spins at one point

Question: Intro
I've created a spaceship sprite in my Unity project, I wanted it to rotate towards the cursor via angular velocity, because I'd like make my game to be heavily physics based.
Problem
Now my problem with rotating the sprite via by angular velocity is the following:
At -180° / 180° rotation my ship spins around, because while my mouse's angle is already 180°, while my ship's rotation is still -180°, or the other way around.
I tried
I tried to solve it mathematically, wasn't too successful, I could make it spin the right way just much slower/faster, I could fix the 180/-180 point, but made two different ones instead.
Looked for different solutions, but couldn't find a more fitting one.
Code
So I have this code for the rotation:
// Use this for initialization
void Start () {
    rb = gameObject.GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update () {
    //getting mouse position in world units
    mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    //getting the angle of the ship -> cursor vector
    angle = Mathf.Atan2(mousePos.y - transform.position.y, mousePos.x - transform.position.x) * Mathf.Rad2Deg;

    //getting the angle between the ship -> cursor and the rigidbody.rotation vector
    diffAngle = angle - (rb.rotation + 90);

    //Increasing angular velocity scaling with the diffAngle
    rb.angularVelocity = diffAngle * Time.deltaTime * PlayerShipStats.Instance.speed * 100f;

Thank you for your contribution in advance
Solution for Problem 1
Inserting this code made it work, not for long :
if(diffAngle > 180) {
        diffAngle -= 360;
    } else if (diffAngle < -180) {
        diffAngle += 360;
    }

Problem 2 and Solution for Problem 2
The new problem is:
rigidbody.rotation can exceed it's boundaries, it can be rotated for more than 360 degrees.
this code patched this bug:
if(rb.rotation + 90 >= 180) {
            rb.rotation = -270;
        } else if (rb.rotation + 90 <= -180) {
            rb.rotation =  90;
        }

The perfect code
void AimAtTarget(Vector2 target, float aimSpeed) {

    //getting the angle of the this -> target vector
    float targetAngle = Mathf.Atan2(target.y - transform.position.y, target.x - transform.position.x) * Mathf.Rad2Deg;

    if (rb.rotation + 90 >= 180) {
        rb.rotation = -270;
    } else if (rb.rotation + 90 <= -180) {
        rb.rotation = 90;
    }

    //getting the angle between the this -> target and the rigidbody.rotation vector
    float diffAngle = targetAngle - (rb.rotation - 90);

    if (diffAngle > 180) {
        diffAngle -= 360;
    } else if (diffAngle < -180) {
        diffAngle += 360;
    }

    //Increasing angular velocity scaling with the diffAngle
    rb.angularVelocity = diffAngle * Time.deltaTime * aimSpeed * 100;
}

Comment: You should normalize the angle difference so that it is always in the -180°..180° range. I.e., `if(diffAngle>180) diffAngle -=360;` etc. By the way, does `Mathf.Atan2` return degrees or radians?
Comment: @LutzL I actually use Mathf.Clamp to limit the turning speed, but I wanted to make my code less dense for this post. Sadly, even if I detect, diffAngle is more than 180, I can't make the rotation smooth. It would be bad to have one side, where the sensitivity of your rotation is different. Mathf.Atan2 returns radian and deals with the tangential exceptions.
Comment: Are you sure `rb.rotation` is also in radians? It would seem to contradict the `90` correction used, as I suppose that means a right angle. -- What I proposed is not a cutting but a correction by `2*pi` resp 360° which gives the same position on the unit circle but a different angle. A similar correction would have to be made for `diffAngle<-180` by adding a full circle.
Comment: Rb.rotation returns degrees but this script works perfectly fine until you reach that turnin point.
Comment: Sorry, with the answer I looked at the end of the line where you indeed have the `Rad2Deg` conversion factor. So only the centering problem remains, which is discussed in the answer, and perhaps the discussion what kind of equation (differential if the `dt` is an indication) you are using for the angle dynamics.
Comment: I realized your first comment was just as good as the answer, I was just too tired at that point.
Answer: There are two problems I see here:
Problem 1
angle is always going to be between -180 and 180, while  rb.rotation is between 0 and 360. So you are comparing angles using two different notations. The first step is to get both angles returning -180 to 180 or 0 to 360. I chose to do the following which puts both angles between -180 and 180:
//getting the angle of the ship -> cursor vector
float targetAngle = Mathf.Atan2(
    mousePos.y - transform.position.y,
    mousePos.x - transform.position.x) * Mathf.Rad2Deg;

//get the current angle of the ship
float sourceAngle = Mathf.Atan2(
    this.transform.up.y,
    this.transform.up.x) * Mathf.Rad2Deg;

Problem 2
If you fix problem 1 and tried your app you would notice that the ship sometimes rotates the wrong way, although it will eventually get to its target. The problem is that diffAngle can sometimes give a result that is greater than +180 degrees (or less than -180). When this happens we actually want the ship to rotate the other direction. That code looks like this:
//getting the angle between the ship -> cursor and the rigidbody.rotation vector
float diffAngle = targetAngle - sourceAngle;

//use the smaller of the two angles to ensure we always turn the correct way
if (Mathf.Abs(diffAngle) > 180f)
{
    diffAngle = sourceAngle - targetAngle;
}

I made a simple Unity to verify this works. I was able to rotate my ship in either direction smoothly.
One thing you may have to handle, if you don't already, is appropriately stopping the rotation of the ship when the it is facing the cursor. In my test I noticed that the ship would jitter slightly when it reached its target because it would (very) slightly overshoot the cursor's angle in one direction and then the other. The larger the value of PlayerShipStats.Instance.speed the more pronounced this effect will likely be.
Comment: Actually I didnt have a problem 1, `angle` and `(rb.rotation - 90)` returned the same angle at the same point (on a {-180, 180} interval). But your answer to my "problem 2" should work, I'll try it asap. Thank you.
Comment: I updated my question to include the answer, Ultimately you and @LutzL figured it out, I just changed it a bit to fit the context. No jitter at all. Thank you guys


How to make my Google Map follow the user at all times and not let them scroll away

Question: I have a GMSMapView connected to my mapView variable. It is all set up and even puts a random polyline on the map for the user. Currently I have a "navigate" button but all it does is zoom in on the user. I would like to make it so once they hit "navigate" it will make the camera follow the user and not let them scroll away from their location (much like the Google Maps app). How can I make this possible? Thanks!
Answer: I'm assuming you've already gotten a CLLocationManager and have started updating user's location with it. Once that's done, you want to set the mapView's camera in the CLLocationManager's delegate method whenever the location changes.
Something along the lines of this:
<code>func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = manager.location {
        // Create camera with the user's new location
        let camera = GMSCameraPosition.cameraWithLatitude(location.coordinates.latitude, longitude: location.coordinates.longitude, zoom: 17.0)
        // Animate the map to the new camera position
        mapView.animateToCameraPosition(camera)
    }
}
</code>
Play around with the zoom parameters to get the result you desire.
Hope it helps.
Comment: so this method runs whenever it notices that the users location has changed? Does it only run when "manager.startUpdatingLocation()" has happened? Does it stop when "manager.stopUpdatingLocation()" gets called?
Comment: and in your opinion where would be a good place to first call startUpdatingLocation?
Comment: @skyleguy Yes. That particular delegate method gets called whenever the user's location changes. [Apple's docs] (https://developer.apple.com/reference/corelocation/cllocationmanagerdelegate) states that it gets called whenever there is new location data available. That _usually_ means when the user's location changes. The delegate method will stop when stopUpdatingLocation() is called.

As for a good place to startUpdatingLocation, it largely depends on your use case. From your initial question, I think viewDidLoad might be a good place for you to do it.


How to prove that $ x_n $ converges when $ 2x_{n+1}+x_n $ converges by using Stolz–Cesàro theorem?

Question: I have already know that by using standard method, we can get that $ x_n $ converges when $ 2x_{n+1}+x_n $ converges. However my teacher said we can use the Stolz–Cesàro theorem to prove this statement. Any hints are welcome.
Comment: What is Stolz theorem?
Comment: It is Stolz–Cesàro.
Comment: Maybe writing $x_n = x_0 + \sum_{i=0}^{n-1} (x_{i+1}-x_i)$ could help?
Comment: I know the Cesaro-Stoltz theorem is applied to sequences of type $x_n=\frac{a_n}{b_n}$ where $b_n$ is incriesing: if $\lim_{n\rightarrow\infty}\frac{a_{n+1}-a_n}{b_{n+1}-b_n}=l$,  then and $\lim_{n\rightarrow\infty}x_n=l$. The reciproc is not true in general.
Answer: If $\ c_n=2x_{n+1}+x_n\rightarrow\ell\ $ as $ n\rightarrow\infty\ $, then
\begin{align}
\frac{2^{n+1}x_{n+1}-2^{n-1}x_{n-1}}{2^{n+1}-2^{n-1}}&=\frac{2^n\big(2x_{n+1}+x_{n}\big)-2^{n-1}\big(2x_{n}+x_{n-1}\big)}{2^{n+1}-2^{n-1}}\\
&=\frac{2^nc_{n}-2^{n-1}c_{n-1}}{2^{n+1}-2^{n-1}}\\
&=\frac{2c_{n}}{3}-\frac{c_{n-1}}{3}\\
&\rightarrow\frac{\ell}{3}\ \ \text{ as }\ n\rightarrow\infty\ .
\end{align}
Let $\ a_r=2^{2r-1}x_{2r-1}\ $, and $\  b_r=2^{2r-1}\ $, then $\ b_r\ $ increases monotonically to $\ \infty\ $, and from above we have
\begin{align}
\frac{a_{r+1}-a_r}{b_{r+1}-b_r}&=\frac{2^{2r+1}x_{2r+1}-2^{2r-1}x_{2r-1}}{2^{2r+1}-2^{2r-1}}\\
&\rightarrow\frac{\ell}{3}\ \ \text{ as }\ r\rightarrow\infty\ .
\end{align}
Therefore, by the Stolz–Cesàro theorem,
$$
\lim_{r\rightarrow\infty}\frac{a_r}{b_r}=\frac{\ell}{3}=\lim_{r\rightarrow\infty}x_{2r-1}\ .
$$
Now from the identity $\ x_{2r}=\frac{c_{2r-1}-x_{2r-1}}{2}\ $, we obtain
$$
\lim_{r\rightarrow\infty}x_{2r}=\lim_{r\rightarrow\infty}\frac{c_{2r-1}-x_{2r-1}}{2}=\frac{\ell}{3}\ .
$$
Thus, since both the even and odd terms of the sequence $\ \big\{x_n\big\}_{n=1}^\infty\ $ converge to the same limit, $\ \frac{\ell}{3}\ $, so does the sequence itself.


Setup DNS on Windows Server 2012 with DHCP running router connected to it

Question: I have a Cisco router connected to a server running a fresh installation of Windows Server 2012.
What should I do to configure DNS on the server if I leave the DHCP enabled on the Cisco router?
Answer: You can have DHCP from any source you like.  If you have active directory in your environment its much better to have dns running on the AD server and have the clients register themselves in DNS. The only benefit that you would get from keeping DHCP on the windows server is that you can have DHCP register clients that don't auto register.
Answer: You have two choices here, you can configure DNS on the router/firewall if it can, or you can enable DNS on the Windows 2012 Server and let that handle it. Personally, I prefer to have both those functionalities in the same spot, so I would check if the Cisco (assuming its an ASA) has that available, and if it's an ASA, it should.
Comment: If he's using AD, he'll want dns on the windows server.
Answer: Since DNS is required to set up AD, this decision must be resolved before installing and configuring AD.  The setup wizard for Windows Server defaults to installing DNS on the first AD server in the forest, along with the AD role.
This is a necro'd question, but if anyone has this question, the best recommendation is to let Windows set up your DNS with the server when you add the AD role.  Personally, I prefer managing DHCP through the Windows interface, so I would move that to the same Windows server.
Bottom line, AD requires DNS, it does not require DHCP.  If you prefer managing DNS on a Linux host, and many do, just be sure to have the details available when you set up your AD so that AD will tie to DNS correctly.  If you intend to have DHCP in your environment, set it up where it makes the most sense for your environment.


Protractor + cucumber - if assertion fails test execution stops abruptly

Question:
Cucumber Test Scenario

@login
Scenario: Test signin link
Given the user goes to "example.com"
When the user clicks on login button
Then the current page is the login page

Hi, Whenever chai/'Chai as promise' assertion fails my test execution stops abruptly, instead of making the corresponding cucumber step fail. If a scenario has 5 cucumber DSL step and if assertion fails in 2nd step test execution I expect test result should be

1 scenario (1 failed)
5 steps (1 failed, 3 skipped, 1 passed)

But I get test result like below with error code 199

Step Definition

this.When(/^the user clicks on login button$/, function() {
        browser.ignoreSynchronization = false;
        return browser.wait(wagHomePage.elements.signIn.isDisplayed().then(function(visible) {
            if (visible) {
                wagHomePage.elements.signIn.click().then(function() {
                    expect(visible).to.be.true;
                });
            }
            else {
                chai.assert.isTrue(false);
            }
        }));
    });

    this.Then(/^the current page is the login page$/, function() {
        expect(wagLoginPage.elements.pageIdentifier.isDisplayed()).to.eventually.be.true;
    });

@login
  Scenario: Test signin link
  √ Given the user goes to "example.com"
[19:58:02] E/launcher - expected false to be true
[19:58:02] E/launcher - AssertionError: expected false to be true
    at doAsserterAsyncAndAddThen (C:\JS_UIAutomation\node
_modules\chai-as-promised\lib\chai-as-promised.js:293:29)
    at .<anonymous> (C:\JS_UIAutomation\node_modules\chai
-as-promised\lib\chai-as-promised.js:283:21)
    at get (C:\JS_UIAutomation\node_modules\chai\lib\chai
\utils\overwriteProperty.js:50:37)
    at Function.assert.isTrue (C:\JS_UIAutomation\node_mo
dules\chai\lib\chai\interface\assert.js:332:31)
    at C:\JS_UIAutomation\example_site_tests\step_defin
itions\wagLogin_definition.js:23:29
    at elementArrayFinder_.then (C:\Users\username\AppData\Roaming\npm\node_modules\protractor\lib\element.ts:840:
22)
    at ManagedPromise.invokeCallback_ (C:\Users\username\AppData\Roaming\npm\node_modules\protractor\node_modules\
selenium-webdriver\lib\promise.js:1366:14)
    at TaskQueue.execute_ (C:\Users\username\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-web
driver\lib\promise.js:2970:14)
    at TaskQueue.executeNext_ (C:\Users\username\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium
-webdriver\lib\promise.js:2953:27)
    at asyncRun (C:\Users\username\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib
\promise.js:2813:27)
[19:58:02] E/launcher - Process exited with error code 199

Please help me to get proper test result like

1 scenario (1 failed)
5 steps (1 failed, 3 skipped, 1 passed)
Comment: I don't get this piece of code `return browser.wait(wagHomePage.elements.signIn.isDisplayed().then(function(visible) {
            if (visible) {
                wagHomePage.elements.signIn.click().then(function() {
                    expect(visible).to.be.true;
                });
            }
            else {
                chai.assert.isTrue(false);
            }
        }));`
You are first waiting for the element to be displayed, if it is visible, you are clicking on something (that resolves in a promise) and then use the previous result in an expect. Can you explain this?
Comment: Sometimes click action is not performing even-though element is visible. so   to make sure the click action is performed i added a promise expect(visible).to.be.true; but i can remove that. Irrespective of this line i face this issue. Please help
Comment: What is the exact line of code that fails, in the log it says `C:\JS_UIAutomation\example_site_tests\step_definitions\wagLogin_definition.js:23:29`. Can you add a string to your expect like this `expect(visible).to.equal(true, 'Descriptive message: ');`
Comment: It is failing in the else part Chai.assert (which is wagLogin_definition.js:23:29).
Answer: I think I see the problem, it looks like you are not implementing the browser.wait() in a correct way. According to the docs it should consist out of a:

condition: The condition to wait on, defined as a promise, condition object, or a function to evaluate as a condition.
opt_timeout: How long to wait for the condition to be true.

Your code is this
return browser.wait(wagHomePage.elements.signIn.isDisplayed().then(function(visible) {
    if (visible) {
        wagHomePage.elements.signIn.click().then(function() {
            expect(visible).to.be.true;
        });
    }
    else {
        chai.assert.isTrue(false);
    }
}));

It should be more like this
// Wait 3 seconds for the element to appear and click on it
// If not the wait wail fail by rejecting the promise with the custom message
return browser.wait(function(){
    return wagHomePage.elements.signIn.isDisplayed()
    .then(function(visible){
        if (visible) {
           // click on the element
           wagHomePage.elements.signIn.click();
           return true;
        }
        // Not visible yet, but it is in the DOM, then try again
        return false;
    }).catch(function(notFound){
        // Element not found in the DOM, try again
        return false;
    });
}, 3000, 'Element not found within 3 seconds');

Keep in mind that isPresent() checks if the element is present in the DOM, isDisplayed() checks if the element is present in the DOM AND visible. If you do a check on isDisplayed() you need to do the catch();
Hope this helps.
Comment: Thank you so much :). This resolved my issue. Now if the element is not visible it throws error message 'Element not found within 3 seconds' and makes corresponding DSL step to fail and move on to execute next test case.Test execution didn't stop abruptly. Thanks !!! :)
Comment: @ThangakumarD, you are welcome. Is [this](http://stackoverflow.com/questions/43333350/protractor-cucumber-element-not-visible-even-though-element-is-visible/43333484?noredirect=1#comment73767697_43333484) also related, and if so, can you link to this answer? Then the circle is round again ;-)
Comment: Yes.Both are related. I copied a link [here](http://stackoverflow.com/questions/43333350/protractor-cucumber-element-not-visible-even-though-element-is-visible/43333484?noredirect=1#comment73775395_43333484). Is this enough ? or is any other way to link answer?
Comment: @Thangakumar, this is good, I also edited your other post with a link to this answer. Grtz


Visual Studio gray text background, how to remove it?

Question: I have the following in a cshtml file

It's not selected, it's like this, gray text background.
How to understand what is this text in the "font and color" settings, and reset it to the white/transparent normal background?
Comment: Have you got Find or Find and Replace open?
Comment: I have nothing open, this my "default" VS display of cshtml files... (
Comment: Oh, I think that's just how it looks in cshtml, so you can tell what's c# and what's html. Unfortunately I don't know how to disable it though.
Answer: You can disable or change the background color for razor code as follows:
Visual Studio > Tools > Options > Environment/Fonts and Colors > Display items: HTML Razor Code Background; Item background:'Automatic'
Answer: You can disable or change the background color for razor code as follows:
Visual Studio > Tools > Options > Environment/Fonts and Colors > Display items:HTML Razor Code Background.
To 'erase' change Item background from 'default' to 'white'


Unsubscribe from observable before interval fired again

Question: I'm developing an angular 5 application where I have an Observable like this one:
Observable.interval(10000)
    .takeWhile(() => !this.zeServerIsOnline)
    .subscribe(i => {
        this.systemService.isServerOnline().subscribe(data => {
            if(data.success) {
                this.zeServerIsOnline = true;
                this.serverPolledForState = false;
                if(this.bookingsInStorage > 0) {
                    this.allBookingsSubmitted = false;
                    this.sendSavedBookingsToServer();
                }
            }
        }, error => this.isServerOnlineFailed(error));
    });

i first thought, that the observable gets directly unsubscribed, when my Boolean this.zeServerIsOnline gets true but it gets unsubscribed, when again 10 seconds are over and the observable recognizes the state of my Boolean (this.zeServerIsOnline) is true than.
So if i now recognize, that my server is online again (this.zeServerIsOnline = true), i'm starting transmitting data (and i thought that this is the place, when the observable is unsubscribed) But now, when the server goes offline again while i'm transmitting data and 10 seconds are not over my Observable triggers again because it didn't recognize the switch from false to true to false.
Only when my server is online longer than 10 seconds, my observable gets unsubscribed. So it must have sth. to do with the interval but how do i directly unsubscribe, when this.zeServerIsOnline gets true?
Answer: Create a variable type of ISubscription
subscription: ISubscription;

Let's think you need to unsubscribe this.systemService.isServerOnline(). You could do it like:
this.subscription = this.systemService.isServerOnline().subscribe(data => {
            if(data.success) {
                this.zeServerIsOnline = true;
                this.serverPolledForState = false;
                if(this.bookingsInStorage > 0) {
                    this.allBookingsSubmitted = false;
                    this.sendSavedBookingsToServer();
                }
            }
        }, error => this.isServerOnlineFailed(error));

Or if you need to unsubscribe Observable.interval(10000) you could do it like:
this.subscription = Observable.interval(10000)
      .takeWhile(() => !this.zeServerIsOnline)
      .subscribe(i => {
        this.systemService.isServerOnline().subscribe(data => {
          if (data.success) {
            this.zeServerIsOnline = true;
            this.serverPolledForState = false;
            if (this.bookingsInStorage > 0) {
              this.allBookingsSubmitted = false;
              this.sendSavedBookingsToServer();
            }
          }
        }, error => this.isServerOnlineFailed(error));
      });

And now you could directly unsubscribe it:
this.subscription.unsubscribe();

You can directly unsubscribe what ever subscription in this way.
Hope this will help you!
Comment: Thanks for your answer coder, i'm new to rxjs so who do i trigger a 10 second interval than on that subscription? So i need to call it every 10 seconds and unsubscribe than inside my `this.sendSavedBookingsToServer()` function.
Comment: you could get the `interval(10000)` subscription into that `this.subscription` variable and unsubscribe it inside `this.sendSavedBookingsToServer()` function using `this.subscription.unsubscribe();`
Comment: @Sithys Glad to hear it!


Reporting standard error on gain using Bayesian A/B testing

Question: I am building a bayesian A/B testing code in python to compare conversion rates between two samples which I will call $A$ and $B$. My aim is to produce a mean conversion rate, in percentage, for $A$ and a mean conversion rate, in percentage, for $B$ then report a gain of $A$ over $B$ with an error on the gain.
The code is pretty straightforward and this is not a coding question but I will poste it anyway:
<code>from scipy.stats import beta

# class for bayesian AB testing
class BayesABTest:

    # get beta distribution function from total players and those who came back
    def getBetaDistribution(self, total, cameBack):
        a = cameBack + 1
        b = total- cameBack + 1
        return beta(a, b)

    # calculate gain between two samples for active and passive players
    def getGain(self, totalA, cameBackA, totalB, cameBackB):
        beta1 = self.getBetaDistribution(totalA, cameBackA)
        beta2 = self.getBetaDistribution(totalB, cameBackB)
        gain = (beta1.mean() - beta2.mean())*100
        return gain, beta1, beta2
</code>
Now the gain in percentage is pretty simple to compute as the difference between the means of the two beta distributions. The error, however, is a bit less obvious to me. In a usual setting, I would compute the two standard errors on the means of each sample, add them, then take the square root like so:
$$
SE_{diff} = \sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}
$$
But since I transformed my means into distributions, I am not sure how this works. So my question are:

How can I compute the standard error on a beta distribution?
Can I simply report the error as the square root of the sum of the two standard deviations of the beta distributions squared like so : $error = \sqrt{s_1^2 + s_2^2}$

Thanks for the help!
Comment: Here's a computational way to get what you want: You have the posterior distribution of the sucess probability p (which is beta(a, b) for each variant A, B. Simulate random values from both posterior distributions (say 10000 each), getting two arrays of 10,000 samples each for A and B. Then, take the difference of these two arrays to get the posterior distribution for pr(success A) - pr(success B), from which you can take the empirical mean, standard deviation, or any other quantity of interest you'd like.
Comment: You could just simulate it.  Since you're using a conjugate prior, just sample from each posterior and estimate the standard error through sampling.
Comment: Thank you both for your input. @aranglol I tried simulating random values from both posterior distributions then compute the difference as you suggest. It seems to me that the parameters of this new posterior distribution for pr(success A) - pr(success B) depend entirely on the number of random values simulated... I can get either a very low standard error by doing so or a very large one if I only take, say, 100 random values. Any thoughts on this?
Comment: Also, can is it not safe to assume that a standard deviation in a Bayesian posterior such as mine is equal to the standard error? Such thing would imply that I can simply consider that simulating n random variables from both posteriors and taking the difference then taking the standard deviation will suffice to report an error on the difference in means.
Comment: @bmasri What you are observing is Monte Carlo error, not the error in your parameter that you are trying to estimate. You should start to see convergence in the estimated standard deviation for an arbitrarily large number of samples. For your second question, yes! I think there might be some confusion with frequentist vs. Bayesian statistics here. In Bayes land, there isn't really a notion of "standard error" because that speaks to a sampling distribution, a frequentist idea. We don't work with sampling distributions, because you have the exact distribution already based on your model and...
Comment: ...prior beliefs. A typical procedure, once you have distribution of pr(success on A) - pr(sucess on B) is to take say, the 5% and 95% quantiles of this distrbution and state that the true effect lies in this range with 90% probability. This is a 90% credible interval, which is analogous to a frequentist confidence interval but has a different meaning and interpretation. There are also highest density intervals in Bayesian stats, and you can also report the mean, median, etc.
Answer: I will outline my comment as an answer.
First, some clarification. In Bayesian statistics, there is no notion of "standard error" in the context of trying to conduct inference on a statistic. The standard error of an estimator is the standard deviation of the estimator's sampling distribution. A sampling distribution relies on the notion of repeated random sampling - a frequentist interpretation of probability.
Rather, what you want is the posterior distribution of the differences in parameters - specifically the posterior distribution of $W := \text{P(success A)} - \text{P(success B)}$.
Once you have the distribution of W, you can describe its qualities in whatever capacity you wish (credible intervals, i.e. quantiles, highest density intervals, etc.) and you can get point estimates by reporting the mean, median, etc.
In theory, you can derive W by thinking about the distribution of W = X - Y, where X and Y are independent Beta random variables. This might give you some distribution in closed form, if you can work out the math.
A much easier way to do this is described in the comments - use Monte Carlo simulation. If you randomly sample an arbitrarily large number of realizations from each posterior/beta distribution (say 10000 each), and simply take the difference between these two arrays, you will have obtained 10000 realizations of W! From here, you can get a Monte Carlo estimate of whatever quantity you wish to conduct inference on W - mean, median, ... using empirical estimators.
In the comments, you stated concerns regarding the "standard error decreasing for a large nunber of random realizations". This is Monte Carlo error - the error that you obtain by approximating some statistic of W with samples from W (as opposed to using math to work out the distribution and/or quantities of W directly). This is error that is unrelated to what is implied by your data or prior beliefs, but rather the "cost" of using simulation. Luckily, as you already noticed, the error goes to 0 for a large number of random samples, so as long as you simulate a large number of realizations, this error will be negligible.
To see this: take the mean of W, derived via. simulation, and compare it to the mean difference that you have already calculated in your code. What you should find is that your Monte Carlo estimate for the mean of W approaches the estimate that you explicitly calculated in closed form for a progressively larger number of samples.
Comment: +1 for the clear answer and explanations. Indeed, I have observed that with increasing number of random variables drawn from each distribution $X$ and $Y$, the empirically calculated parameters of the distribution of $W=X-Y$ are the same as the ones calculated explicitly in closed form using scipy's methods. Thanks again!


An argument on page 62 of Griffith's book,  "Introduction to Algebraic Curves"

Question: I am a bit confused about some of the things that Griffiths says on page 62 of his book, Introduction to Algebraic Curves.  I am not sure how I can reproduce the text here. I can see that GoogleBooks does have those pages on display.

Firstly I felt that the points $(x,y_\nu(x))$ are points on the algebraic curve $f$ which can have a non-trivial topology but from the way the line $\Lambda$ or the set $\Omega$ is talked about it seems that one is working on $\mathbb{C}\times \mathbb{C}$. What is the right picture? Are these local analytic elements on the generically non-trivial Riemann surface or are they on just $\mathbb{C}\times \mathbb{C}$?

Now these function elements $y_\nu(x)$ were obtained by using the implicit function theorem locally around each of the roots of an algebraic curve $f(x,y)=0$ This could be done only on the complement of the non-singular points. Now one removes a semi-infinite line from the plane which passes through the finite number of singular points. Then what is left is still simply connected.

Now to extend these local analytic elements to the complement of the line that has been removed, does one necessarily need to use the Riemannn monodromy theorem or isn't it possible to simply argue that from the property of analytic continuation? (..that if two analytic functions agree on a "large" enough open set then they are the same..)
The explicit need for a path and continuation along it comes only when one introduces the equivalence relation whereby one calls two of the $y_\nu$s to be equivalent if there exists a path in the full space (without deleting any of the points unlike at first) along which analytic continuation will convert one into the other...this again doesn't seem to need the monodromy theorem...Am I missing something?
What exactly is this "heredity property" that is being invoked to say that if $f$, a second degree homogeneous polynomial in two complex variables evaluated on the point $(x,y_\nu(x)$ went to zero then it should evaluate to $0$ on any extension of the function $y_\nu(x)$.
I guess that given any set of $n$ locally holomorphic functions $y_i(x)$ one can remove a semi-infinite line in the plane and repeat the above argument with some specific choice of path that intersects the line.

Hence any line segment and a path intersecting it induces a permutation of the $y_i$s?

Lastly I want to know if that entire argument can be made on $\mathbb{C}$ or is this entire thing something typical over $\mathbb{C}\times \mathbb{C}$ ? May be by replacing the holomorphic functions by power-series expandable real functions...they too will satisfy the analytic continuation property like the holomorphics..I am not clear about what happens to the "heredity" property.
Or more generally is there an extension of this argument/proof/technique for $\mathbb{C}^n$ or $\mathbb{R}^n$ (..looking at the zero-sets of homogeneous polynomials on appropriate number of variables..)...possibly by restricting the class of functions appropriately.

I would like to know if or what is the essential crux or main idea behind this technique of proof.
Answer: The general case

Let $X$ be a compact Riemann surface and $f\in \mathcal{M}_X[t]$, say $$f(x,t)=t^d+t^{d-1}f_{d-1}(x)+\cdots+f_0(x)$$
If $x_0$ avoids a finite bad set $\Delta\subseteq X$, $f(x_0,-)$ will have $n$ zeroes; $y_1,...,y_n$. The implicit function theorem says that there are then functions
$$Y_i:U_i\longrightarrow \mathbb{C}$$
on open sets $U_i$ containing $x_0$ with $Y_i(x_0)=y_i$. Then for all $x$ in  $U=\bigcap U_i$,
$$Y_1(x), \ . \ . \ . \ , Y_n(x)$$
are the zeroes of $f(x,-)$.
This shows that for small enough open set $U\subseteq X\setminus \Delta$ ,
$$\mathcal{S}(U)=\{\text{holomorphic solutions }s:U\to \mathbb{C}\text{ to }0=f(-,s(-)):U\to \mathbb{C}\}$$
has size $n$. This can only decrease for larger $U$.
If $U,V$ two open sets on which there are $n$ solutions, and $U\cap V$ is connected, then $\mathcal{S}(U\cup V)$ has size $n$ too. If $u_1,...,u_n$ and $v_1,...,v_n$ are solutions on $U$ and $V$, then by connectedness, for each $u_i$ there is a $v_{\tau(i)}$ equal to it on $U\cap  V$. The identity principle (uniqueness of analytic continuation) guarantees that this is a bijection.

What it means here
In our case, $X=\mathbb{CP}^1$ and the $f_i$ are polynomials in $x$. If $\Omega\subseteq \mathbb{CP}^1\setminus \Delta$ is simply connected and open, then one can write
$$\Omega=B_1\cup B_1\cup \cdots$$
as the union of balls, with $B_k\cap (B_{k-1}\cup \cdots \cup B_1)$ connected, and each $\mathcal{S}(B_k)$ having size $n$.
TL;DR
We have proven that for each polynomial $f\in \mathbb{C}[x,y]$ and open simply connected set $\Omega \subseteq \mathbb{C}$ avoiding the critical values of $x$, there are $n$ functions ($n$ is the $x$-degree of $f$)
$$s_1,...,s_n:\Omega\longrightarrow \mathbb{C}$$
with $f(-,s_i(-))=0$ as functions $\Omega \to \mathbb{C}$. The proof only uses the implicit function theorem and the uniqueness of analytic continuation.
$$\text{}$$
$$\text{}$$
Hereditary property
I think the ''hereditary property" means that if
$$s:U\longrightarrow \mathbb{C}$$
is a solution to $f(-,s(-))=0$ on open set $U$, and $\widetilde{s}:\widetilde{U}\to \mathbb{C}$ is a holomorphic extension of $s$ to a bigger open set $\widetilde{U}\supseteq U$ then
$$f(-,\widetilde{s}(-))=0$$
on $\widetilde{U}$. This is easy: the holomorphic function
$$f(-,\widetilde{s}(-)):\widetilde{U}\longrightarrow \mathbb{C}$$
which is zero on $U$, hence on $\widetilde{U}$, by the identity principle (uniqueness of analytic continuation). In particular, I would not expect this sort of thing to work in $\mathbb{R}^n$, since there are counterexamples to the identity principle.
$$\text{}$$
$$\text{}$$
Why thinking about $\mathcal{S}$ is useful
By picturing it, the sheaf of solutions $\mathcal{S}(U)$ should give a degree $n$ cover
$$Y'\longrightarrow X\setminus\Delta$$
since on small opens it is the $n$-point set. To do this formally, topologise
$$Y'=\bigcup_{x\in X\setminus \Delta} \mathcal{S}_x$$
by declaring basic opens to be $(U,s_i)$ for solutions $s_i$ on small open sets $U$.
Lifting the Riemann surface structure to make $Y'\to X\setminus \Delta$ an unbranched cover of Riemann surfaces. We can glue over $\Delta$ to get a degree $n$ branched cover
$$Y\longrightarrow X$$
Call $Y$ the ''the Riemann surface associated to $f$''; this gives one direction of the equivalence
$$\{\text{degree }n\text{ extensions of }\mathcal{M}_X\}\longleftrightarrow \{\text{degree }n \text{ branched covers of }X\} $$
which sends
$$\text{splitting field of }f(t)\in \mathcal{M}_X[t] \longrightarrow Y$$


Using standard deviation to calculate Control Limits for Individual Control Chart

Question: To compute the control limits using the 3 sigma rule, the standard deviation is usually approximated by the formula:
$\sigma=\frac{\overline{MR}}{1.128}$,
where
$\overline{MR}$ is the average of all the moving ranges of two observations, given by pattern:
$\overline{MR}=\frac{\sum_{i=2}^{N}|x_{i}-x_{i-1}|}{N-1}$
$N$ is the number of observations (batches).
Why do we calculate $\sigma$ such, not using the pattern:
$\sigma=\sqrt{\frac{1}{N-1}\sum_{i=1}^{N}(x_{i}-\bar{x})^{2}}$?
Answer: The NIST Chapter on "Process or Product Monitoring and Control" is a useful reference on this topic. As explained there, it often is preferable to use estimates of $\sigma$ based on the standard formula that you present. The moving-range approach is perhaps better limited to evaluation of individual measurements rather than batches; from Section 188.8.131.52:

Control charts for individual measurements, e.g., the sample size = 1, use the moving range of two successive observations to measure the process variability.

With only 2 measurements, an estimate of $\sigma$ based on the range is as efficient as the usual standard deviation formula.
Even then, NIST implies that this approach is best used in early "Phase 1" evaluation of quality control when "we use historical data to compute the initial control limits." From the end of Section 18.104.22.168:

Another way to construct the individuals chart is by using the standard deviation...It is preferable to have the limits computed this way for the start of Phase 2.

If moving ranges are used, you have to be particularly careful to monitor trends, as you can have a small moving range while a process is systematically moving out of control.
There is a bias in the estimate of $\sigma$ that depends on sample size, so a correction factor explained in Section 6.3.2 might be applied to the usual standard deviation formula that you present.
As someone who remembers the days of manual calculators, I suspect that use of moving ranges has something to do with that old technology. Updating mean values as new data came in wasn't so hard, but updating variances required extra steps.
Comment: Thank You very much!


Views - how to replace the pager with a slider

Question: I have a view of events, and want to display 10 events at a time.
Instead of the clicking the pager, I want the view to cycle to the next 10 events automatically after a set number of seconds - the view will be displayed on a monitor without user interaction.
The views_slideshow module only allows me to do this with every single item in the view.
How would I best approach this - ideally with an existing module.
Please let me know if the question is not clear.
Any help appreciated!
Comment: This answer is similar - maybe some of the principles could be used: http://drupal.stackexchange.com/questions/76010/multiple-nodes-in-one-slide-using-views-slideshow-or-another-module?rq=1
Answer: Views Slideshow sounds like the ticket https://www.drupal.org/project/views_slideshow.
FlexSlider might do the same, but also responsively.


How to enable install from url in Drupal Commons?

Question: I cannot find any option to install the modules from a url.
Currently, I am installing them through cpanel by manually uploading, unzipping etc.
Can anyone suggest a solution?
Comment: Make sure you have the Update module enabled...
Answer: Also you can try Drush

Drush or drupal shell is a command-line utility to help the site
  building and maintenance workflows.

The following will download and enable the module:
drush en module_name -y

Example Commands
drush dl cck zen

Download current recommended versions of CCK module and Zen theme.
drush en content

Enable the content (cck) module.
 drush vset theme_default theme_name

make theme_name theme default theme


GlassFish não pega context root da aplicação

Question: EDIT
Galera eu consegui resolver, estava faltando apontar minha aplicação para meu virtual server, obrigado.
Subi uma aplicação no servidor hoje e o glassFish não está pegando o contexto da aplicação sozinho por exemplo para acessar estou tendo que colocar : www.blabla.com/Atendimento.
<glassfish-web-app>
<context-root>/Atendimento</context-root>

<parameter-encoding default-charset="UTF-8" />

<property name="alternatedocroot_1" value="from=/backgrounds/* dir=e:\HRatendimento\imagens\" />
<property name="alternatedocroot_2" value="from=/logos/* dir=e:\HRatendimento\imagens\" />
<property name="alternatedocroot_3" value="from=/gerais/* dir=e:\HRatendimento\imagens\" />
<property name="alternatedocroot_4" value="from=/anexos/* dir=e:\HRatendimento\imagens\" />
<property name="alternatedocroot_5" value="from=/usuarios/* dir=e:\HRatendimento\imagens\" />
<property name="alternatedocroot_6" value="from=/licenca/* dir=e:\HRatendimento\" />
<property name="alternatedocroot_7" value="from=/manuais/* dir=e:\HRatendimento\" />

E no glassFish eu deixei o contextRoot como /Atendimento.

Alguém tem alguma ideia do que possa ser?
Comment: Tente editar o context root no console (porta 4848). Se não funcionar tire um screen das configurações no console e mostre do seu `glassfish-web.xml` (todo o conteúdo, bem como a pasta em que ele está localizado). Se o objetivo for jogar na raiz do site, basta setar o context-root para `/ `.
Comment: @AnthonyAccioly novamente me ajudando, então essa aplicação funcionava tranquilo, eu fiz esse deploy hoje e aconteceu isso, poém eu não fiz alteração nessas configurações
Comment: Entendi. Só para poder te ajudar melhor. O objetivo é eliminar o `/Atendimento` e publicar na raiz? Ou é para ficar onde está só que está acontecendo algum problema?
Comment: Sim publicar na raiz
Answer: No GlassFish o sinônimo para raiz é /.
Você pode setar esse contexto de várias maneiras:

Por arquivos de configuração como o glassfish-web.xml:
<glassfish-web-app>
    <context-root>/</context-root>
</glassfish-web-app>

Pelo console administrativo como demonstrado na sua pergunta.
Pelo asadmin na hora de publicar sua aplicação:
 asadmin deploy --contextroot "/" Atendimento.war

Do seu IDE (geralmente existe alguma opção para trocar o context-root nas configurações de deploy).
Comment: Aí não sei dizer Wellington, talvez você tenha fixado caminho de recursos na aplicação. O interessante é sempre deixá-los relativos e considerar o contextPath: e.g., `${pageContext.request.contextPath}/img/logo.png`.
Comment: Troquei /Atendimento por apenas "/" e funcionou, porém ele está perdendo todas as imagens :(
Comment: '' esta assim, mas sua resposta está correta, novamente muito obrigado, vou tentar descobrir o porque está perdendo o caminho.
Comment: Eu não quis dizer os docroots (mas verificar se essas pastas contém o arquivo pode ajudar). Acredito que dentro do próprio markup o caminho para suas iagens estejam errados. E.g., `/Atendimento/backgrounds/meufundodetela.jpg`. Mas de qualquer forma é chute; se não conseguir resolver abre uma pergunta com as informações relevantes (estruturas de pasta, caminhos dentro do html gerado, configurações, etc) que tenho certeza que o pessoal descobre ;).
Comment: Galera só para conhecimento de todos eu consegui arrumar, estava faltando apontar para meu virtual server do serviço.


How to wait for reload in Playwright?

Question: We are using the Playwright dotnet and we have been using WaitForNavigationAsync to wait for a page to reload.
However this is now deprecated and we are advised to use WaitForURLAsync instead. As far as I can tell this will return immediately if I'm already on the URL that I'm waiting for which will be the case when expecting a reload. I have also looked at WaitForLoadStateAsync but that also appears to return immediately.
So given the new changes to the API what is the correct way to wait for a page to reload? We don't want to use ReloadAsync as the test is clicking buttons triggering navigation to the same URL.
Comment: Will something have changed in the newly reloaded page due to that button getting clicked? Wait for that instead. You shouldn't care whether the page reloads or not, only whether the state of the page has change due to your manipulations.
Comment: It is very annoying that the Playwright team have deprecated this method which a good number of us use safely and correctly.  I am in the same situation but as they [stated](https://github.com/microsoft/playwright/issues/20853#issuecomment-1433572982) it is unlikely for the method to be removed (at least not before a v2 Playwright comes out), that I am sticking with it.

I might try to rally some people to try and get it undeprecated.  Failing that, I will just wait until it is fully removed as a method and then re-implement myself in a folked version.
Comment: Yes I suppose so! But the data could be retrieved from a slow API request and I don't know how long the page takes to reload. So I'm just wondering if there is a potential risk that the reload is slow and the data takes a long time to load the it will exceed the timeout. I would feel more comfortable knowing that the page has been reloaded and can continue with my next assertion.
Answer:
How to wait for reload in Playwright?

Don't. Instead wait for an object to reach desired changed state after re-load and verify it using web assertions.
await expect(page.getByText('Welcome')).toBeVisible({timeout:5000});

Comment: Yes I get that but that desired state has to be reached within a certain timeout. Say I have a website that is served slowly (size, slow server etc.) and I wan't to make sure that once the content is served by the server, some specific thing happens within 5 seconds (maybe an AJAX call or something along those lines) - if I don't know when the browser has reloaded then I don't know when to wait - if the initial load is low I can easily hit the timeout. That's why I would like to know when the browser has reloaded and I'm ready to wait for the desired changed state.
Comment: Again , you don't need to know that. You can verify in sum total (reload+ element displayed ) that by an reasonable time page reaches to a certain expected  state like for example "Welcome"displayed otherwise timeout failure.

How to wait for reload in Playwright?


Are there social media guidelines for athletes in the Olympics?

Question: At the 2012 Olympics in London, two athletes were expelled for offensive tweets on Twitter(1).
Are there social media guidelines for athletes in the Olympics? If so, are these enforced by the IOC, international sport federations, or national teams?
Answer: There are guidelines for social media which is enforced by the IOC. Basically they are encouraged to use social media to post or tweet photos etc as long as;

any such postings, blogs or tweets must be in a first-person,
  diary-type format

Also they can't use their social media to promote sponsorships or advertisements.
This next quote is probably the most important and interesting part of it as it seems to be the downfall of most footballers when they tweet!

Postings, blogs and tweets should at all times conform to the Olympic
  spirit and fundamental principles of Olympism as contained in the
  Olympic Charter, be dignified and in good taste, and should not be
  discriminatory, offensive, hateful, defamatory or otherwise illegal
  and shall not contain vulgar or obscene words or images.
Comment: I'm sure this doesn't apply to only footballers, but I know where you're coming from. Thanks for the answer.
Comment: They do tend to be some of the worst culprits on twitter.


Check that a given user has a given privilege

Question: Given a pair of a user and a privilege I need to determine if a user has the privilege on the server. The following is true in my setup:

The server is a part of a domain but not a domain controller
There are several domains with trust relationship in the infrastructure
Sometimes users (local, domain, or from a different domain) can belong to a local group by a merit of them being in some other group (domain or local) that belongs to a local group, as opposed to belonging to the group directly.

Example scenario for the last point:

User1 belongs to group TeamA in the DomainA
DomaimA\TeamA is a member of DomainB\SpecialAccess
DomainB\SpecialAccess is a member of DomainB\DomainAdmins
Finally DomainB\DomainAdmins belong to local Administators group
Local Administators group has SeRemoteInteractiveLogonRight privelege

Now If I have on the input DomainA\User1 and SeRemoteInteractiveLogonRight I need to arrive to Yes or No answer. So I open the Local Policy on the machine, note what groups are listed against the right I'm interested too then go to the server managers and see what at the group members and then I need to see what members of any groups in these groups and so on.
I have a gut feeling that it can be easier. I was really excited when I found AccessChk utility It lasted whole three minutes that took me to discover that it only lists direct relationship, so user within a group won't be listed.
Now I'm guessing that it would be possible to combine results from AccessChk some how so that I can check if a user belongs to any of the groups that AccessChk return, but given that it's not a single domain but several of them I'm not sure how to approach this. Also AccessChk output does not seem to distinguish between a group and a user.
EDIT: In the spirit of not falling into XY problem trap, what I really need to do is to make sure that on a group of servers no specific user accounts that are used as IIS application pool identities have SeInteractiveLogonRight or SeRemoteInteractiveLogonRight privileges. I have no problem with the IIS part, but the last step of checking an account against a privilege is something that I'm struggling finding a straightforward way to check. I also would like to automate the check because this is something that will need to be done regularly.
Comment: This sounds like a job for... Resultant Set of Policy (RSoP)!
http://technet.microsoft.com/en-us/library/cc758010%28v=WS.10%29.aspx
Comment: @zespri - My answer was garbage and I deleted it. The SeInteractiveLogonRight and SeRemoteInteractiveLogonRight user rights are handled differently than "normal" privileges and it looks like reporting on them is going to be problematic. If I come up with a solution for you I'll post another answer but, for now I've got nothing.
Comment: @Davidw - RSoP is problematic in that the Local Security Policy defaults won't be reflected in the output. So, any "Not Configured" entries will just show up as "Not Configured" and you won't actually see what principals are granted the right by Local Security Policy. Finally, even if you do get a list of principals from Group Policy you'll be stuck expanding group memberships (potentially cross-domain, too) to replicate OS functionality. This has actually turned out the a much more challenging question than I expected it to be.
Comment: @EvanAnderson Exactly! When I was asked to estimate how long it was going to take me, it seemed to be a straightforward task. And after a couple of days of googling and trying different things... nothing. Currently my plan is to pinvoke [GetTokenInformation](http://msdn.microsoft.com/en-us/library/windows/desktop/aa446671%28v=vs.85%29.aspx) with TokenPrivileges [token information class](http://msdn.microsoft.com/en-us/library/windows/desktop/aa379626%28v=vs.85%29.aspx)  Of course I need to figure out first how to get hold of the token itself. This route seems the most promising at the moment.
Comment: @zespri - NtOpenProcessToken() is probably the best way to get at the token. (Have a look at http://www.leeholmes.com/blog/2006/07/21/get-the-owner-of-a-process-in-powershell-%E2%80%93-pinvoke-and-refout-parameters/)
Comment: Are you using entirely 'real' user accounts, or are there some managed service accounts in there too?  IIS will accept either in Win2008R2+, but you might have harder time getting the token of an MSA.
Comment: One option to get the token might be to scan for processes owned by that user, then call `OpenProcessToken`...
Comment: Related: http://www.tomshardware.com/forum/224643-46-detect-user-logon-rights-win2k
Comment: Related: http://www.informit.com/articles/article.aspx?p=474649&seqNum=6
Comment: @EvanAnderson, just FYI I think I cracked this (see below). Also: [my related SO question](http://stackoverflow.com/a/37858949/284111)
Comment: This should be easy with Powershell, expect Powershell is bad dealing with local groups. But if you can manage to get the members of the local group, a loop in Powershell expanding the AD groups until you get just users, and compare with your given user should be the way to go...
Comment: @zespri - It took me a few minutes to get the context back (since it has been two years since we last talked about this), but that looks legit to me! (I remember being frustrated at having *just* learned, by answering your question and subsequently deleting my answer, that user rights and privileges are handled differently in NT. That was a real "today I learned" moment...)
Answer: Access tokens do not have information about rights, only about privileges.
What you need to do is this:

Find the IIS worker process that corresponds to your app pool. Since you know the app pool identity that should be easy by enumerating all the processes with the worker process name, and filtering the one that has the identity. If there are more than one, you can use any.
Use GetTokenInformation with TokenGroup information class, not the TokenPrivilege on the process token. The result will give you all the transitive groups the identity belongs too. This means even indirect ones.
Now you can loop through these groups and call LsaEnumerateAccountRights on each one and collate the information. This will give you what you want.

The above relies on the existence of the process (and token) corresponding to the account identity. In your scenario this should not be a problem. In scenarios when this is a problem, you can try and use Active Directory lookup for Token-Groups computed attribute. This article lists a few approaches how to pull this off.


Redirect to anchor after form validation

Question: I am trying to redirect users to the anchor of the error form field after form validation.
In the form I set the form validation handler with the following code.
$form['#validate'] = 'my_form_validate';

In the validation handler, if the form shows some error message, I am trying to scroll to error field.
function my_form_validate() {
    ...
    $form_state['redirect'] = 'node/' . $form['nid']['#value'] . '#' . $error_field_anchor;
    ...
}

The form is not redirecting after validation.
I have tried other paths, such as user/1, node/123 without anchor but the form is not getting redirected to that one.
Comment: Try  `drupal_goto($path);`
Comment: I try function drupal_goto(), and it's work and redirect, but form_validation message not displaying.
This is one difference between form_state['redirect'] and drupal_goto()
http://drupal.findincity.net/ppst/63547274810018958054256/what-is-the-purpose-and-differences-between-drupalgotodrupalredirectform-and-formstateredirect
this article is answered why drupal_goto() not correct for this case.
Comment: `$form['#validate'] = 'my_form_validate'` replaces any existing validation handler, which may explain why the redirect isn't happening: No validation error is set. This is probably a task to do with JavaScript as what you want to achieve is scrolling the page. Unfortunately, we cannot say why the redirection doesn't take place, since we don't know the code that checks when users should be redirected (which could be wrong code) nor in which hook is the form validation handler added (which could target the wrong form or not form at all).
Answer: Use this and put in you form
$form_state['redirect'] = 'url';

Comment: Nothing changed. After submit wrong form and validation, error message apear and form not redirected.
Answer: What you're looking for is drupal_redirect_form($form_state). In the validation function, set the redirect element in $form_state to the parameters used by drupal_goto().
function my_form_validate() {
  // @TODO: Add validation function check
  $form_state['redirect'] = array('node/' . $form['nid']['#value'], array('fragment' => $error_field_anchor));
  drupal_redirect_form($form_state);
}

Comment: calling drupal_redirect_form will abort any further form validation. If you are 100% positive that this validate function is the only one that needs to be called, then this is fine. However, if your form may be altered or needs further validation, this approach will break it.
Comment: also, FWIW, doesn't work on Drupal 7


no matching function for call to 'boost::property_tree::ptree_bad_data::ptree_bad_data()

Question: I have my custom exception class derived from boost::property_tree::ptree_bad_data as follows:
class MyCustomException : public boost::property_tree::ptree_bad_data
{
    public:
      explicit MyCustomException(const std::string& msg): mMsg(msg) {}
      virtual ~MyCustomException() throw() {}
      virtual const char* what() const throw() { return mMsg.c_str(); }

    private:
      std::string mMsg;
};

During compilation I get errors as:
error: no matching function for call to 'boost::property_tree::ptree_bad_data::ptree_bad_data()'
       explicit MyCustomException(const std::string& msg): mMsg(msg) {}
                                                                    ^
note:   candidate expects 2 arguments, 0 provided
       explicit MyCustomException(const std::string& msg): mMsg(msg) {}
                                                                   ^

Any idea what could be the reason?
Comment: ptree_bad_data has not default ctor, hence the error. Initialize your base
Comment: The code and the error message you show doesn't match. When posting questions about build-errors, use the errors from the [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) that you show us.
Comment: @Someprogrammerdude I have edited the error.
Answer: According to the documentation the class ptree_bad_data doesn't have parameterless constructor. It has actually single constructor:
template<typename T> ptree_bad_data(const std::string &, const T &);

So you have to provide these two arguments in your constructor:
explicit MyCustomException(const std::string& msg)
    : boost::property_tree::ptree_bad_data(msg, nullptr /* correct data here */)

There is also no need for your exception class to store exception message separately. Standard exception classes will do that for you.
Btw, are you sure you want to derive your exception from ptree_bad_data?
Comment: @astre then derive from std::exception if you don't have specific reason to derive from `ptree_bad_data` (which you probably don't have if you don't use all its constructor parameters).
Comment: Thanks. It worked. The reason was to use more specific exception instead of std::exception. Any particular reason this might be not good idea ?

no matching function for call to ‘boost::property_tree::ptree_bad_data::ptree_bad_data()


Delete ' signs out of multiple cells in matlab

Question: I have got a 2x5 cell-array containing char strings. E.g. it looks like this:
{'''ABC''' , '''DEF''' , '''GHI'''   , '''-'''   , '''MNO'''; ...
'''PQR''' , '''STU''' , '''Value''' , '''XYZ''' , '''-'''}

So for example, if I give out one cell, the output is following: ''ABC''. Now I want the output to be 'ABC'. How can i delete all ' of the cells?
Comment: Please edit this question to make that an actual Matlab cell array i.e. drop all the `|`s and use the `{}` syntax so we know exactly how your data are stored
Comment: Ok sorry, but done :)
Answer: So basically you just want to loop through each element of the cell array and drop the first and the last character:
A = {'''ABC''' , '''DEF''' , '''GHI'''   , '''-'''   , '''MNO''';'''PQR''' , '''STU''' , '''Value''' , '''XYZ''' , '''-'''}

cellfun(@(x)x(2:end-1),A,'uni',0)

Comment: Thank you! How bad, I didn't realise this way to solve my problem. Just being a blockhead today.


flatten / group generated files in android studio flutter project

Question: Coming from PHPStorm the IDE by default folds / collapses similar files to one level.
So for example when I have a file.ts and file.js in the same folder, file.js will be hidden in a dropdown below file.ts because PHPStorm knows its generated and assumes the files are related.
Is there a similiar feature in Android Studio when using Flutter?
I want to group / collapse my .freezed.dart and .g.dart files so they are hidden from the project view but not ignored.
Answer: File nesting rules | IntelliJ IDEA Documentation
This works for all IntelliJ-based IDEs.

In the Project tool window (Alt+1), open options.

new UI:
old UI:

Select File Nesting. A dialog opens in which you can configure file nesting rules.

Add new rules:

.freezed.dart; .g.dart;


Feature selection vs Feature subset selection

Question: I am trying to verify if these two terms "Feature selection" and "Feature subset selection" relate to the same term. After viewing a number of articles it seems that both are used interchangeably, while I was initially assuming that the latter relates to ensemble feature selection where not a single feature subset but a number of feature subsets is calculated.
Can you confirm that these two are just different names for the same task or is there some significant difference similar to my initial assumptions?
Comment: what is the context?
Answer: I like "An Introduction to Statistical Learning with Applications in R" by G.James et al., so I took a look at this book.
According to the book, it seems like feature selection is more wide term that includes methods of subset selection. P. 218:
"In this chapter, we see some approaches for automatically performing feature selection or variable selection — that is, for excluding irrelevant variables from a multiple regression model.
<...>
• Subset Selection. This approach involves identifying a subset of the p
predictors that we believe to be related to the response. We then fit
a model using least squares on the reduced set of variables.
• Shrinkage. This approach involves fitting a model involving all p predictors.However, the estimated coefficients are shrunken towards zero
relative to the least squares estimates. This shrinkage (also known as
regularization) has the effect of reducing variance. Depending on what
type of shrinkage is performed, some of the coefficients may be estimated
to be exactly zero. Hence, shrinkage methods can also perform
variable selection".
So it seems that for feature selection we may use subset selection (i.e. best subset selection, backward or forward selection) or shrinkage methods such as lasso regression.
Hope this helps.


How to play bends with vibrato on electric guitar?

Question: I can bend strings easily and apply vibrato without much trouble, but when it comes to combining those two techniques I am totally lost. When I try to make vibrato on a bent string I loose control of pitch and sense of rhythm goes out of the window. Moreover, "rate" of vibrato that I can achieve is much lower while bending than "plain" vibrato.
How can I practice vibrato with bends?
Comment: @ToddWilcox  that's what I would say too.  Why don't you make it an answer before someone else does?  Just because it fits on one typewritten page does not mean it has to be relegated to a comment ;-)
Comment: Isolated practice is the only way I know. Bend a string up one fret, apply slow vibrato. Relax. Bend up two frets, apply slow vibrato, relax. Repeat every day until the vibrato becomes easier and you can increase and control the vibrato speed. Most of the time there are no shortcuts.
Comment: @RockinCowboy LOL! Ok, done.
Comment: My problem is that when I play "normal" vibrato, it comes from shaking motion of my wrist. But when I bend, wrist is too tightened so I can't make that motion, so I have to somehow utilize only fingers.
Answer: Isolated practice is the only way I know.
Bend a string up one fret, apply slow vibrato. Relax.
Bend up two frets, apply slow vibrato, relax.
Repeat every day until the vibrato becomes easier and you can increase and control the vibrato speed. Most of the time there are no shortcuts.
Answer: The vibrato in this case is usually to bend a note up, say, one fret, then let it relax and re-tension it a few times. You don't always have to let it back to the ordinary fretted note, it could be relaxed half a fret down, but then it only needs to be bent back to the target note. Again, with a two fret bend that is given vibrato, it may need to go to a straight string again, but it may only need to be relaxed by half a semitone, or one semitone.Try to use a couple of fingers, it's hard work controlling a big bend with only one. It depends what style, genre or who you're trying to emulate. You need to do it slowly to check pitch, particularly the target note. Don't overshoot. Ears are good for this. Yours or your listeners.A tuner will also help, when practising slow vib. As often, no substitute for doing it lots, a.k.a. practice.
Comment: I agree.   Playing a two step bend then releasing the bend down one step and raising it again is a good way to keep a consistent pitch in your vibrato.  You can also go the other way, bending up one step from the target note and releasing again.

This method allows you to check your target pitches by playing both notes before performing the bend.


How to view .py in Eclipse

Question: I just installed eclipse on my machine and want to modify a .py file. I tried opening the file and I get the error application not found. What do I need to install and how do I install it. I have searched the web and not found any clear instruction. I am using Java Eclipse SDK.
I am trying to open the file .py with Eclipse on windows machine. The error I get is "application not found".
Comment: Is this on Mac? Windows? Linux?
Comment: This question is tough to answer. How did you try opening the file? Via Eclipse? What was the exact error message you got? What OS are you using, Windows, Mac, Linux, etc etc. The more info you can give us, the more helpful we can be.
Comment: @Alan I am using Windows and trying to open the .py file from within eclipse
Answer: Install the PyDev plug-in for Eclipse:
http://www.rose-hulman.edu/class/csse/resources/Eclipse/eclipse-python-configuration.htm

How to view .py in Eclipse


java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2)

Question: @WebMethod(operationName = "SearchOR")
  public  SearchOR getSearchOR (@WebParam(name = "comp")
  String comp, @WebParam(name = "name")
 String name) {
            //TODO write your implementation code here:
     SearchOR ack = null;

    try{
     String simpleProc = "{ call getuser_info_or(?,?)}";
        CallableStatement cs = con.prepareCall(simpleProc);
        cs.setString(1, comp);
        cs.setString(2, name);
        **ResultSet rs = cs.executeQuery();**

      while (rs.next()) {

           ve.add(rs.getString(1));
           ve.add(rs.getString(2));

        }}catch ( Exception e) {
        e.printStackTrace();
        System.out.print(e);
    }
    return ack;
}

I am getting error at portion i have made bold.It is pointing to that location.My Query is
here:
DELIMITER $$
DROP PROCEDURE IF EXISTS .`getuser_info_or$$
# MySQL returned an empty result set (i.e. zero rows).`
CREATE PROCEDURE .getuser_info_or``
(
IN comp VARCHAR(100),
IN name VARCHAR(100),
OUT Login VARCHAR(100),
OUT email VARCHAR(100)
)
BEGIN
SELECT sLogin, sEmail
INTO Login, email
FROM ad_user
WHERE company = comp OR sName=name;
END $$
# MySQL returned an empty result set (i.e. zero rows).
DELIMITER ;
Answer: I believe your problem is your call does not match the method definition. In your definition you have two parameters: IN comp, IN name, OUT Login, OUT email. So your call should be:
String simpleProc = "{ call getuser_info_or(?, ?, ?, ?)}";

And from the javadocs:

If used, the result parameter must be
  registered as an OUT parameter.

So you would need to add those registrations:
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.VARCHAR);

The stored procedure as defined does not create a resultset for the retrieved data, but rather places it in the out parameters. To fetch them you will need to access them via the callable statement:
String login = cs.getString(3);
String email = cs.getString(4);

Comment: Thanks .Thanks for ur response ... Now gwtting this error ..any idea about it..

java.sql.SQLException: ResultSet is from UPDATE. No Data.
        at

com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
        at com.mysql.jdbc.ResultSet.next(ResultSet.java:6450)
        at WS.TestDB.getSearchAnd(TestDB.java:85)
        at WS.TestDB.main(TestDB.java:98)
Comment: It is because your procedure does not create a resultset. You need to get the values from the statement. I have updated my answer.
Comment: Hi very thanks jessup will like to ask some more doubts .If possible can u share ur mail id or IM like that something so it would be more helpful to me.Have lot of doubt...:-(


ICC - unclear comment from reviewer

Question: I'm new here and not a statistician, so I apologize in advance and I sure hope someone can help!
I'm working on a study where we have 10 locations $(5 \ intervention, 5 \ control)$. We have two measurements of activity for each participant $(n=  700)$ at each location. I've received the following comment from a reviewer: "Typically an intracluster correlation coefficient (ICC) is calculated to adjust for the correlation between participants at a single location"
I know how to calculate ICC using SPSS, but because there are different numbers of participants at each location, I'm a little confused... can anyone help?
Thanks so much in advance!
Comment: "I'm a little confused, can anyone help" is not a very specific question. Are you asking whether the usual computations for intraclass correlation are still valid in the case of unequal cluster sizes?
Comment: CV aims to be a repository of questions that are useful to others. With that in mind, could you edit your title to reflect the statistical question, rather than the circumstances in which it arose?
Answer:
Are you analyzing the data as a clustered randomized trial? Well I guess randomization doesn't really matter in this case. But have you addressed clustering in some way? If yes, ignore (2).
You need to address clustering in some way. I'm sure there are many ways to do this. The first that comes to mind would be a mixed-effects model with a random effect for location/cluster. (This is a commonly cited reference: Methods for evaluating area-wide and organisation-based interventions in health and health care: a systematic review) But depends on your study and field of research. I've seen location modeled as a fixed effect. This can be useful. More important is what the standard practice is in your field.
Usually clustering is addressed in the modeling stage. An actual ICC could be generated, but not sure how it would be useful. This may just be a limitation of my understanding generally.  (ICCs are often used in the sample size estimation stage. But sounds like you're way beyond that now.)

ICC - unclear comment from reviewer


Spreadsheets get unique names but ignore blank cells

Question: I would like to use spreadsheets to get all unique names from Column A in a table but in the same time I would like blank cells to be ignored. So far I've got this formula that returns all of the unique names from column A but I don't know how to go about ignoring blank cells and not repeating values that have once been added previously.
Here is how my document looks so far. As you can see everything stops after Megan because there is a blank cell.
=IFERROR(INDEX($A$2:$A$90, MATCH(0, COUNTIF($I$10:I10, $A$2:$A$90), 0)), "")
Searched long and wide but came up with nothing, if anyone has any idea how one could do that I would really appreciate it. Thanks!
Answer: =unique(A2:A) should work
=unique(filter(A2:A,A2:A<>"")) to also ignore blanks
Comment: @Max Makhrov I used this method to remove a string that was my headers as well as ignore white space! I was curious if there was a name for the `<>` notation or if you could provide any further documentation.
Comment: unique is an excel beta function, what about any other formula which will with Excel 2019 or older stable version?
Comment: NOT(ISBLANK(...)) also availabe (more readable)

eg. FILTER(A2:B10, NOT(ISBLANK(A2:A10)))
Comment: Thank you for your very quick reply but using your formula returns duplicate values as you can see here http://prntscr.com/gyhxmh
Comment: It works, my bad when trying to use it. Thank you very much!!
Comment: @ConstantFun, I cannot find the documentation for `<>`. This is known from Excel: https://stackoverflow.com/questions/532435/what-does-mean
Comment: `=unique(filter(A2:A,A2:A<>""))` removes any empty/blank row. `=unique(A2:A)` does NOT. I tested four values (strings and numbers separately) where there was one duplicate value and used the `ROWS` function to display the number of rows of data returned. `=rows(unique(filter(A2:A,A2:A<>"")))` returned a value of 3 (no empty row) whereas `=rows(unique(A2:A))` returns a value of 4 (i.e. it includes the empty row).
Answer: Yet another hack
=SORT(UNIQUE(A2:A))

Technically, this does not remove the blank result. But nonetheless puts it at the end of the list. You'll also benefit from the sort if you need it.
Answer: You can use query:
=unique(query(A2:A,"select A where A<>''"))

Answer: You can use this code:
=IFERROR(INDEX($A$2:$A$90, MATCH(0, INDEX(COUNTIF($I$10:I10, $A$2:$A$90)+($A$2:$A$90=""), ), 0)), "")

should work


Let $f(x)$ be a differential real function defined on the real line. If $f(0)=0$ and $f'(x)=[f(x)]^2$, then $f(x)=0$ foi any $x$.

Question: Again, $f:\mathbb{R}\to\mathbb{R}$ is differentiable, $f(0)=0$, and $f'(x)=[f(x)]^2$ for every $x$. A friend suggested the following argument:
If exists $c$ such that $f(c)\neq0$, there exists an interval $I$ around $c$ such that $f(x)\neq0$ if $x\in I$ (because $f$ is continuous since it is differentiable). In that interval, we could define $g(x)=x+\frac{1}{f(x)}$. This function $g$ would be differentiable and $g'(x)=0$. Then $g(x)$ is constant, for example, $k$. Then, $f(x)=\frac{1}{k-x}$ for $x\in I$
But I don't know where to find an absurd. What should I do next?
I think I should use the fundamental theorem of calculus and try to find an absurd with $f(x)=\int_0^x f'(t)dt=\int_0^x [f(t)]^2 dt$, but I also didn't got anywhere.
Thanks in advance.
Comment: but this expression for $f(x)$ is valid only for $x$ in $I$, and $k$ doesn't need to be in $I$ ..
Comment: $f(x)=1/(k-x)$ is not defined at $x=k$ (a contradiction).
Answer: Suppose $f(x)$ exists on some closed interval $[0,\delta]$.  Let $F=F(\delta)$ be its maximum value on this interval.  If $x\in(0,\delta)$, then your integral equation $f=\int f^2$ yields
$$
|f(x)|\le \int_0^xf(t)^2dt\le x F^2.
$$
Hence,
$$
F(\delta)\le \delta F(\delta)^2.
$$
If $F(\delta)\neq 0$, then
$$
1/\delta\le F(\delta).
$$
This contradicts continuity of $f(x)$ at $x=0$, since we can choose $\delta$ arbitrarily small.
Answer: Your friend's argument is actually very close to a complete proof.  It proves that for any interval $I$ on which $f$ is nonzero, there exists a constant $k$ such that $f(x)=\frac{1}{k-x}$ for all $x\in I$.  So take a maximal such interval $I$; in other words, a connected component of the open set $\{x\in\mathbb{R}:f(x)\neq 0\}$.  Then $0\not\in I$, so $I=(a,b)$ is an open interval that is not all of $\mathbb{R}$.  That is, either $a$ or $b$ is finite; let us suppose $a$ is finite (the other case is similar).  Now simply observe that $f(a)=0$ (otherwise we could enlarge $I$ to contain $a$), but $f(x)=\frac{1}{k-x}$ does not approach $0$ as $x$ approaches $a$ from above, so $f$ is discontinuous at $a$.  This is a contradiction.
Answer: Let $a < b \in \mathbb{R}$. Since $f: [a,b] \longrightarrow \mathbb{R}$ is continuous, theres exist $F: [a,b] \longrightarrow \mathbb{R}$ such that $F' = f$. Let $g: [a,b] \longrightarrow \mathbb{R}$ defined by $g(x) = f(x)e^{-F(x)}$. Note that $g$ is differentiable, then
$$g'(x) = f'(x)e^{-F(x)} + f(x)e^{-F(x)}(-f(x)) = (f(x))^{2}e^{-F(x)} - (f(x))^{2}e^{-F(x)} = 0.$$
Therefore, $g$ is constant. Since $g(0) = 0$, $g(x) = 0$ for all $x \in [a,b]$, so $f(x) = 0$ for all $x \in [a,b]$. Since $a, b$ were chosen arbitrarily, the result follows.
Answer: Say $f_1$ is a solution of the differential equation. Let $J \supseteq \{0\}$ be an interval of maximal length with $f_1|_{J}=0$. By continuity, it is closed.
Assume $b=\sup J < \infty$. Then, by Picard-Lindelöf there exists an open interval containing $b$, say $\tilde J$, such that $f_1$ agrees with the 0-function on $\tilde J$, which contradicts that $J$ is maximal. That is, the assumption $b<\infty$ is wrong.
Answer: By contradiction.  First, suppose $f(x)\ne 0$ for some $x>0.$ For $x\geq 0,$ for brevity let $F(x)=\sup_{0\leq y\leq x}|f(y)|=\sup_{0\leq y\leq x}|f(y)-f(0)|.$
Let $r=\sup \{x\geq 0: F(x)=0\}=\sup \{x\geq 0:\forall y\in [0,x]\;(f(y)=0)\}.$
For $x> r:$  Since $f(t)=0$ for $t\in [0,r],$  we have $F(x)=\sup_{r\leq y\leq x}|f(y)|=\sup_{r\leq y\leq x}|f(y)-f(r)|.$ Therefore $$F(x)=   \sup_{r\leq y\leq x}|\int_r^yf(t)^2dt|\leq$$ $$\leq    \sup_{r\leq y\leq x}\int_r^y F(x)^2dt=$$ $$=   \sup_{r\leq y\leq x} (y-r)F(x)^2=$$ $$=(x-r)F(x)^2.$$ So $x>r\implies F(x)\leq (x-r)F(x)^2.$
Now by def'n of $r,$ for every $x>r$ there exists $x'\in (r,x)$ with $f(x')\ne 0,$ so if $x>r$ then $F(x)\geq |f(x')|>0.$
So for $X>r$ we have  $0<F(x)\leq (x-r)F(x)^2,$ implying $\frac {1}{x-r}\leq F(x).$
So $\lim_{x\to r^+}F(x)=\infty.$ This is impossible  because $\sup \{F(x): r< x\leq r+1\}\leq F(r+1)<\infty. $
Second, the case where $f(x)\ne 0$ for some $x<0$ is handled similarly.
Answer: Consider the differential equation (y=f(x)) $y'=y^2$.  The solution is $y=\frac{1}{c-x}$ where c is an arbitrary constant.  If f(0)=0, then c must be infinite, so that f(x) is identically 0.


How to find by Selenium a tag that's produced by javascript (I guess)

Question: Heyo!
I have to download a file from corporate site by using Selenium, and got stucked on the last step:
When I press Ctrl+U on the site the code contains only base tags like   and some s those are empty:

but when i select and inspect an element by Chrome dev tool
it says that there are many tags in
, how to find an "invisible" <select> tag by Selenium?
The code below returns with NoSuchElementException
WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.ID, 'pucContent'))).find_element_by_tag_name('select')

My guess that javascript creates new tags and all content within
 tag
Comment: If Selenium doesn't find the tag when you search for it, then it's not there. With the caveats that 1. what you _search for_ is not there, hence you could be searching for something wrong 2. it's not there _when you're searching_ hence you could be searching for the correct thing before it's been added or after it's been removed.
Comment: Paste the HTML that is displayed after the page is loaded and using Inspect with the dev toolbar. It will give you a better idea of what the page looks like when you need to interact with it.
Answer: My guess is that

 is there at the beginning and gets populated after the page is loaded. So what you really need to be waiting for in your wait is something inside that. If there is a <select> inside that elemeint when you inspect, try waiting like this:
WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#pucContent select'))).find_element_by_tag_name('select')

Keep in mind the "page_source" of a web page is only what is passed when the document is requested, it won't contain anything loaded dynamically after the original document is loaded.


A pigeonhole riddle

Question:
John offers Dean the following challenge:
Dean would choose 8 natural numbers so that $10\leq n \leq 36$.
If John manages to create two equal sums using only numbers that Dean chose, at most once each, he wins.
Assuming John has adequate time to check all options, will he always win? and why?

My thoughts were counting the number of options that Dean has for choosing 8 numbers, which is $27 \choose 8$, and also counting the number of options John has of creating sums, which is $\binom{27}{8}\cdot\sum^8_{i=2} \binom{8}{i}$. But that doesn't bring me anywhere.
I feel like it's true that John would always win, and I know I need to use the pigeonhole principle somehow, which means showing that for sure there are more possible ways to arrange sums than the number of sums possible. So, there are at least two arrangements for the same sum. (By arrangement for the same sum I mean two different combinations of numbers that summed give the same answer).
But I'm kind of stuck there.
Would appreciate assistance!
Comment: Welcome to MSE.  You'll get a lot more help if you show that you have made a real effort to solve the problem yourself, even if you haven't made much progress.  What are your thoughts?  What have you tried?  How far could you get?  Where are you stuck?  This question will likely be closed if you don't add more context.  Please respond by **editing the question body.**  Clarifications don't belong in the comments.
Comment: The number of options Dean has is not important.  Given the eight numbers, how many combinations are possible?  What are the minimum and maximum sums?
Answer: You can compute the maximum sum $S_M=36+35+34+33+32+31+30+29=260$ and the minimum sum $S_m=10+11=21$ (assuming we always have to sum at least two numbers). This means that any solution of the sum $S$ of any combination of the eight numbers will be $S_m \leq S \leq S_M$. From $S_M-S_m=239$ we get the number of different sums we can obtain from the combination of those numbers.
On the other hand, there are $\sum^8_{i=2} \binom{8}{i}$ possible sums from the 8 numbers chosen. It is enough to show that $\sum^8_{i=2} \binom{8}{i}>239$ in order to prove, by the Pigeonhole Principle, that there will always be a sum $S$ which can be computed in at least two different ways using different combinations of those 8 numbers.
Comment: I cant believe I didn't see that, thank you!
Answer: It is being asked if John can always find from any $8$-set, two non-empty, proper, disjoint subsets having same sum.
There are $2^8-2=254$ non-empty, proper subsets. Hence $254$ possible sums for any $8$-selection.
The minimum and maximum sum for any non-empty, proper subset is $10$ and $30+31+\ldots+36=231$ respectively.
Hence due to Pigeonhole principle, John always wins.
Note that either John obtains two disjoints subsets right away or two non-disjoint subsets. In the latter case, he removes the common terms to obtain disjoint ones.

A pigeonhole riddle