Row_Number() Over Order By Computer column

Question: I would like to do Paging and Sorting in SQL Query.
Here is the my query
;WITH myCTE AS
(SELECT (FirstName+''+LastName) as [User Name],
         ROW_NUMBER() OVER (ORDER BY FirstName) as RowID
         From [MyTable])

SELECT TOP 10 * FROM myCTE
    WHERE RowID > 10*(2-1)

It is working fine, but now I want to sort records by the computed column [User Name]
So I changed query like this
;WITH myCTE AS
(SELECT (FirstName+''+LastName) as [User Name],
         ROW_NUMBER() OVER (ORDER BY [User Name] ASC) as RowID
         From [MyTable])

SELECT TOP 10 * FROM myCTE
    WHERE RowID > 10*(2-1)

But it gives this error:
Msg 207, Level 16, State 1, Line 2
Invalid column name 'User Name'.

Can anyone help me how to use ROW_NUMBER() OVER computed column? or how can I achieve sorting and paging records in SQL query?
Answer: Simply refer to the actual expression in the order by, not the alias:
;WITH myCTE AS
(SELECT (FirstName+''+LastName) as [User Name],
         ROW_NUMBER() OVER (ORDER BY FirstName+''+LastName ASC) as RowID
         From [MyTable])

SELECT TOP 10 * FROM myCTE
    WHERE RowID > 10*(2-1)

Answer: Two things. First, you can't refer to other columns within the same SELECT clause, because all columns are effectively computed "in parallel", and so the newly created value isn't available. One way is to repeat the expression as Ian's answer shows, another way is to introduce another CTE:
;WITH CombinedNames AS
(
    SELECT (FirstName+''+LastName) as [User Name]
    FROM MyTable
), Numbered as
(
    SELECT [User Name],
         ROW_NUMBER() OVER (ORDER BY [User Name]) as RowID
         From CombinedNames
)
SELECT TOP 10 * FROM Numbered
    WHERE RowID > 10*(2-1)

But, and this is important, this is still actually broken. Why? Because you've not applied any ORDER BY to the final SELECT that uses TOP to select 10 rows - so you're not getting "the 10 rows that should appear on page 2", you're getting "any random 10 rows that don't appear on page 1". So we need to make another change:
;WITH CombinedNames AS
(
    SELECT (FirstName+''+LastName) as [User Name]
    FROM MyTable
), Numbered as
(
    SELECT [User Name],
         ROW_NUMBER() OVER (ORDER BY [User Name]) as RowID
         From CombinedNames
)
SELECT TOP 10 * FROM Numbered
    WHERE RowID > 10*(2-1)
ORDER BY RowID

or if you prefer:
;WITH CombinedNames AS
(
    SELECT (FirstName+''+LastName) as [User Name]
    FROM MyTable
), Numbered as
(
    SELECT [User Name],
         ROW_NUMBER() OVER (ORDER BY [User Name]) as RowID
         From CombinedNames
)
SELECT TOP 10 * FROM Numbered
    WHERE RowID > 10*(2-1) AND RowID <= 10*2

But note that this second variant doesn't guarantee the order of the results returned within the page.
Answer: DECLARE @pageNumber int,
        @page_Size int,
        @page_start int

SET @pageNumber = 1
SET @page_Size = 10
SET @page_start = ((@page_Size-1) * @pageNumber) + 1
Select TOP(@page_Size)<valiables_names>,ROW_NUMBER() [Row_ID] from <table_Name> having Row_ID >= @page_start


LDA, PCA and k-means: how are they related?

Question: I am trying to understand how linear discriminant analysis (LDA) is related to principal component analysis (PCA) and k-means clustering method. As an example, here is a comparison between PCA and k-means:

My question is how LDA is related to PCA and k-means?
Comment: Where is the snapshot taken from? By the way, it does not look much of a *comparison* between k-means and PCA to me; it shows two different formulas, yes, but how do they compare?..
Comment: See also: http://stats.stackexchange.com/questions/23353/pca-lda-cca-and-pls, http://stats.stackexchange.com/a/87509/4598
Answer: I'm by no means an expert in the topic, but it seems that K-means clustering can be viewed as a dimensionality reduction technique, of which LDA and PCA are direct examples. Clustering via K-means seems to uncover the latent structure of data, which essentially results in dimensionality reduction. I'm sure that other people will provide some more advanced answers to this question.
Additionally, I would like to share two references that are relevant to the question/topic and IMHO are rather comprehensive. One reference is a highly-cited research paper by Ding and He (2004) on the relationship between K-means and PCA techniques. Another reference is a research paper by Martinez and Kak (2001), presenting the comparison between PCA and LDA techniques.
References
Ding, C., & He, X. (2004, July). K-means clustering via principal component analysis. In Proceedings of the twenty-first International Conference on Machine Learning (p. 29). ACM.
Martínez, A. M., & Kak, A. C. (2001). PCA versus LDA. IEEE Transactions on Pattern Analysis and Machine Intelligence, 23(2), 228-233.
Comment: See stackoverflow.com/a/29731291/2056067 for an attempt to summarize Ding & He. :-)
Comment: Maybe so, the line is not very clear for programming-related statistics questions (or vice versa). You can flag the question for moderator attention. DS SE is still in beta though. :)
Comment: @A.Donda: Thank you for the link. :-) Both answers are very nice (+1) and I will re-read them, when I'll have a bit more time. However, I think that particular question belongs to either _Cross Validated_, or _Data Science_ SE site and, therefore, should be migrated.
Answer: LDA & PCA are used just in different circumstances.
Clustering & PCA are unsupervised. LDA is supervised. - here is good explanation of differencies b/w unsupervised & supervised methods.
The main aim of Clustering, as part of EDA, is grouping... or even if outliers are forming Gaussian mixture => Novelty appearance in ds (e.g. compared with another ds). Then you can calc. responces to these generalized groups. But either such grouping will lead to dimensionality reduction or not depends on data themselves. But whether such grouping will lead to dim_reduction or not - depends on case/chance (on data).
PCA (also part of EDA) really aims for dimensionality reduction if you have tooo great quantity of features, extracting Principal Components that input into variety in ds. Also used for outliers removal in pre-modelling stage (as is before modelling dependencies). N.B. Non-Gaussian distributed data causes PCA to fail.


EditText máscara veículo

Question: Gostaria de saber como faço para criar uma mascara em um EditText no formato ABC-1234. Estou tentando algo como exemplo abaixo, porém sem sucesso ainda.
public abstract class PlacaVeiculoMask {

public static String PLACA_MASK = "???-####";

public static String unmask(String s) {
    return s.replaceAll("[A-Z]{3}-[0-9]{4}", "");
}

public static TextWatcher insert(final EditText editText) {
    return new TextWatcher() {
        boolean isUpdating;
        String old = "";

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str = PlacaVeiculoMask.unmask(s.toString());
            String mask = PLACA_MASK;
            String mascara = "";
            if (isUpdating) {
                old = str;
                isUpdating = false;
                return;
            }
            int i = 0;
            for (char m : mask.toCharArray()) {
                if ((m != '#' && str.length() > old.length()) || (m != '#' && str.length() < old.length() && str.length() != i)) {
                    mascara += m;
                    continue;
                }

                try {
                    mascara += str.charAt(i);
                } catch (Exception e) {
                    break;
                }
                i++;
            }

            isUpdating = true;
            editText.setText(mascara);
            editText.setSelection(mascara.length());
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        public void afterTextChanged(Editable s) {
        }
    };
}

}
Answer: Fiz um exemplo que pode servir pra você.
    public static void main(String[] args) {
        String pattern = "HHH-HHH";
        String numeroProcesso = "ABC123";
        System.out.println(format(pattern, numeroProcesso));
    }

    private static String format(String pattern, Object value) {
        MaskFormatter mask;
        try {
            mask = new MaskFormatter(pattern);
            mask.setValueContainsLiteralCharacters(false);
            return mask.valueToString(value);
        } catch (ParseException e) {

       throw new RuntimeException(e);
    }

Caracteres válidos:
*  qualquer caractere
H  (0-9, a-f or A-F).

Para mais informações: https://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html
Answer: Eu tenho uma classe pra isso que utilizei uma vez:
class LicenseVehicleMask(var editText: EditText) : TextWatcher {

private var isUpdating: Boolean = false
protected var mOldString = ""
protected var mMask: String?= ""
internal var befores = ""

override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
    befores = s.toString()

}

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
    var str = s.toString()

    if (str.length == 0) {
        return
    }

    if (before == 1 && befores.length > 0 && !isUpdating) {
        val last = befores.substring(befores.length, befores.length)
        val rep = last.replace("(", "").replace(")", "").replace(" ", "").replace("-", "")
        if (rep.length == 0) {
            str = str.substring(0, befores.length - 1)
        }
    }

    mMask = DEFAULT_MASK

    val mask = StringBuilder()
    if (isUpdating) {
        mOldString = str
        isUpdating = false
        return
    }
    var i = 0
    for (m in mMask!!.toCharArray()) {
        if (m != '#') {
            mask.append(m)
            continue
        }
        try {
            mask.append(str[i])
        } catch (e: Exception) {
            break
        }

        i++
    }
    isUpdating = true
    val x = mask.toString()
    editText.setText(x)
    editText.setSelection(mask.length)

}

override fun afterTextChanged(s: Editable) {

}

companion object {

    val DEFAULT_MASK = "###-####"
}}

Comment: Aqui comigo não funcionou. A unica coisa que mudei foi a linguagem, fiz esse exemplo de código em Java
Comment: o que exatamente nao funcionou, a mascara nao chegou a pegar no edittext?
Comment: Meu edittext reconhece a mascara, entra na função. Porém não formata no valor correto.

EditText máscara veículo


Installing "cryptography" on Python 3.9.0a5 (error)

Question: just updated Python from 3.8.2 to 3.9.0a5 due to the merge operator for dictionaries.
When I now try to install "cryptography" in my virtual environment, I get the following error:
cryptography install error
Pip Version is: 20.1.1,
Python Version is: 3.9.0a5
Comment: You installed an alpha version (**a** in 3.9.0**a**5 is for alpha). I believe the latest (as of writing this comment) is beta 3 (Python 3.9.0b3) so try with that. However, keep in mind that a beta version does not guarantee everything will work, that's why it's a beta.
Answer: This package does not publish a wheel (precompiled) version for python 3.9 only up to 3.8
https://pypi.org/project/cryptography/2.9.2/#files
so this means that you will need to install the headers into your computer's build environment so that python can compile with openssl from source (on some linux systems that will be as simple as installing a package with the openssl headers and library, on windows you may also need to install a c compiler)
Answer: Thanks a lot! With your Instructions I was able to figure out the remaining steps.
Installing latest SSL for 64bit and setting env variables properly with:
<code>set LIB=C:\OpenSSL-win64\lib;%LIB%
set INCLUDE=C:\OpenSSL-win64\include;%INCLUDE%
</code>
fixed the issue :)


Logo image displaying at incorrect aspect ratio?

Question: According to Lighthouse, the main logo at the top of our page (nrsmart.com) is being displayed at the wrong aspect ratio. File name: nrsmart-logo-longtext.png. I've tried a bunch of things - including removing the image from the container (.thehomepage). Why is this happening? My CSS code looks correct to me... The other large image on the home page (nrs-nrsmart-national-remarketing-service.jpg) resizes fine with no aspect ratio change... So why would the logo have trouble?
Here is the Lighthouse report:
Displays images with incorrect aspect ratio
Image display dimensions should match natural aspect ratio.
Aspect Ratio (Displayed): 412 x 36 (11.44)
Aspect Ratio (Actual): 800 x 69 (11.59)
.responsivelogo {
  display:block;
  margin-left:auto;
  margin-right:auto;
  max-width:100%;
  height:auto;
}

It's in a container (.thehomepage):
.thehomepage {
  z-index:9999990;
  position:fixed;
  top:0px;
  width:100%;
  height:auto;
  background-color:white;
}

Any ideas? This is driving the perfectionst inside me insane!
Comment: What dimensions were you expecting? There's no way to perfectly scale with the scale multiplier between those two resolutions. The scaling is correct to within less than one pixel. Also, the other image you reference also has non-perfect scaling, it just depends on the browser size.
Comment: I posted about this a while back at Lighthouse - someone there suggested their analysis in the Lighthouse software is too strict. Thanks for helping clarify for me... I didn't realize my other image had non-perfect scaling. Lighthouse didn't report that one...
Comment: Shows correct to me. I think your report is testing on mobile devices and your logo is responsive so it adapts it's width, but the Lighthouse thinks it should be 800*69 since you specified it in the element.

Solutions I can think of:
1) Instead of Height, Width set Max-Width
2) Maybe there is an option in the Lighthouse to ignore such issues
Answer: As someone at Lighthouse suggested (that their analysis may have been too strict), they may have made a change to the way Lighthouse does their analysis.  I just scanned our site again, and the image aspect ratio error I was getting before is gone.  It no longer appears when I analyze our site, so the issue appears to be resolved.


How to deploy to AWS with circleci 2.0?

Question: I have config.yaml I try upload code to AWS. On first version it's works fine, but now it's doesn't work. How can I fix it? I added deploy section and wrote sh commands
version: 2
    jobs:
      build:
        working_directory: ~/myProject
        parallelism: 1
        shell: /bin/bash --login
        environment:
          CIRCLE_ARTIFACTS: /tmp/circleci-artifacts
          CIRCLE_TEST_REPORTS: /tmp/circleci-test-results
        docker:
        - image: circleci/build-image:ubuntu-14.04-XXL-upstart-1189-5614f37
          command: /sbin/init
        steps:
        - checkout
        - run: mkdir -p $CIRCLE_ARTIFACTS $CIRCLE_TEST_REPORTS
        - run:
            working_directory: ~/myProject
            command: nvm install 8.9.1 && nvm alias default 8.9.1
        - restore_cache:
            keys:
            - v1-dep-{{ .Branch }}-
            - v1-dep-master-
            - v1-dep-
        - run: sudo sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) main universe restricted multiverse"
        - run: sudo apt update
        - run: sudo apt-get install python2.7-dev
        - run: sudo easy_install --upgrade six
        - run: sudo pip install --upgrade urllib3==1.21.1
        - run: sudo pip install --upgrade pip
        - run: sudo pip install --upgrade blessed
        - run: sudo pip install awsebcli==3.12.3 --ignore-installed six pyyaml
        - run: rm -rf /home/ubuntu/.aws
        - run: if [ -z "${NODE_ENV:-}" ]; then export NODE_ENV=test; fi
        - run: export PATH="~/myProject/node_modules/.bin:$PATH"
        - run: npm install
        - save_cache:
            key: v1-dep-{{ .Branch }}-{{ epoch }}
            paths:
            - vendor/bundle
            - ~/virtualenvs
            - ~/.m2
            - ~/.ivy2
            - ~/.bundle
            - ~/.go_workspace
            - ~/.gradle
            - ~/.cache/bower
            - ./node_modules
        - run: npm test
        - store_test_results:
            path: /tmp/circleci-test-results
        - store_artifacts:
            path: /tmp/circleci-artifacts
        - store_artifacts:
            path: /tmp/circleci-test-results
    deploy:
        name: deploy to AWS
        production:
            branch: production
            commands:
                - bash ./deploy_prod.sh
                - eb deploy stmi-production
        staging:
            branch: master
            commands:
                - bash ./deploy_staging.sh
                - eb deploy stmi-dev

Answer: This works for me:
machine: true
    steps:
      - checkout
      - run:
          name: create workspace
          command: mkdir -p /tmp/workspace
      - run:
          name: Install awsebcli package
          command: |
            sudo apt-get -y -qq update
            sudo apt-get install python-pip python-dev build-essential
            sudo pip install --upgrade awsebcli
            eb --version
      - run:
          name: installing dependencies
          command: |
            npm  install
      - run:
          name: deploy
          command: |
           bash deploy.sh
      - run:
          name: Removing aws config
          command: |
            rm -rf /home/circleci/.aws
      - run: ls /tmp/workspace
      - persist_to_workspace:
          root: /tmp/workspace
          paths:
            - status.txt`

And this is my deploy.sh
 mkdir /home/circleci/.aws
 touch /home/circleci/.aws/config
 chmod 600 /home/circleci/.aws/config
 echo "[profile user]" > /home/circleci/.aws/config
 echo "aws_access_key_id=$AWS_ACCESS_KEY_ID" >> /home/circleci/.aws/config
 echo "aws_secret_access_key=$AWS_SECRET_ACCESS_KEY" >>
 /home/circleci/.aws/config

  eb deploy $BEANSTALK_ENVIRONMENT --profile user --region
  $BEANSTALK_PRODUCTION_AWS_REGION &&
  echo 'Deployment Succeed' >> /tmp/workspace/beanstalk-deploy-
  status.txt

How to deploy to AWS with circleci 2.0?


Project architecture using Nuxt/Firebase

Question: I'm setting up a new project for my job, and I'd like some advice if possible. My project consist of using nuxt.js for frontend and firebase for backend. So it's basically 100% frontend project.
My website will have two big features :
1. The frontend side of thing: home page, search page, view profiles, etc.
2. The backend side of thing: a dashboard where the user can register and manage whatever data he will have to enter, edit, delete, etc.
So considering this project will become fairly big in the near future, and performance is a huge priority for this project,
My question is:
Would it be better to have two sub-project with different dependencies (node_modules and package-lock, etc) and also different nuxt.config.js. The subfolder for the dashboard would be in a sub-domain, example: www.dashboard.website.com, And for the frontend side would just be the main domain www.website.com.
OR
Just put everything in one big project and share the dependencies even if some won't be needed in the dashboard and vice-versa.
Answer: This isn't something that can be so quickly answered.
Consider some things.
Hosting - I assume you already have these domains if not i suggest snatching them up along with their counterparts .org, .com, .info (Idk how big your company is but they should have resources for this)
Server - If you do not house your own, you will have to depend on a reliable provider with great up time and speed.
Data - Design a data structure for every metric you will be housing and think in terms of how you can possibly add more you aren't thinking of. Determine the types, location, callbacks, descriptions, etc. (I advise heavy documentation/excel file of each metric you create)
Security - Depending on what your hosting on your servers - if they are yours, you have to be in compliance with all laws and regulations. If your hosting eu data you will have more regulations. I would ask your IT department if they require an audit etc before hand.
Storage - What types of files, data will you be processing in forms of all request types and how they will affect your front end/backend.
That's now answering the direct question but if you plan better based off your original question you wont be stuck recreating the first month over and over because of complications,
Comment: All the hosting will be through Firebase cloud storage directly (Firestore).

The data will be managed there, and the website will also be deployed through firebase as well. For security, that's a good idea thank you !

I'll base my structure around all those things and make sure to think about everything so just like you said, I don't have to re-do it again. Great insight thanks a lot


How to terminate AWS managed blockchain instance

Question: I followed these instructions below to get an AWS Ethereum instance running, however since I am just learning blockchain, I would like to create an image and start/stop as needed. However when I go to EC2 and stop my instance, it restarts. I saw other posts about this being caused by elastic beanstalk but when I go to elastic beanstalk, I don't see anything there. What else could be causing it to restart?
Thanks!
https://docs.aws.amazon.com/blockchain-templates/latest/developerguide/blockchain-templates-getting-started.html
Comment: Do you have an Auto Scaling Groups? Check.
Comment: No, both AWS Auto Scaling and Elastic Beanstalk have nothing.
Comment: Although when I go to CloudFormation > Stacks.. one of the stacks description says "This template creates an AutoScalingGroup of EC2 Instances"
Answer: If you check the source code of one of its nested stacks ethereum-autoscalegroup.template.yaml, you can see that it actually creates instances in an autoscaling group (ASG).
Instances in ASG can't be stopped. However, you can terminate them, by setting desired capacity and minimum capacity to 0 of your ASG. Then if you want to create new instances when you need them, you can change desired capacity back to 1.
Comment: Ok thanks. I was looking under AWS Auto Scaling > Scaling plans when I should have looked under EC2 > Auto Scaling groups


Solving a linear program thanks to complementary slackness theorem

Question:
Using the complementary slackness theorem, say if the following basis optimal:
$$x_1*=0=x_5*,x_2*=4/3,x_3*=2/3,x_4*=5/3$$
\begin{cases}
\max & 7x_1 &+6x_2&+5x_3&-2x_4&+3x_5\\
&x_1 &+3x_2 & +5x_3 & -2x_4 & +2x_5&\le 4\\
&4x_1 & +2x_2 & -2x_3 & +x_4 & +5x_5&\le 3\\
&2x_1 & +4x_2& +4x_3 & -2x_4 & +5x_5&\le5\\
&3x_1 &+x_2 & +2x_3 & -x_3 &-2x_5&\le 1\\
\forall i, x_i\ge 0
\end{cases}

I know it is feasible because:
\begin{cases}
3*4/3&+5*2/3&-2*5/3&=4, ok\\
2*4/3&-2*2/3&+5/3&=3,ok\\
16/3& +8/3&-10/3&=14/3<5,ok\\
4/3& +14/3&-5/3&=1,ok
\end{cases}
I did the dual but I'm definitely not sure about it and I'm looking for the rules related to the dual construction:
\begin{cases}
\max & 4y_1 &+3y_2&+5y_3&+y_4&\\
&y_1&+4y_2 &+2y_3& +3y_4&= 7\\
&3y_1&+2y_2&+4y_3&+y_4&=6\\
&5y_1&-2y_2&+4y_3&+2y_4&=2\\
&2y_1&+y_2&+5y_3&-2y_4&=  3\\
\forall i, y_i\ge 0
\end{cases}
I'm not sure about it, and I don't know what to do from here.
Do I have to find all $y_i$?
Comment: Why do you have only 4 constraints although there are 5 variables at the primal problem ? The third constraint is missing.
Comment: @callculus, I don't know, it is the way it was given in Linear Programing by Vasek Chvàtal p69, Problem 5.3.a
Comment: @callculus, you were right, one line is missing in the dual
Answer: I use the table below to create the dual problem. If you have any question about the table or other aspects of my answer feel free to ask.
\begin{cases}
\min & 4y_1 &+3y_2&+5y_3&+y_4&\\
&y_1&+4y_2 &+2y_3& +3y_4&\geq 7\\
&3y_1&+2y_2&+4y_3&+y_4&\geq6\\
&5y_1&-2y_2&+4y_3&+2y_4&\geq5\\
&-2y_1&+y_1&-2y_3&-y_4&\geq -2\\
&2y_1&+5y_2&+5y_3&-2y_4&\geq  3\\
\forall i, y_i\ge 0
\end{cases}
You have evaluated the values of the slack variables ($s_i$). The result is right. $s_1=s_2=s_4=0$. And $s_3=5-\frac{14}{3}=\frac{1}{3}>0$

Now we can apply the complementary slackness theorem:
$x_j\cdot z_j=0 \ \forall \ \ j=1,2, \ldots , n$
$y_i\cdot s_i=0 \ \forall \ \ i=1,2, \ldots , m$
$s_i \text{ are the slack variables of the primal problem.}$
$z_j \text{ are the slack variabales of the dual problem.}$

Since $s_3 > 0$, we can conclude that $y_3=0$
And $x_2=x_3=x_4> 0 \Rightarrow z_2=z_3=z_4=0$
Now we can take the constraints 2,3,4 from the dual and replace the $\geq$-signs by the equality signs. Additionally we can drop the terms with $y_3$.
\begin{cases}
&3y_1&+2y_2&+y_4&=6\\
&5y_1&-2y_2&+2y_4&=5\\
&-2y_1&+y_1&-y_4&= -2\\
\end{cases}
Finally you have to solve this little equation system.

Remark
If the primal problem is a min problem then you read the table from right to left. Et vice versa.
Comment: Thank you for this very insightfull answer!
I had two questions, how does the first and last line of the dual disapeared? Second you talked about $s$ and $z$ in your dual theorem but you don't use such variables then, why?
Comment: First question: The first and the last constraint are not very helpful here. We can´t get rid of the **in**equality signs.  We know from the primal problem that $x_1=x_5=0$. Therfore $x_1\cdot z_1=0$ and $x_5\cdot z_5=0$. In both cases the product is zero no matter what $z_1, z_5$ is. We cannot be sure, that $z_1$ or $z_2$ are zero. They are both slack variables of the dual problems (constraint 1 and 5). Second question: If we have inequalities then the slack variables are not need. But to transform the inequlities in equalities we need slack variables.
Comment: The fifth constraint can be written with an inequality sign or with an equality sign. $2y_1+5y_2+5y_3-2y_4\geq  3\Rightarrow 2y_1+5y_2+5y_3-2y_4-z_5  =3$ The slack variable has a positive value. In combination with the minus sign $z_5$ are subtracted, because the rest of the LHS ($2y_1+5y_2+5y_3-2y_4$) is greater than 3.
Comment: First: Since $s_3 > 0$, we can conclude that $x_2=x_3=x_4> 0 \Rightarrow z_2=z_3=z_4=0$, why is it important to say it? We don't use it then, don't we? Second: I tried some linear combination to understand why were the first and the last constraint not useful but I still don't figure it out...
Comment: @Marine1 Second question: Now we have a linear equation system of three equations and three variables. This has a unique solution. Thus we dont´have to care about the first and fifth constraint. Have you been able to evaluate the values of $y_1,y_2$ and $y_4$ ?
Comment: First question: No, from $s_3>0$ we can conclude that $y_3=0$, because $y_i\cdot s_i=0$. Therefore we can drop all terms with $y_3$, because the are all equal to zero. Next one. From $x_2>0$ we can conclude that $z_2=0$,  because $x_j\cdot z_j=0$. Similar reasoning for $z_3$ an4 $z_4$. The second constraint of the dual is $y_1+4y_2 +2y_3 +3y_4\geq 7$. In general we can introduce a slack variable to transform it into an equality: $y_1+4y_2 +2y_3 +3y_4-z_2 =7$. From above we know that $z_2=0$. Therefore we can drop $z_2$. For the same reason the third and the fourth constraints are equalities.
Comment: @Marine1 You have to read the last two comments in opposite order.
Comment: Second: actually the second constraint of the dual is $3y_1+2y_2+4y_3+y_4\ge 6$. We should therefore have:

\begin{cases}
\min & 4y_1 &+3y_2&+5y_3&+y_4&\\
&y_1&+4y_2 &+2y_3& +3y_4&\geq 7\\
&3y_1&+2y_2&+4y_3&+y_4&=6\\
&5y_1&-2y_2&+4y_3&+2y_4&=5\\
&-2y_1&+y_1&-2y_3&-y_4&= -2\\
&2y_1&+5y_2&+5y_3&-2y_4&\geq  3\\
\forall i, y_i\ge 0
\end{cases}

isn't it?
First: Okay for the reasons we don't bother with the first and fifth dual constraints. We chose them because we had equalities and because their associated slack variables were null thanks to the fact that $x_1*=x_5*=0$, that's it?
Comment: @Marine1 After applying then we can transform the dual problem like you have done. The slack variables of the constraints $2,3,4$ are null thanks to the fact $x_2,x_3,x_4 > 0$. Btw what about $y_3$ ?
Comment: oh yeah I forget, it had to disapear!
Comment: @Marine1 That´s right !


How to create a IUSHR4 on IJVM?

Question: i need to create an extension of MAL.
So, first i had tried to add on mic1sim.mal
<code>MAR = SP = SP + 1;  rd             // read top of the stack
H = TOS                           // H will be a SP
MDR = H = H >> 1; wr              // SHIFT 1  and write on MDR
MDR = H = H >> 1; wr                 // SHIFT 1 + 1 = 2
MDR = H = H >> 1; wr              // SHIFT 1 + 1 + 1 = 3
MDR = H = H >> 1: wr              // 4th shift
TOS = MDR; goto Main1             // TOS updated
</code>
But doesn't work! Can someone explain me where i wrong?
Answer: SP points to the top of the stack. SP + 1 points to data that is no longer on the stack. Reading this value will return garbage. You have a condition where two different values are being written to MDR in the third instruction: the result from the ALU operation and the data from memory from the read in the first instruction.
It is not necessary to write after each shift. Calculate the result in H. When done, store the value of H into MDR and write the value to the stack.
TOS already has the top value on the stack at the start of the instruction. It is not necessary to read it.

How to create a IUSHR4 on IJVM?


Prove that $\theta \cdot (x,y)=(x\cos(\theta),x\sin(\theta)+y\cos(\theta) )$ is an group action.

Question: Let $G$ the additive group of $\mathbb{R}$ and $\mathbb{X}=\mathbb{R}^2$
Prove that
$$\theta \cdot (x,y)=(x\cos(\theta),x\sin(\theta)+y\cos(\theta) ) $$
Define a group action of $G$ in $\mathbb{X}$
My attempt:
By definition $\theta:G\times \mathbb{X}:\rightarrow\mathbb{X}$ define a group action if
We know that $0$ is the zero element of $G$, then:
$0\cdot (x,y) = (x\cos 0,x\sin 0+y\cos 0) = (x,y)$ for all $(x,y)\in \mathbb{R}^2$
Now, we need to prove that $(\theta + \beta)\cdot(x,y)=\theta+(\beta\cdot(x,y))$ here i'm stuck. can someone help me?
Answer: the last thing you need to prove is that the way the group acts on things is consistent with the way elements in the groups are combined. So, that means "Apply $\beta$ to a point, and then applying $\theta$, is the same as [adding/multiplying] $theta$ and $\beta$, and then applying the result."
For example, matrices act of vectors. If you happen to have a collection of matrices that form a group under matrix multiplication, then yes, it's a group action, because $(AB)\mathbf{x}=A(B\mathbf{x})$ for any vector $\mathbf x$ and matrices $A$ and $B$. If your collection of matrices is a group under matrix addition though, then the group doesn't act on vectors as a group action: $(A+B)\mathbf x$ is not equal to $A(B\mathbf{x})$.
For your example, what you need to prove is that
$$\theta\cdot(\beta\cdot(x,y))=(\theta+\beta)\cdot(x,y)$$.
The simplest way is to expand the left hand side and the right hand side, and try to show they're equal. The left hand side is:
$$\theta\cdot(\beta\cdot(x,y)) = \theta\cdot(x\cos\beta, x\sin\beta+y\cos\beta)$$
which in turn is
$$\left((x\cos\beta)\cos\theta, (x\cos\beta)\sin\theta+(x\sin\beta+y\cos\beta)\cos\theta\right)$$
The right hand side is
$$(\theta+\beta)\cdot(x,y) = \theta\cdot(x\cos(\theta+\beta), x\sin(\theta+\beta)+y\cos(\theta+\beta))$$
To prove these are equal, you'd then use a bunch of trig to simplify things. Unfortunately, it will turn out they are not equal, and therefore this map from $G\times{\mathbb X}$ to $\mathbb X$ is not a group action.
Are you sure you typed the question correctly? Perhaps you meant
$$\theta\cdot(x,y)=(x\cos\theta-y\sin\theta, x\sin\theta+y\cos\theta)$$ instead?
Comment: Thanks @Michael Hartley yes, i made a mistake but know i understand how to proceed with the exercise. Thanks
Answer: I think your argument failed to be consistent at the end of your approach. you wrote $$(\theta+\beta)\cdot (x,y)=\theta+\beta\cdot(x,y) $$ which is wrong as $\beta\cdot (x,y)$ is an element of $X=R^2$ so $\theta$ will act as an action on $\beta\cdot(x,y)$.Therefore a natural symbol will be $\theta\cdot(\beta\cdot(x,y))$ on the right hand side.
So we are to show that $$(\theta+\beta)\cdot(x,y)=\theta\cdot(\beta\cdot(x,y)). $$Now,$(\theta+\beta)\cdot(x,y)=(x\cos(\theta+\beta),x\sin(\theta+\beta)+y\cos(\theta+\beta))$ and $\theta\cdot(\beta\cdot(x,y))=(x\cos\beta\cos\alpha,x\sin(\alpha+\beta)+y\cos\beta\cos\alpha)$ which may not be same all the time. So the proposed function may not be a group action. thank you.


How do I stop git from deleting what is on a server subdirectory?

Question: My main directory structure is /site_program_files/users/usr1
I don't want Git to touch what is in a /users directory and subdirectories...
So, I have added /users to my .gitignore file and did a commit then push. And also deleted what was there before with git rm -rf /users.
But now, every time I push it deletes all the files my users updated in their /users directories on the hosted website. All I want is for git not to affect what is in the /users subdirectory on the server, regardless what I'm doing for testing on my local version of it. What am I doing wrong?
Comment: You asked git at some point to track everything in `users/` and later told it to delete everything in `users/`. It is natural that every clone that takes the "delete from `users/`" commit would delete the `users/` directory; that's what the commit was all about anyway! But from that point on, `users/` would remain untouched. So this is a one-time thing for each clone, and they can always retrieve the files in `users/` from a previous version.
Comment: Actually @KeyWeeUsr's statement is quite wrong. `.gitignore` doesn't force a directory to be emptied. It just doesn't show you that there are files to be added.
Comment: I guess it's because of .gitignore. It ignores all files, so when you push, it sends an empty folder which replaces folder on server.
Comment: It's terrible logic this Git s*ht ;-)  I just want it not to mess with that subdirectory, what do I do?
Comment: http://stackoverflow.com/questions/10100933/how-to-ignore-files-and-folders-with-pull-requests-to-github-in-distinct-git-clo
Comment: So now how do I stop it from always deleting that subdirectory and what is under it in the future? I need to be able to test it locally but not replicate what happens with that subdirectory to the server. It should certainly not delete that subdirectory on the server
Comment: Repeat after me: "Don't push to a non-bare repository. Ever."
Comment: @CodeGnome I never did... The first thing I ever did is pull from master. So, any other ideas?
Comment: If you're not pushing to a non-bare repository, then your post is flawed. You are blaming Git (a tool you don't understand) for behavior of something on OpenShift (a platform you don't understand) using a deployment process you don't understand and haven't included in your post. This is not a Git issue, so unless you include the relevant programming-related code, this question is likely to be closed as off-topic *as a programming question.*
Comment: @CodeGnome... Look, the gist of it is that Git and or Openshift process has allowed my to get out of sync. Now, I just need a simply way to override that Git-jive and make the remote (hosted version) be the same as what is on my mac. If there isn't a way to do that in Git for these special circumstances than Git does have a flaw... and that started with the .gitignore not ignoring issues I experienced in the onset ;-)
Answer: (I assume your hosted website has some sort of auto-deploy script.  Unless you show this script, we must make some assumptions about it.  For now I will assume it consists mostly or solely of a git checkout command.)
Edit: the actual deployment code appears to be a custom OpenShift Ruby script (which is never shown on this linked page): https://developers.openshift.com/en/managing-deployments.html.  Someone familiar with OpenShift and Ruby can perhaps comment on what the default deployment script really does.  If it's not just git checkout (and clearly it's not), some of the assumptions below are unlikely to hold.
Edit 2: this appears, in the end, to be a question about OpenShift.  The problem appears to have nothing at all to do with git.
You can't really get around this in git, at least not without custom hacking.  The reason why is simple enough:

As far as git knows, you are (on the hosted web site) asking it to move from $old_commit (whatever ID that is) to $new_commit (another ID).
So, git compares what's in $old_commit vs what's in $new_commit.
The old commit had files users/usr1/foo and users/usr2/bar.  The new commit does not.
Therefore, git must remove those files so that it makes the correct transition from old to new.

Git will do this every time you move from $old_commit to $new_commit, because those are the instructions needed to convert a work tree from $prev_commit to $new_commit.  It doesn't matter that in $new_commit, the files are in .gitignore (which doesn't mean "ignore", really): what matters is that they are in $old_commit and not in $new_commit.
But, we can observe one other thing: with any luck, git will only ever do this transition from $old_commit to $new_commit once.  What we need to do, then, is, on the hosted web site:

Move all the precious user files out of the way, so that they don't exist under their original names for a while;
Cause git to do the old-to-new conversion (which should silently "remove" the now-non-existent paths); and
Move the precious user files back.

The drawback here is that if you ever do somehow go back to $old_commit on the hosted web site—or indeed, any old commit that has those files—and then transition it to $new_commit (or any newer commit that no longer has the files), git will remove the files again.
It might be nice if git had an ignore syntax and/or file that marked particular files as "precious, do not destroy, though do not source control either"; but it doesn't (at least, not today).
Comment: At this point it's not the push itself doing it, and it's not git doing it, it's *something else*.  I don't know how to tell you this any better, it's *something in the deployment script* (not git).  Git has plenty of flaws, but not this particular one.  Given that *it's in the deployment script* you're going to have to *change the deployment script*.  Nothing else will help.
Comment: Luckly,  everything in the /users directory on the server is still just testing crap. So at the moment the web-app recreated /users/usr1 from the database. But now if I change something on my mac and commit push again, will it again wipe out those directories? Or will it adhere to that /users in the .gitignore file? I just want to tell it to forget/ignore everything it ever did or will do with /users
Comment: Once the server's current commit is one that does not have the user files in it, moving from that commit to another commit that also does not have the user files in it, git won't *remove* the user files.  However, what gets deployed depends on the precise deployment script on the server, which you have not shown, so it's not possible to say for certain.
Comment: So here's what I think might work.  Delete the /users and its subdirectories on my mac, then do a git add and git commit. Then recreate /user on my mac, and again git add then commit. Then Git push to the server
Comment: I don't know what you are initially `git add`ing in the comment above.  Remember that both `git add` and `git rm --cached` merely adjust the *index* (what will be in the *next* commit).  When you `git push`, you transfer commits (not the index) to the pushed-to repository.  What that site does with the new commits depends on the deployment script code.
Comment: How can I just get rid of/reset Git (its tracking and repository) and tell it to start over from scratch with /users in the .gitignore and begin with a first add and commit?
Comment: Again, we're all kind of working in the dark, because you haven't shown us what's on the server.  All of your issues have to do with what the server is doing, but for all we know, the server could be acting on radio messages from Mars, rather than anything you're doing on your end.
Comment: It's a rails app on Openshift. All my Git commands have been from my Mac since I did an initial pull after initially deploying the app to the server. My only mistake was that I did not add /users to .gitignore from the onset... I dont care about the Git repository... this is still just me myself and I... How can I just reset it to make that initial push again?
Comment: Hm, now we might be getting somewhere.  Following some links I arrived at https://developers.openshift.com/en/managing-action-hooks.html - but this is getting deep into RoR territory and I know nothing of Rails and relatively little of Ruby.  But it looks like you're supposed to write specific action hooks to make things happen.
Comment: I don't think it's rails based... This to me, it seems like Git BS on the dir/file structure outside of Rails. The users dir is just another  dir with text files in it. I just want to get Git to really to it's job and "ignore" it (like I told it to in .gitignore) when I push the root directory. There  must be a way,..
Comment: It clearly is specific to OpenShift.  Click on "deployments" and you get to https://developers.openshift.com/en/managing-deployments.html which talks about how to modify their standard deployment script (but does not show their standard deployment script, but it probably is written in Ruby).
Comment: OK, but by default (which is what I chose) Openshift deploy just follows the Git push directives. My problem now is finding a way to get Git to do exactly what .gitignore says, or reset it and have it delete the Git repository and start froms cratch with the right .gitingore ignores
Comment: @GreenChief If starting from scratch is an option for you, then `git-filter-branch` may be your friend. It rewrites the history (beware!) and it's easy to get a history which has always ignored `/users` and never stored anything there.
Comment: @maaartinus ok so what do I type to do that on my local machine?
Comment: You say that it "follows the push directive", but we need to know *what it does at that point*.  For instance, suppose that on a `git push`, the default script starts with `rm -rf $target` followed by `git --work-tree=$target checkout $branch`.  In this case the target directory `$target` will initially be emptied on every `git push`, no matter what is in the repository.  This is what I mean when I say "we need to know what is in the deployment script".  (If you look at their examples, it clearly does more than just `git checkout`: we see output like `remote: Waiting for stop to finish`.)
Comment: Now a Git push is removing the /users directory on the server, even it it remains on my local mac. So it's all f*ch*d up. They must fix Git to work better than this...
Comment: What if I just type Git reset --hard origin/master. Fix the .gitignore, git add it, commit and push to master?
Comment: @GreenChief I used `git-filter-branch` just a few times, so I can't help you more than any random documentation can. But it looks like `--index-filter` could be all you need. Something like `git-filter-branch --index-filter "git rm --cached --ignore-unmatch" /users HEAD` could do. Backup everything first!


Find $\lim\limits_{n \rightarrow \infty} \frac{n(\sqrt[n+1]{n+1} - 1)}{\ln{n}}$.

Question: So I came across an interesting problem, find: $\lim\limits_{n \rightarrow \infty} [(n+1) \sqrt[n+1]{n+1} - n \sqrt[n]{n}]^\frac{n}{\ln n}$
After proving that $(n+1) \sqrt[n+1]{n+1} - n \sqrt[n]{n}$ converges to $1$, I added $1$ subtracted $1$, and then I needed to find: $\lim\limits_{n \rightarrow \infty}\frac{n}{\ln n}[(n+1) \sqrt[n+1]{n+1} - n \sqrt[n]{n} - 1]$
I quickly split this limit into two parts: $\lim\limits_{n \rightarrow \infty} \frac{n}{\ln n}[n(\sqrt[n+1]{n+1} - \sqrt[n]{n})]$ and $\lim\limits_{n \rightarrow \infty} \frac{n}{\ln n}(\sqrt[n+1]{n+1} - 1)$. I proved that these two limits are opposites, so added
together would equal $0$. There is a problem in this though, if the limits are not finite, their sum would be undefined.
To conclude, I either need to find one of the two limits listed above, or at least prove that one of the limits is finite.
Comment: might help https://math.stackexchange.com/questions/3909506/how-is-it-correct-lim-n-rightarrow-inftynn1-sqrtn1n1-n-sqrtnn?noredirect=1
Comment: I see that you are romanian :)))
Answer: For $$\lim_{n \to \infty} \frac{n(\sqrt[n+1]{n+1}-1)}{ln(n)}=\lim_{n \to \infty} \frac{n}{ln(n)}\cdot(\sqrt[n+1]{n+1}-1)=\lim_{n \to \infty} \frac{n}{ln(n)}\cdot(e^{\frac{ln(n+1)}{n+1}}-1)=\lim_{n \to \infty} \frac{n}{ln(n)}\cdot\frac{(e^{\frac{ln(n+1)}{n+1}}-1)}{\frac{ln(n+1)}{n+1}}\cdot \frac{ln(n+1)}{n+1}=\lim_{n \to \infty} \frac{ln(n+1)}{ln(n)}\cdot \frac{n}{n+1}\cdot\frac{(e^{\frac{ln(n+1)}{n+1}}-1)}{\frac{ln(n+1)}{n+1}}$$
All of those terms tend to $1$ for the first 2 being obvious and for the last one we have that $$\lim_{n \to \infty} \frac{ln(n+1)}{n+1}=0$$ by Cesaro-Stolz so the last term is a fundamental limit:
$$\lim_{x \to 0} \frac{e^x-1}{x}=1$$
Comment: I think that you wrote it wrong. It needs to be (n+1)th root, not square root


Fazer uma query com laravel com a seguinte lógica

Question: Olá amigos da comunidade. Preciso preencher um gráfico mas não consigo montar a query para receber os atributos, alguém poderia me ajudar? A query que preciso fazer é a seguinte.
select client.name, count(*) as Tickets
from client, ticket
where client.id = ticket.client_id
group by client.id

Answer: Pode tentar:
use DB;
...
$dados = DB::select('select client.name, count(*) as Tickets
from client, ticket
where client.id = ticket.client_id
group by client.id');

Comment: Funcionou direitinho, valeu amigo :)
Comment: De nada @FelipePaetzold, ainda bem


animateWithDuration() stops after app exit

Question: I've incorporated a glow effect into my UIButtons, (code taken from https://github.com/bc-oscar/Glowing-UIButton). The code is in a separate swift file and the buttons are defined in the view controller as being of type 'GlowingButton', and changed to derive from this custom class in the identity inspector. The effect works when the app is run the first time but then stops when returning to it after exit?
import UIKit

class GlowingButton: UIButton {

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
    // Drawing code
}
*/

// Creates a glow effect in the button by setting its layer shadow properties
func startGlowWithCGColor (growColor:CGColor) {
    self.layer.shadowColor = growColor
    self.layer.shadowRadius = 10.0
    self.layer.shadowOpacity = 1.0
    self.layer.shadowOffset = CGSizeZero
    self.layer.masksToBounds = false

    // Autoreverse, Repeat and allow user interaction.
    UIView.animateWithDuration(1.0, delay: 0, options: [UIViewAnimationOptions.Autoreverse,                                                         UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.Repeat, UIViewAnimationOptions.AllowUserInteraction],
        animations: { () -> Void in
            // Make it a 15% bigger
            self.transform = CGAffineTransformMakeScale(1.15, 1.15)
        }) { (Bool) -> Void in
            // Return to original size
            self.layer.shadowRadius = 0.0
            self.transform = CGAffineTransformMakeScale(1.0, 1.0)
    }
}

// Removes the animation
func stopGlow () {
    self.layer.shadowRadius = 0.0
    self.transform = CGAffineTransformMakeScale(1.0, 1.0)
    self.layer.removeAllAnimations()
    self.layer.masksToBounds = true
}

}
Answer: That's because you are calling startGlowWithCGColor in your viewDidLoad, try putting it in viewDidAppear
https://github.com/bc-oscar/Glowing-UIButton/blob/master/SampleApp/Sample%20App/ViewController.swift#L24
Comment: I made a `viewDidAppear` function and put the `button.startGlowWithCGColor` calls in there, but it still didn't work.
Comment: Neither answer nor comment has helped me so far.
Answer: I don't fully understand what causes this but it seems exiting the app leaves the function stuck on self.transform = CGAffineTransformMakeScale(1.0, 1.0). Recursively calling the function with self.startGlowWithCGColor(growColor) restarts the effect.


Java println method from another class

Question: I'm having a bit of a problem with a method from another class
The method i want to is:
/**
 * Prints out information about the owner
 */
public void printOwnerInfo()
{
    System.out.println("Information about the owner of the forest");
    System.out.println("Name: " + name);
    System.out.println("Adresse: " + adresse);
    System.out.println("Phone Number: " + phone);
}

I would like to have this information printed along side:
/**
 * Prints out information about the forest
 */
public void printForestInfo()
{
    System.out.println("Information about forest: " + name);
    System.out.println("Location: " + location);
    System.out.println("Square meters: " + squareMeters);
    System.out.println("Price per square meter: " + price + " euro");
    System.out.println("Price for the forest: " + (squareMeters * price) + " euro");
    System.out.println.forestOwner.printOwnerInfo();
}

I've declared the "Owner" class in the "Forest" field as:
public Owner forestOwner;

But I can't seem to get it to print out the Owner information with the Forest information.
they work fine each on there own.
Comment: Change `System.out.println.forestOwner.printOwnerInfo();` to `forestOwner.printOwnerInfo();`.
Answer: This makes no sense
System.out.println.forestOwner.printOwnerInfo();

I guess you want to print from the object forestOwner the method printOwnerInfo() so:-
forestOwner.printOwnerInfo();

Which will call the method on the object and the Printlns are handled in there
Answer: This call doesn't make sense:
System.out.println.forestOwner.printOwnerInfo();

This would only start to be sensible if printOwnerInfo() returned a String (which you're then passing into your System.out.println call), and if you corrected the chain of calls. So, either replace that line with this:
forestOwner.printOwnerInfo()

... or have that owner method return a String instead and call it like so:
System.out.println(forestOwner.printOwnerInfo());

Answer: I think you need to do something like the following in the printForestInfo method:
forestOwner.printOwnerInfo();

... as your code prints to the console from within that method. The 'out' field of the System class is declared static and public, thus it is "available" globally.

Java println method from another class


E/AndroidRuntime(14021): FATAL EXCEPTION: grpc-default-executor-0

Question: Initially, the app was not crashing but it was not able to read/write from firestore. So I added apply plugin: 'com.google.gms.google-services' in app gradle and classpath 'com.google.gms:google-services:3.1.0' in project gradle. Also, I added <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in AndroidManifest.xml. But this error is occuring now.
E/AndroidRuntime(14021): FATAL EXCEPTION: grpc-default-executor-0
E/AndroidRuntime(14021): Process: com.ayushsaxena.dhira, PID: 14021
E/AndroidRuntime(14021): java.lang.AssertionError
E/AndroidRuntime(14021):    at io.grpc.internal.DnsNameResolver.getResourceResolver(DnsNameResolver.java:536)
E/AndroidRuntime(14021):    at io.grpc.internal.DnsNameResolver.access$500(DnsNameResolver.java:60)
E/AndroidRuntime(14021):    at io.grpc.internal.DnsNameResolver$1.run(DnsNameResolver.java:211)
E/AndroidRuntime(14021):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime(14021):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime(14021):    at java.lang.Thread.run(Thread.java:919)
E/libEGL  (14021): call to OpenGL ES API with no current context (logged once per thread)

Comment: It seems to be an issue with the JDK version, try to update it to 64bits
Comment: did you added the internet permission?
Comment: `android.permission.ACCESS_NETWORK_STATE` != `android.permission.INTERNET`. Try the latter.
Comment: Where to write it?@Lee3
Answer: I was able to solve a similar issue by adding the Firebase Bill of Materials (BOM) as dependency.
See:
https://firebase.google.com/docs/android/learn-more#bom
In my case:
apply plugin: 'com.google.gms.google-services'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

dependencies {
    implementation platform('com.google.firebase:firebase-bom:26.1.0')
    implementation 'com.google.firebase:firebase-messaging'
}


Precalculus Trig Problem

Question: I have no clue where to start this problem, some help would be awesome and much appreciated!

$$\text{If }\sin(x)-\cos(x)=-0.3, \text{ evaluate }\sin(2x).$$
Answer: Note that
$$(\sin(x) - \cos(x))^2 = \sin^2(x) + \cos^2(x) - 2 \sin(x) \cos(x) = 1 - \sin(2x)$$
Now use this to compute what you want.

Precalculus Trig Problem


Leveraging rsync for a local copy between two slow drives, benefits without a daemon

Question: I am confused by the benefits of rsync (3.1.1) if there is no daemon running remotely, e.g. copying from a drive mounted via SMB2 (via a VPN) to an external HDD (USB 2.0, sadly). Both connections are slow (and my data is ~1TB), but I am confused how compression or careful diffing could speed things up if all this requires my CPU reading in the data in the first place, no? Both drives are local in this sense. (I cannot replace the SMB connection with SSH via rsync, as it cannot handle my password.) Or even with a remote drive, I am confused how rsync could do its magic if there is no one on the other end doing the compression before the data gets to the local CPU.
Is this a reasonable setup for such a copy?
rsync -vhcrC --progress src dest
-c: Maybe checksums are a bad idea, file size and timestamp might be the only thing rsync can check without loading the data in in the first place.
-h: human-readable output
-v: verbose
-C: skipping what CVS skips

omitting:
-a: I am not interested in archiving, as files move from Windows to mac, permissions will change anyway, I think
-z: this is the compression issue
-W: sometimes copying whole-files-only use less of the CPU, but some files are really big here (~100GB), and an interrupted transfer is better restarted

Comment: you wrote...I cannot replace the SMB connection with SSH via rsync, as it cannot handle my password... Why? IMHO rsync with password less ssh works fine.
Comment: @Jayan But I do have a password, and I cannot turn it off. Did I write anything different?
Answer: Note: the following is all going off theory -- the real right way to make sure this is correct in your situation is to run tests on various combinations of options.
The data connections in an rsync operation look something like this:
Source disk <-> rsync instance <-> other rsync instance <-> destination disk

In general, rsync is designed for the case where the first and last links (between the rsync instances and their disks) are fast, and the middle link (between the rsync instances) is slow. This is especially true of the -z (compression) and -c (checksum files to decide which to transmit); in a situation where the both rsyncs are on the same computer (therefore with a fast connection), these options basically make no sense.
More specifically: the -z option compresses data over the middle link, trading off higher CPU load on both ends for lower bandwidth need on the middle link. If the middle link's fast, save CPU by skipping this option.
As for the -c option, this forces both rsyncs to read all files that don't need to be synced in full in order to really make sure they don't need to be synced. If either or both of the disk links are slow, and there are a lot of files that're already in sync, this will slow the process down proportionally. As long as you don't need to worry about files contents changing without their timestamps also changing, you should avoid this one. Note that omitting this isn't much use unless you also add the -t option (or -a) so it'll copy timestamps -- without those, it'll have to compare everything anyway.
You might also want to add the -W option (just copy whole files, skip the compare-and-find-just-the changes), as that'll avoid extra reading of modified files. This probably isn't necessary, though, as all the versions of rsync I'm familiar with do this automatically when both source and destination are specified as local paths (which should apply even if one of those local paths happens to be within a network mount point).
Short summary: remove -c, add -t and maybe -W.


Why is SQL Server limiting speed to/from one database from IIS

Question: I am having troubles with SQL server (or IIS, but I am pretty sure its SQL)
I have posted before with a more vague question, however its still happening and I have some more detailed information.
Previous Post
The problem:
SQL Server 2008r2 to Website (iis 7) appears to be limiting data transfer speed when the IIS website tries to access it. The speed appears to get limited to 1Mb per second.
This fixes itself if I restart the database service, or take the DB offline, but I would rather not have to do this every week.
Some trouble shooting:

File transfers from the same machines are fine, so I don't think its the network.
I can connect from my local SQL Management studio, and query the SAME database fine
Other websites on the same IIS server to the SQL server do not suffer talking to other DBs
Pointing our dev server to the live troublesome database has the same issues
Taking a copy of the database and putting that on another SQL doesn't have the issue

So, I think I have whittled it down to one Database within SQL seems to be having intermittent troubles transferring data to IIS.

Any ideas what would be causing this?
Why would it happen after a few
days of working normally?
Where can I start trouble shooting?

EDIT 1: NEW INFO
I have done some more tests, it seems that it is one specific Stored Procedure that, only sometimes, is only using 10% of the network speed.
When I was fiddling around with the SP, doing nothing other than "tweaking it" seemed to break the bottleneck and thus it started working normally again.
Help, this is driving me mad!
Thank you

Answer:
Pointing our dev server to the live troublesome database has the same
  issues

That indicates that it is an issue with that particular web app, since you say other web apps don't have this problem.
Unless those other web apps use radically different database data, performance should be at least comparable.
What you want to do is run a server-side trace on the database, and capture only the duration and rowset size for each SQL call from that server - and possibly from another server for comparison.
You can then plot this against perfmon captured data for SQL server and the IIS machine - yes, SQL Server Profiler fully supports this scenario :)
This will yield zoom-, scroll-, and clickable graphs for all the data you put in; refer to SQL Server Profiler help (BOL) for details on how to set this up.
Comment: Hi, thanks for your reply. I fiddled around in perfmon and SQL Profiler and didn't get much (information overload). However, your reply prompted me to do some other tests. I have edited my question with more details.
Answer: If it's a single SP that seems to be the problem, and 'tweaking' it appeared to resolve the issue, the problem is probably down to the compiled execution plan - it may have been compiled for a set of parameters that cause it to run slower for other, more common sets of parameters.
Next time you have the problem, try running a dbcc freeproccache and see if that resolves it. If it does, you could add a WITH RECOMPILE hint to the SP itself to stop the plan being cached.


Google Analytics Embed API: Display specific account data, not authenticated users

Question: I have this example - Embed API Third Party Visualizations - working locally and on a test server, but I'm unsure of what I need to do to ONLY display our organization's Google Analytics data instead of the user's personal GA account.
I created the project and clientID within our org's Google Account, but I'm obviously not understanding something big here.
I'm completely new to both GA's API and oAuth in general, so while I'm sure this has been answered multiple times, I wasn't completely sure which direction to look in.  If someone can give a helpful nudge in the right direction I'll happily be on my way.
Thanks everyone!
Answer: Embeded API uses Oauth2 to authenticate.   Oauth2 requires that a user give you access to their Google Analytics data.
You want to show your person Google Analytics data to other users.  Normally I would say you should use a Service account, a service account gives the application direct access to a specific account it has to be set up like you would add a user to Google Analyitcs.   The problem is the Embeded API uses JavaScript, for security reasons its probably not a good idea to use a service account with JavaScript. I also think it may be against Googles terms of service to use a service account with JavaScript.   That being said I have never found anyone who has gotten a service account to work with JavaScript probably for the reasons I just stated.
Drop the embedded API and switch to a server sided language of some kind and code it yourself.    What you want to do cant be done with the embedded API.
Comment: Thanks for the explanation!  This makes more sense. I'm going to make your answer as correct and look into using a service account using PHP.


How to handle "create database permission denied in database 'master' in windows authentication exception?

Question: I opened "ASP.NET SQL Server Setup Wizard" using the command apsnet_regsql from visual studio 10 command propmpt(Run as Administrator).
In that wizard I selected Windows Authentication instead of Sql Authentication. When I tries to connect to Master Database I am getting the following exception
An error occurred during the execution of the SQL file 'InstallCommon.sql'. The SQL error number is 262 and the SqlException message is: CREATE DATABASE permission denied in database 'master'.
Creating the TestDB database
and the SqlException is:
create database permission denied in database 'master' in windows authenticAtion.
I understand that I don't have permission to create database. But how and where can I give permission to do that.
So please help me and give a solution for my problem.Thanks.
Comment: see this post may be helpful to you http://blog.techdreams.org/2007/11/create-database-permission-denied-sql.html
Answer: You need to login as a user who is a member of the sysadmin or dbcreator roles.
Comment: i am login the system with my admin credentials. how to change db roles?


Transitive closure of binary relation with proof of equivalence

Question: On the set X = {1,2,3,4,5,6,7,8,9}, there is binary relation Q = {(1,9),(2,5),(3,7),(4,1),(5,8),(6,2),(7,3),(8,6),(9,4)}. Make a transitive closure T of the relation Q. Decide and prove whether the relation T is an equivalence on X.
If yes, write out the partition belonging to this equivalence. If not, find the partition belonging to the least equivalence which contains the relation T. Also state how many classes does the partition have.

Could you please help me understand the way this is solved?
This is the solution I have in my study materials:
Q = {(1,9),(9,4),(4,1),(2,5),(5,8),(8,6),(6,2),(3,7),(7,3)}
Q2 = {(1,4),(9,1),(4,9),(2,8),(5,6),(8,2),(6,5),(3,3),(7,7)}
Q3 = {(1,1),(4,4),(9,4),(6,8),(2,6),(5,2),(8,5),(3,7),(7,3)}
Q4 = {(1,9),(9,4),(4,1),(2,2),(5,5),(6,6),(8,8),(3,3),(7,7)}
T = {(1,1),(4,4),(4,9),(1,4),(1,9),(4,1),(4,9),(9,1),(9,4),(2,2),(5,5),(6,6),(8,8),(2,8),(2,5),(2,6),(5,2),(5,6),(5,8),(6,2),(6,5),(6,8),(8,2),(8,5),(8,6),(3,3),(7,7),(3,7),(7,3)} = T-1
Which means T is symmetric and reflexive, because X = {(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),(8,8),(9,9)}. As a transitive closure T is transitive -> therefore it is an equivalence.
Answer: I don't like how it is written in your solution, it seems kind of tedious. I propose the following. First identify we have
$(1,9),(9,4),(4,1)$. We also have $(2,5),(5,8),(8,6),(6,2)$. And finally $(3,7),(7,3)$
Now the transitive closure of the relation Q is the minimal relation that contains all of the pairs in Q but also satisfies transitivity.
We are going to prove that this closure is precisely the relation where (x,y) are related if and only if ${x,y}$ is a subset of $\{ 1,9,4 \}$,$\{2,5,8,6\}$ or $\{3,7\}$.
To prove this it suffices to prove that the relations of this subset are required for transitivity to occur.
To see why think of the relations within your cycle as a directed cycle. Now see that directed cycles are strongly connected components and that they have a path from $y$ to $y$ for any vertex $y$. (which also satisfies reflexivity).
Therefore what you have is an equivalence relation.
Comment: OK, I got (1-9-4), (2-5-8-6) and (3-7) from the first *Q*. Why am I doing *Q2*? Based on my study materials, I should carry on up to *Q4*. Why do I need to do that?
Comment: uhm, Just look at the natural cycles that are formed. Once you extend them you will get that the relation inside those cycles is complete except for the reflexive cases.
Comment: I extended my question with the solution from my materials. Could you please take a look?
Comment: Thanks, I'm gonna read this a few more times to actually get it. Thanks :)
Comment: You can think of any relation as a directed graph where the edge (a,b) is an edge on the graph if (a,b) is an element in the relation. Then the transitive closure of the same vertex looks like the graph where (x,y) is connected if and only if (x,y) are connected, also (x,x) is an element if and only if x is inside a directed cycle inside the graph.


Como medir a performance e custos (processamento e memória) de um frontend?

Question: Estou trabalhando em um projeto que utiliza muito JavaScript (ecmascript-6, jQuery), Html5, CSS e gostaria de ter alguma forma de medir a performance, o consumo de processamento e  o consumo de memória RAM, para que, ao realizar alterações na forma de implementar, seja possível checar se melhorou ou piorou o desempenho da aplicação.
Notas:

Não estou perguntando sobre boas práticas de otimização recomendadas pelo Google, Yahoo, Mozilla, Amazon, etc. (unificação e e minificação JavaScript ou CSS, utilização de cache, otimização de imagens, gzip, etc.), pois isso está  satisfatoriamente resolvido.
Não estou considerando o tempo de download da página, está satisfatoriamente resolvido.
Uma forma para medir o consumo em memória RAM é o gerenciador de tarefas do Google Chrome, SHIFT + ESC, mas processamento não é mensurável adequadamente e não registra o histórico de consumo da memória RAM. Também não tenho referências de se estas medidas são confiáveis ou se não são.
Também tem o recurso Profiles do Google Chrome DevTools (F12). Mas não achei prático para mensurar. Idem para o FireBug do Mozilla Firefox (F12).
As ferramentas para desenvolvedor do Microsoft Edge (F12) são interessantes, mas ainda não parece ser a solução.

Como posso medir de forma prática e eficiente estas variáveis? Preferencialmente algo que registre valores máximos consumidos de CPU e memória RAM.
Para ilustrar: em PHP utilizo o WebGrind para realizar estas análises. Gostaria muito de encontrar algo similar em JavaScript.
Answer: No Firefox você pode usar a extensão Firebug.
No Chrome, basta apertar F12.
Ainda sobre o Chrome, dẽ uma olhada nas abas:

Network: para ver coisas relacionadas a rede
Timeline: ver qual tipo de operação o browser está fazendo. Ex: executando um script (Scripting) ou pintando a tela (Painting)
Profile: também mostra uso de CPU, além do uso de memória

Como tem muitas opções, sugiro dar uma olhada aqui:
https://developers.google.com/web/tools/chrome-devtools/


How to fix ClassPath in Netbeans on Windows

Question: I just restarted java for university and I have a pretty basic program that I need to code. The thing is every time I try to run it, I get a NoClassDefFoundError as follow:
<code>run:
java.lang.NoClassDefFoundError: log120/devoir1/LOG120Devoir1
Caused by: java.lang.ClassNotFoundException: log120.devoir1.LOG120Devoir1
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: log120.devoir1.LOG120Devoir1.  Program will exit.
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
</code>
I am using Netbeans 7.0.1 since it was the IDE I was using a couple of years ago to code java. I googled the error and found something about the class path but all the example I found were for LINUX based OS so I am kinda lost as to how to set it right on Windows.
The class does exist, the program did compile, from what I understand this error comes when the JVM tries to run the code and does not find the class.
Anyone can help me with finding the ClassPath on Netbeans 7.0.1 or if it is not the ClassPath finding why this error keeps popping up?
Comment: Just FYI, the your text doesn't match the exception, they're actually different exceptions, with different causes/fixes. How are you trying to run the code, from within the IDE, or the command line?
Comment: IDE, i press the play button and I get the error shown.
Answer: If you're trying to run your own code, setting your classpath is probably barking up the wrong tree.  Netbeans should be including your code automatically on the classpath when it tries to run it.
Please describe how you have your code laid out within your project (eg do you have LOG120Devoir1.java in a log120/devoir1 directory?) as well as how you told netbeans that you wanted to run that class as your main method.
Comment: the .java are under LOG120-Devoir1\src\log120\devoir1. Netbeans made these repertories when i created the java application. When I go in properties => Run => main classes, it says there are no classes to be found. All the classes have the main function (they were made by the IDE) but nothing is running and I am getting the exception


Difference between confidence intervals and prediction intervals

Question: For a prediction interval in linear regression you still use $\hat{E}[Y|x] = \hat{\beta_0}+\hat{\beta}_{1}x$ to generate the interval. You also use this to generate a confidence interval of $E[Y|x_0]$. What's the difference between the two?
Comment: $\hat{E}[Y|x] = \hat{\beta_0}+\hat{\beta}_{1}x$ doesn't "generate the interval".
Comment: I do not see a reason for the divergence between the two methods in any of the answers above. Regression results are typically estimated based upon parametric Student's t distribution parameters and typically regression, especially from poorly matched to the data regression models, lead to residuals that are not studentized, e.g., skewed but especially with heavy tails typically (if not always) making the parametric measures of data dispersion larger than their corresponding anticipated measured quantiles. A rule of thumb I have found useful: If I see residuals with outliers, long tails, and u
Comment: Related : [Obtaining a formula for prediction limits in a linear model](http://stats.stackexchange.com/q/9131/17230).
Answer: Your question isn't quite correct. A confidence interval gives a range for $\text{E}[y \mid x]$, as you say. A prediction interval gives a range for $y$ itself. Naturally, our best guess for $y$ is $\text{E}[y \mid x]$, so the intervals will both be centered around the same value, $x\hat{\beta}$.
As @Greg says, the standard errors are going to be different---we guess the expected value of $\text{E}[y \mid x]$ more precisely than we estimate $y$ itself. Estimating $y$ requires including the variance that comes from the true error term.
To illustrate the difference, imagine that we could get perfect estimates of our $\beta$ coefficients. Then, our estimate of $\text{E}[y \mid x]$ would be perfect. But we still wouldn't be sure what $y$ itself was because there is a true error term that we need to consider. Our confidence "interval" would just be a point because we estimate $\text{E}[y \mid x]$ exactly right, but our prediction interval would be wider because we take the true error term into account.
Hence, a prediction interval will be wider than a confidence interval.
Comment: I feel  like this should make sense but when I read it.. it still doesn't.
Answer: One is a prediction of a future observation, and the other is a predicted mean response. I will give a more detailed answer to hopefully explain the difference and where it comes from, as well as how this difference manifests itself in wider intervals for prediction than for confidence.
This example might illustrate the difference between confidence and prediction intervals: suppose we have a regression model that predicts the price of houses based on number of bedrooms, size, etc. There are two kinds of predictions we can make for a given $x_0$:

We can predict the price for a specific new house that comes on the market with characteristics $x_0$ ("what is the predicted price for this house $x_0$?"). Its true price will be $$y = x_0^T\beta+\epsilon$$. Since $E(\epsilon)=0$, the predicted price will be $$\hat{y} = x_0^T\hat{\beta}$$ In assessing the variance of this prediction, we need to include our uncertainty about $\hat{\beta}$, as well as our uncertainty about our prediction (the error of our prediction) and so must include the variance of $\epsilon$ (the error of our prediction). This is typically called a prediction of a future value.
We can also predict the average price of a house with characteristics $x_0$ ("what would be the average price for a house with characteristics $x_0$?"). The point estimate is still $$\hat{y} = x_0^T\hat{\beta}$$, but now only the variance in $\hat{\beta}$ needs to be accounted for. This is typically called prediction of the mean response.

Most times, what we really want is the first case. We know that $$var(x_0^T\hat{\beta}) = x_0^T(X^TX)^{-1}x_0\sigma^2$$
This is the variance for our mean response (case 2). But, for a prediction of a future observation (case 1), recall that we need the variance of $x_0^T\hat{\beta} + \epsilon$; $\epsilon$ has variance $\sigma^2$ and is assumed to be independent of $\hat{\beta}$. Using some simple algebra, this results in the following confidence intervals:

CI for a single future response for $x_0$: $$\hat{y}_0\pm t_{n-p}^{(\alpha/2)}\hat{\sigma}\sqrt{x_0^T(X^TX)^{-1}x_0 + 1}$$
CI for the mean response given $x_0$: $$\hat{y}_0\pm t_{n-p}^{(\alpha/2)}\hat{\sigma}\sqrt{x_0^T(X^TX)^{-1}x_0}$$

Where $t_{n-p}^{\alpha/2}$ is a t-statistic with $n-p$ degrees of freedom at the $\alpha/2$ quantile.
Hopefully this makes it a bit clearer why the prediction interval is always wider, and what the underlying difference between the two intervals is. This example was adapted from Faraway, Linear Models with R, Sec. 4.1.
Comment: It is nice to see an old thread considerably improved by a clear and thoughtful response.  Welcome to our site!
Comment: If I am understanding your question @Pugl, the formal difference here is that epsilon is only associated with a prediction for an individual observation, not with prediction of the mean response.
Comment:  is the residual.
Comment: Shouldn't this be

...x0 + 1/n +1  (for the prediction interval (1)), and
...x0 + 1/n (for the confidence interval (2)_

http://www2.stat.duke.edu/~tjl13/s101/slides/unit6lec3H.pdf http://www.real-statistics.com/regression/confidence-and-prediction-intervals/
Comment: @jpgard Is the formal difference hence just the result of E(eps) = 0?
Comment: That is helpful thanks @jpgard
Comment: Hmm I think there might be an issue with the variance for (1). You state that we need the variance for $x_0^T\hat{\beta} + \epsilon$. Shouldn't there be a residual component here as well?
Comment: I think for the standard error, you need to divide it by $\sqrt{n}$ before multiply with critical value.
Comment: What is the meaning of $\hat{\sigma}$ ?
Comment: I really wish Faraway would have explicitly labeled #1 as a prediction interval, and #2 as a confidence interval. Would've cleared up so much for me. Thank you for typing this up, but Faraway caused me some confusion on this point, so I can't upvote.
Comment: @FinncentPrice I believe ̂ is the standard deviation of the residuals.
Comment: @AdrianKeister Just to be sure, is it true that, the `1.` of the end of this answer is prediction interval, and the `2.` is confidence interval?
Comment: @Basj That's correct. Prediction intervals are always slightly wider than corresponding confidence intervals.
Answer: The difference between a prediction interval and a confidence interval is the standard error.
The standard error for a confidence interval on the mean takes into account the uncertainty due to sampling.  The line you computed from your sample will be different from the line that would have been computed if you had the entire population, the standard error takes this uncertainty into account.
The standard error for a prediction interval on an individual observation takes into account the uncertainty due to sampling like above, but also takes into account the variability of the individuals around the predicted mean.  The standard error for the prediction interval will be wider than for the confidence interval and hence the prediction interval will be wider than the confidence interval.
Answer: I found the following explanation helpful:

Confidence intervals tell you about how well you have determined the mean. Assume that the data really are randomly sampled from a
  Gaussian distribution. If you do this many times, and calculate a
  confidence interval of the mean from each sample, you'd expect about
  95 % of those intervals to include  the true value of the population
  mean. The key point is that the confidence interval tells you about
  the likely location of the true population parameter.
Prediction intervals tell you where you can expect to see the next data point sampled. Assume that the data really are randomly sampled
  from a Gaussian distribution. Collect a sample of data and calculate a
  prediction interval. Then sample one more value from the population.
  If you do this many times, you'd expect that next value to lie within
  that prediction interval in 95% of the samples.The key point is that
  the prediction interval tells you about the distribution of values,
  not the uncertainty in determining the population mean.
Prediction intervals must account for both the uncertainty in knowing
  the value of the population mean, plus data scatter. So a prediction
  interval is always wider than a confidence interval.

Source: http://www.graphpad.com/support/faqid/1506/
Comment: @tel: Obviously the variance
Comment: What the heck is meant by "data scatter" here?
Comment: So, when does the prediction interval converge to the narrower confidence interval? When there is no noise in the data (perfect correlation)?
Answer: Short answer:
A prediction interval is an interval associated with a random variable yet to be observed (forecasting).
A confidence interval is an interval associated with a parameter and is a frequentist concept.
Check full answer here from Rob Hyndman, the creator of forecast package in R.
Answer: This answer is for those readers who could not fully understand the previous answers. Let's discuss a specific example. Suppose you try to predict the people's weight from their height, sex (male, female) and diet (standard, low carb, vegetarian). Currently, there are more than 8 billion people on Earth. Of course, you can find many thousands of people having the same height and other two parameters but different weight. Their weights differ wildly because some of them have obesity and others may suffer from starvation. Most of those people will be somewhere in the middle.
One task is to predict the average weight of all the people having the same values of all three explanatory variables. Here we use the confidence interval. Another problem is to forecast the weight of some specific person. And we don't know the living circumstances of that individual. Here the prediction interval must be used. It is centered around the same point, but it must be much wider than the confidence interval.
Comment: In short.
Confidence Interval - A range for the expected AVERAGE
Prediction Interval - A range for a SINGLE DATA POINT
Comment: Don't you think you can explain both with just the first example: confidence interval is the interval for true mean to lie within; whilst prediction interval is for all possible outcomes? Which is obviously wider.
Comment: Thanks for the good example. So in your example for the first case, we have an uncertainty because we still only have a sample out of the entire population, so is the uncertainty we have here between the estimated mean and the true mean of the population? While in the second case, we have sampling variance as well as the residual error?
Comment: I'm not sure about your second case. Which interval to use, depends on the goal.


"Structure->Block" showing when permission is not given to user

Question: I have user role 'Admin', who can see 'taxonomy terms' under 'Structure', I have given same permission but it is showing 'Block' and 'Views' too.
Is there any workaround in Drupal 8?

Any help would be great. Thanks
Answer: You've probably given them the Administer blocks and Administer views permission as well. Withdraw these permissions and the links should disappear.

“Structure->Block” showing when permission is not given to user


How to check if a date is into a range of dates with a specific repetition?

Question: I'd like to create a simple pills reminder iOS application (let's leave notifications aside for the moment).
I want to create a single DB record for a pill that has repetitions and check if a specific day intersects date "generated" by the repetition.
Example:
I set a pills period that starts from April 12 and ends April 20, with repetition every 2 days , at 3.00 pm.
So this pills is valid for this dates :

April 12 at 3.00pm
April 14 at 3.00pm
April 16 at 3.00pm
April 18 at 3.00pm
April 20 at 3.00pm

Questions:

Which type of data can describe the information "Every 2 days"? NSDateInterval would be a good solution ?
How can i verify that a specific day agrees with my repetition scheme ? (i.e. Check if April 13 is a valid date for the previous example and get "NO" as answer)
Answer: Here is an example class which should meet your criteria:
main.m
<code>#import <Foundation/Foundation.h>
#import "DateChecker.h"

int main(int argc, const char * argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Specify a period in days
    NSInteger period = 2;

    // Set the start/end/current days.  These can be retrieved from a database or elsewhere
    NSDate *startDate = [NSDate dateWithString:@"2012-04-12 00:00:00 +0000"];
    NSDate *endDate = [NSDate dateWithString:@"2012-04-20 00:00:00 +0000"];
    NSDate *currentDate = [NSDate dateWithString:@"2012-04-14 00:00:00 +0000"];

    // Actually do the checking.  This could alternatively be offloaded to a function in DateChecker
    if([DateChecker date:currentDate isBetweenDate:startDate andDate:endDate])
    {
        if([DateChecker date:currentDate fallsOnStartDate:startDate withInterval:period])
        {
            NSLog(@"The date %@ falls in the specified date period & is on the interval date.", currentDate);
        }
        else
        {
            NSLog(@"The date %@ falls in the specified date period & is NOT on the interval date.", currentDate);
        }
    }
    else
    {
        NSLog(@"The date %@ does not fall in the specified date period.", currentDate);
    }

    [pool release];

    return 0;
}
</code>
DateChecker.h
<code>#import <Foundation/Foundation.h>

@interface DateChecker : NSObject
{
}
+ (BOOL)date:(NSDate*)date fallsOnStartDate:(NSDate*)beginDate withInterval:(NSInteger)daysInterval;
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate;

@end
</code>
DateChecker.m
<code>#import "DateChecker.h"

@implementation DateChecker

+ (BOOL)date:(NSDate*)date fallsOnStartDate:(NSDate*)beginDate withInterval:(NSInteger)daysInterval
{
    NSDateComponents *components;
    NSInteger days;

    // Get the number of days since the start date
    components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit fromDate: beginDate toDate: date options: 0];
    days = [components day];

    // If the number of days passed falls on the interval, then retrun YES
    if(days % daysInterval == 0)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;

    if ([date compare:endDate] == NSOrderedDescending)
        return NO;

    return YES;
}

@end
</code>
That should give you an idea on how to write a class that can handle your requirements.  I ran this as a command line app and it seemed to work alright.  The function
<code>+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
</code>
was graciously obtained from How to Check if an NSDate occurs between two other NSDates.


Outlook 365 (pywin32) - cannot access the body of the e-mails

Question: Since we moved to the Office Semi-Annual Enterprise Channel, version 1908, build 11929.20838, I cannot access the body or even the sender of the e-mails anymore via MAPI.
Python version: tried   3.6.8 32-bit,  3.6.8 64-bit  and  3.8.2 32-bit.
Pywin32 version: tried  228  and  227
I am wondering why this is happening, since it still works fine on previous versions of Office (not Enterprise).
=== Code example ===
<code>import win32com.client

def checkOutlookInbox():
    account = 'firstname.lastname@example.com'
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    inbox = outlook.Folders(account).Folders("Inbox")
    messages = inbox.Items

    for message in messages:
        msg = message.body
        sender = message.Sender
        print(sender)
        print(msg)
</code>
=== Output (error) ===
File "C:\Python36-32Bit\lib\site-packages\win32com\client\dynamic.py", line 516, in getattr
ret = self.oleobj.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147467259, 'Unspecified error', None, None)
===
Any ideas why this is happening on this specific Office version?
Answer: Firstly, you are not using MAPI - this is Outlook Object Model.
Secondly, are you ure you only have mail item objects in the Inbox, and not report items (NDRs) or meeting requests/updates?
Comment: You are right, it's OOM. Not MAPI. By the way, yes, I am sure I have only e-mail objects. The application is being used for over a year and as mentioned, it's still works on previous versions of Outlook (previous build and not "Enterprise" version) with the very same code.
Comment: Does it work if you avoid touching the Sender and Body properties and only access a property like Subject?
Comment: Yes, it does. Actually I still can access the Subject, among a few properties of e-mails. But the Sender and Body provide the said error. Except when I run the code over a previous build. Then I am able to access all properties.
Comment: Then this is an indication that you are running into the security patch - you need to either use Extended MAPI (C++ or Delphi)  or Redemption (any language) or ensure that the client machine has up-to-date antivirus app installed.


Azure - how to route traffic away from a server during an update

Question: What's the best practice for routing traffic away from an Azure website / role when you want to run an update.
Would you simply route away traffic using the Traffic Manager and wait the 5 minutes or however long you have the DNS TTL set to?
That would work fine but it adds a lot of delay to deployments. Is there a better/faster way to route traffic away during a deployment?
Answer: You need to use what is called "Staged Deployment" in Azure.
When you create a site/role on Azure, you're actually using a production environment to host your site/roles in, this production environment is live and is serving people in real time, thus you can't actually do testing and bug fixing on it.
The Staged Deployment solution, you can create a replica of your production environment, this environment is live but it is not being used to serve people on the internet, so you may use it for your testing and bug fixing purposes.
Once your testing and fixing is done, you can "swap" both environment by a click of a button, where the production will become a staged environment, and the staged environment will become a production.
The benefit of this approach is that

You will be avoiding all downtime for your end users when moving from testing to production.
You can swap back the environments back to the way they were in case you found a problem in your new sites or app.
You will have an environment that matches your production for your testing purposes that can be later used as a production site.

More info can be found here on how to use and activate the feature: http://azure.microsoft.com/en-us/documentation/articles/web-sites-staged-publishing/
Hope this helps.


How to get String[] String's to a seperate String?

Question: I have a list of URL's added to a String[] with this.
try {
    Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
    List<String> thumbLinks = new ArrayList<String>();
    for(Element thumb : thumbs) {
        thumbLinks.add(thumb.attr("src"));
    }
    for(String thumb : thumbLinks) {
        System.out.println(thumbLinks.get(1));
    }
}

How can i add each String that is loaded into a separate String?
EDIT:
SO as the images are loaded into the thumbLinks list. I want to get each link to a seperate
String url1;
String url2;
String url3;

Comment: Separate `String`s called what?
Comment: Can you give an example of what you're trying to achieve?
Answer: If you expect a fixed number of items, and you have a fixed number of String variables, you have little choice but something like:
String url0 = thumbLinks.get(0);
String url1 = thumbLinks.get(1);
...
String url5 = thumbLinks.get(5);

Well, you could do something grim with reflection, I guess.  But probably best to avoid this at all.
Comment: So you think this is  a bad idea?
Comment: @coder: Yes, probably.  Why would you want to do this, when it would be simpler to use arrays or containers?
Comment: This is the syntac error i get when i use thumbLinks[0]  The type of the expression must be an array type but it resolved to List
Comment: @coder: What version of Java are you using?  You may need to use `String url0 = thumbLinks.get(0);`.
Comment: I don't think this is possible even *with* reflection.
Comment: @Null: It's possible if the receiving variables are member variables of a class.
Comment: @Oli How can I do that? I can't find anything that adds fields to a class.
Comment: ohhhh! Got it..Whats dangerous about the way i am doing it now?
Comment: @coder: There's nothing dangerous.  There just doesn't seem to be a good reason to have a bunch of separate variables, rather than an array.  An array or container is much more convenient (you can't iterate over a bunch of variables, for instance).
Comment: Oh check out the answer below at the bottom. Seems to be a good idea also.
Comment: @coder: Both of the other answers are just transferring the contents of your `List` into an array.
Comment: When i use your code inside my last for() it returns the urls like 3 seperate times?
Comment: @coder: I don't understand what you mean.  If you put my code inside your loop, then of course it will be executed multiple times.
Comment: It shouldnt matter though or be to much of a waste
Answer: take a String array of the size of your ArrayList object - thumbLinks in your case. take an int variable and initialize it with zero. I have made some changes in your code just have a look:

try{
        Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
        List<String> thumbLinks = new ArrayList<String>();
        for(Element thumb : thumbs) {
            thumbLinks.add(thumb.attr("src"));
        }

        String[] urls = new String[thumbLinks.size()];
        int x =0;
        for(String thumb : thumbLinks) {
            urls[x++] = thumb;
        }
    }catch(Excpetion e){

    }

use urls for your purpose
Answer: ArrayList has method public <T> T[] toArray(T[] a) that you can call as described below on thumbLinks:
String[] url = new String[thumbLinks.size()];
url = thumbLinks.toArray(url);

Then, you will have an array of strings that you can access like this:
System.out.println(url[0]);
System.out.println(url[1]);
System.out.println(url[2]);
// etc, etc. all the say up to thumbLinks.size() - 1

While this is not exactly what you've asked for, it's pretty much the same thing. If you really want variables named url1, url2, url3, etc., you're likely going to have to code it line by line for every element in the list.
Just as an aside, you don't need an array to access the elements of your thumbLinks list directly. You can already do this:
System.out.println(thumbLinks.get(0));
System.out.println(thumbLinks.get(1));
System.out.println(thumbLinks.get(2));
// etc. all the way up to thumbLinks.size() - 1

Comment: IS there a way to add a String for each element it finds?
Comment: Referencing the above code, every element in the `url` array is a variable of type `String` and the `toArray` method will create an element for every element in the `thumbLinks` list. Is that what you're asking?
Comment: @coder_For_Life22 with all this being said, I'm not sure there is much of a reason to create an array. You already have the `thumbLinks` list where you can reference any element with `thumbLinks.get(x)` where `x` is any integer from 0 to `thumbLinks.size() - 1`


How big should be a sample size?

Question: Question:
Assuming the population standard deviation σ = 3, how large should a sample be to estimate the population mean µ with a margin of error not exceeding 0.5?
My answer:
SE<= 0.5=3/√n ---> n=36
But probably the correct answer is:

So, can anyone explain more about the second solution?
Comment: Hint: consider where the "$1.96$" came in and notice that your answer doesn't use this factor at all.  Why not?
Comment: The difference come from the explanation of "a margin of error". You explain the a margin of error as SE (standard error). The second explanation of a margin of error is the half of the width of the 95% CI (confidence interval) which is 1.96*SE.
Answer: A 95% confidence interval for normal population $\mu,$ where the SD is $\sigma,$
based on a sample of size $n$ is of the form $\bar X \pm 1.96\sigma/\sqrt{n}.$
As in @statistician's Comment, the 'standard error' of $\bar X$ is $SD(\bar X) = \sigma/\sqrt{n}.$
And the 'margin of error' of the confidence interval is $\Delta = 1.96\sigma/\sqrt{n}.$ You know $\sigma = 3$ and you want to find $n$ so that $\Delta = 0.5$ (or perhaps a bit smaller).
So solve  $\Delta = 1.96\sigma/\sqrt{n}$ for $n$ in terms of $\Delta$ and $\sigma.$ That gives the equation $n = (1.96\sigma/\Delta)^2,$ to which you
refer in your question. So $n \approx 11.76^2 = 138.4.$ Rounding up to
the nearest integer, you get $n = 139$ as the sample size that gives $\Delta$ just a bit smaller than the required 0.5.
Note: Your solution $n = 36$ gives SE$ =3/\sqrt{36} = 0.5,$ equivalent to $\Delta = 1.96(0.5),$ but not to $\Delta = 0.5.$
Roughly speaking, to cut $\Delta$ in half requires a four-fold increase in $n,$
and dividing by 1.96 is almost cutting $\Delta$ in half, which explains why
$4(36) = 144$ is not far from the correct answer $n = 139.$
Comment: Fair point, but in practice that assumption doesn't always hold, yet people will use this approach to estimate the number of samples required (e.g. in simulation).  Just wanted the caveat here for practitioners.  Thanks for clarifying.
Comment: (+1), I just want to add that this is an estimation only.  It is entirely possible to collect 139 samples (or even more) and still not it your intended margin of error.
Comment: Because $\sigma$ is known, the width of the CI is determined by $\alpha$ and $n,$ but of course not 100% of the CIs will cover $\mu.$

How big should be a sample size?