Pinch Zoom ListView Android

Question: I'm trying to implement a pinch to zoom in a listview on Android and I'm facing a problem when I click and drag the zoomed list view.
First, here's the code:
public class ScaleListView extends ListView {

private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
private float x = 0;
private float y = 0;
private float startx = 0;
private float starty = 0;
private boolean canClick = true;
private float xtranslation = 0;

public ScaleListView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        startx = ev.getX();
        starty = ev.getY();
    }

    if (ev.getPointerCount() > 1) {
        y = ev.getY();
        x = ev.getX();
    } else if (ev.getAction() == MotionEvent.ACTION_UP) {
        canClick = (ev.getX() - startx) == 0 && (ev.getY() - starty) == 0 && mScaleFactor == 1;
    } else if(ev.getAction() == MotionEvent.ACTION_MOVE){
        xtranslation = ev.getX() - startx;
    }
    mScaleDetector.onTouchEvent(ev);
    return super.onTouchEvent(ev);
}
@Override
public void onDraw(Canvas canvas) {
    canvas.scale(mScaleFactor, mScaleFactor, x , y);
    canvas.translate(xtranslation, 0);
    super.onDraw(canvas);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        canClick = false;
        mScaleFactor *= detector.getScaleFactor();

        // Don't let the object get too small or too large.
        mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));

        if (mScaleFactor <= 1) {
            mScaleFactor = 1;
            canClick = true;
        }

        xPos = ScaleListView.this.getWidth() - detector.getFocusX();

        ScaleListView.this.invalidate();
        return true;
    }
}
public boolean canClick(){
    return canClick;
}

The problem is with the translation. It goes infinite, I can drag it horizontally and take the list view off the viewport. So I can't face how to put an edge to the translation...
Thanks for any help.
Comment: have you found  the solution?
Comment: No. I've tried to create some mathematical formula but it didn't work.
Comment: is it possble to add the above listview inside ascrollview ? i ink this may create problem
Comment: I'm sorry. I don't have access to the code anymore
Comment: i think it will be use to you [link for pinch zoom of listview][1]

  [1]: http://stackoverflow.com/questions/8196503/pinch-zoom-on-a-listview
Comment: And what are the semantics of a pinch-zoomed list?!
Comment: Well... My client complained their users have vision problems. Android offers native accessibility for this nowadays, but not at the time I've posted this (not that I remember though). And I don't even remember what I did to solve my client's issue. The only thing I remember is that I could not make this work the way I wanted
Answer: I just put together a working class for this.
Let me know if it works for you.
https://github.com/Xjasz/AndroidZoomableViewGroup
Comment: I'm sorry, but I don't have access to the code anymore. Unfortunately I don't even remember what I did with this feature request. :( I'll accept your answer since it seems to be the best solution.
Comment: Thats OK I just wanted to post this somewhere.  I wasted a day just searching for one that wasn't to broken to manage.
Answer: follwing code restricts my textview to screens edges.. Hope this will help you in your listview ..I had done this code on ACTION:Move
layoutParams.leftMargin = X - _xDelta;
                    layoutParams.topMargin = Y - _yDelta;
                    if (layoutParams.leftMargin < 0) {
                        layoutParams.leftMargin = 20;
                    } else if (layoutParams.leftMargin > mainimage.getWidth()) {
                        layoutParams.leftMargin = mainimage.getWidth() - 20;
                    }
                    if (layoutParams.topMargin < 0) {
                        layoutParams.topMargin = 20;
                    } else if (layoutParams.topMargin > mainimage.getHeight() - 100) {
                        text.setText(text2.getText().toString());
                        layoutParams.topMargin = mainimage.getHeight() - 90
                                - text.getHeight();
                        // layoutParams.leftMargin = 20;
                    }

                    text.setX(layoutParams.leftMargin);
                    text.setY(layoutParams.topMargin);

                    v.setLayoutParams(text.getLayoutParams());

Pinch Zoom ListView Android


The number of times one needs to sample with replacement to cover a fraction P of a set

Question: Take the expression $(1-(1-\frac{1}{n})^x)$, which is the expected fraction of elements one samples from a set of $n$ elements, sampling with replacement (and uniform probability) $x$ times.
Provided some $n$, how do we analytically solve for $x$ s.t. $(1-(1-\frac{1}{n})^x) \geq P$?  It appears that $\frac{x}{n}$ converges to a fixed value as $n \to \inf$.  Is this true?  If so, how do we find it without relying on numerical methods?
Comment: Your expression $(1-(1-\frac{1}{n})^x)$ is always less than $1$, so how can this be the expected number of unique elements?? Also, to even have the slightest nonzero chance of covering a portion $P$ with $x$ samples one needs $\frac xn\geq P$, and this requires $x\to\infty$ as $n\to\infty$. So obviously $x$ cannot.
Comment: @Marc von Leeuwen Sorry, I meant that the expression was the fraction of a set of n elements covered after sampling with replacement x times.
Answer: The inequality can be rewritten as
$$\left(1-\frac{1}{n}\right)^x\le 1-P.$$
We first solve the equation
$$\left(1-\frac{1}{n}\right)^t= 1-P.$$
Take the (natural) logarithm of both sides.
We get
$$t\log\left(1-\frac{1}{n}\right)=\log(1-P).$$
Thus
$$t=\frac{\log(1-P)}{\log\left(1-\frac{1}{n}\right)}.$$
Presumably we want $x$ to be an integer. The smallest integer $x$ for which our inequality holds is $\lceil t\rceil$.
It is clear that $x\to \infty$ as $n\to\infty$. However, something interesting happens if we look at $\frac{x}{n}$. We look instead at the closely related $\frac{t}{n}$, which has the same limit. We have
$$\frac{t}{n}=\frac{\log(1-P)}{n\log\left(1-\frac{1}{n}\right)}.$$
Note that the denominator $n\log\left(1-\frac{1}{n}\right)$ is equal to
$\log\left(\left(1-\frac{1}{n}\right)^n\right)$. But $(1-1/n)^n\to e^{-1}$ as $n\to\infty$, so the denominator approaches $-1$. It follows that as $n\to\infty$, $\dfrac{t}{n}$ (and therefore $\dfrac{x}{n}$) approaches $-\log(1-P)$.
Comment: Nicolas Sorry, I meant that the expression was the fraction of a set of n elements covered after sampling with replacement x times.
Answer: We have
\begin{align*}
  1 - \left(1 - \frac 1n\right)^x \ge P\\
\iff \left(1 - \frac 1n\right)^x \le 1-P\\
\iff x \cdot \log\left(1- \frac 1n\right) \le \log(1-P)\\
\iff x \ge \frac{\log(1-P)}{\log(1 - \frac 1n)}
\end{align*}
So the smallest such $x$ is $x(n) = \left\lceil\frac{\log(1-P)}{\log(1 - \frac 1n)}\right\rceil$ and $x(n) \to \infty$ as $n \to \infty$ (as $\log$ is continuous and $\log 1 = 0$).


Number of observations used for ARIMA modeling

Question: Our professor keeps on writing in his slides that when you test different ARIMA models on your time series, one always has to keep T fixed.
I assume he is talking about fitting your model using the same number of observations. If you try a model with a higher lag, you loose one observation to fit the data on. Is this correct?
Is this why he writes restrict your sample? We have 214 observations, should I for example to be on the safe side only use 205 observations? And how does Eviews know to always use the same number of obersations?
Ref screenshot:

Thanks in advance.
Answer: When you test ARIMA models with different number of lags, you must make sure you always have the same data available to calculate the coefficients. If you don't specify the sample to be used in Eviews, you will use one observation less for estimating an AR(5) model than for estimating an AR(4) model, and hence the coefficients, and more important the significance of your coefficients, are not calculated on the same number of observations.
This should be avoided, so think first about the maximum number of lags you want to include in  the model and set the sample size accordingly.


MVC3 - How to Exclude the hidden columns of the Dhtmlxgrid in the excel file

Question: Is there anyway, to exclude the hidden columns of the DhtmlxGrid in the excel file?
Right now when I do export to excel, it also includes the column which are hidden in the excel. Please suggest.
<code>MVC3
in View:
on a button click my code:

_grid.toExcel('@Url.Content("~/Shared/ExportGridToExcel?TableName")' +'Doc');

in Controller:

 public ActionResult ExportGridToExcel(string TableName)
        {
            var generator = new ExcelWriter();
            var xml = this.Request.Form["grid_xml"];
            xml = this.Server.UrlDecode(xml);
            var stream = generator.Generate(xml);
            return File(stream.ToArray(), generator.ContentType, TableName + ".xls");
        }
</code>
Answer: Find this method and replace this
<code>    public ActionResult GenerateExcel()
    {
        var generator = new ExcelWriter();
        var xml = this.Request.Form["grid_xml"];
        xml = this.Server.UrlDecode(xml);
        var xmlObj = XDocument.Parse(xml);
        foreach (var x in xmlObj.Descendants("columns").ElementAt(0).Descendants("column"))
        {
            var w = x.Attribute("width").Value;
            if (Convert.ToString(w).Equals("0")) { x.SetAttributeValue("hidden", "true"); }
        }
        xml = xmlObj.ToString();
        var stream = generator.Generate(xml);
        return File(stream.ToArray(), generator.ContentType, "grid.xlsx");
    }
</code>
Dont forget to mark this as answer if it works
Answer: Use setColumnHidden api to hide column before export call, and show the column after it. Hidden columns do not included in the export result.


Installing/Linking libwebsockets library in AWS Linux for mosquitto MQTT

Question: Following the AWS Guide: https://aws.amazon.com/blogs/iot/how-to-bridge-mosquitto-mqtt-broker-to-aws-iot/ and I got to the step that has me install mosquitto.
//Update the list of repositories with one containing Mosquitto
sudo wget http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7/home:oojah:mqtt.repo -O /etc/yum.repos.d/mqtt.repo
//Install Mosquitto broker and Mosquitto command line tools
sudo yum install mosquitto mosquitto-clients
However, the guide is so outdated that it does not mention anything about the missing libwebsockets library. I've spent roughly 4-5 hours on searching for an answer on how to manually install/link/setup the library but I have not been able to make anything work.
(1) Tried this
git clone https://github.com/warmcat/libwebsockets.git
cd libwebsockets
mkdir build
cd build
cmake .. -DCMAKE_C_COMPILER=/usr/bin/gcc
make
sudo make install
But yea that didn't work because CMAKE throws all kinds of errors like
CMake Error at /usr/share/cmake/Modules/CMakeDetermineSystem.cmake:99 (message):   Could not find toolchain file: /tmp/mytoolchainfile
Call Stack (most recent call first):
CMakeLists.txt:131 (project)
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_C_COMPILER_ENV_VAR
CMake Error: Could not find cmake module file: /tmp/libwebsockets/build/CMakeFiles/184.108.40.206/CMakeCCompiler.cmake
-- Configuring incomplete, errors occurred!
So I tried to set the CMAKE_C_COMPILER path to /usr/bin/gcc, which is where the compiler is installed and that didn't do anything either. In all honesty, I'm not super familiar with Linux, I'm just trying to make do the best I can. I could really use some guidance on how best to get library installed and linked into Linux. I do believe AWS runs a red-hat version of linux.
Thanks for your time!
Answer: I had this working using aws linux 2
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm -P /tmp
sudo yum install -y /tmp/epel-release-latest-7.noarch.rpm
sudo yum install libwebsockets
sudo yum install mosquitto mosquitto-clients


How can I turn this into an AngularJs Directive?

Question: I have a select list that I am populating with ng-options. It also has a "default" selected item that kind of acts like a "placeholder" since  lists don't have an actual "placeholder" attribute.
However, what I wanted to accomplish was to have only that very first  (the placeholder value) have a lighter font color than all the rest of the options in the select list very similar to that of the lighter font a placeholder attribute in a text input has.
I got this to work but without writing a Directive. I'd like to port this code over to a Directive so that it more conforms to the "Angular Way" and is more reusable across my site.
Any help would be really appreciated! See below for code:
The HTML:
<select
    ng-model="priority"
    id="priority" name="priority"
    class="span7"
    required
    ng-options="p.Description for p in priorities"
    ng-class="appliedClass()">

    <option value="" selected>select priority</option>

</select>

The CSS:
.select-placeholder {
    color: #999;
}

The JS:
    /*
        Watches the 'priority' select list for changes
    */
    $scope.$watch('priority', function(value) {

        // value of the <option> element from the select list
        var selectedValue = value;

        // applies the 'select-placeholder' css class to ng-class
        // if the selected item is the default (placeholder) item.
        $scope.appliedClass = function() {

            if (selectedValue === undefined) {
                return 'select-placeholder';

            }

        };

    });

Comment: its better you give a try first using angular documentation http://docs.angularjs.org/guide/directive and if you have some problem the ask the problem again
Comment: Anybody else care to answer the question?
Answer: One option if the user really has to enter a value would be to add the required html5 attribute and style based on the :invalid rule:
/* style based on invalid */
select:invalid { color: red }

/* so drop-down items don't inherit color */
select:invalid option { color: black; }

html:
<select required>

You could do your styling all in css based on value, but the value attribute isn't set when the value property changes:
/* style based on value */
select[value=""] {
    color: #aaa;
}

/* so drop-down items don't inherit color */
select option {
    color: black;
}

/* if you want the style in the drop-down list too */
select option:nth-child(1) {
    color: #aaa;
}

To fix that you could use jQuery to set the value attribute based on the value property (fiddle):
$('#priority').attr("value", $('#priority').val())
    .change(function() { $(this).attr("value", this.value); });

Or an angular directive (fiddle):
app.directive("setValueAttribute", function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            element.attr('value', element.val());
            element.on('change', function(e) {
                var that = angular.element(this);
                that.attr('value', that.val());
            });
        }
    };
});

Comment: Ah, the directive simply copies whatever the value property is to the value attribute.  The value property that contains what the user selected is not available as a css selector.  You could call the attribute "data-my-attribute" and use that in the css as an attribute selector if you wanted, or you could change the directive to add a css class if the value is empty and remove it if there is something there.
Comment: Wow! thanks so much for taking the time to explain it and demonstrate it so well! Take care!
Comment: Jason, I'm looking through it again, and it works great but I still don't quite understand how exactly. How does it know to set the "placeholder" value to gray defined in the css above it? Thx again!
Comment: `select[value=""]` sets the color to gray when the value attribute of the select is empty.  The option elements when the box is dropped down are separate but they inherit that so you need to make them black with another rule, then the third rule colors the first drop-down option using `nth-child`.
Comment: Thanks Jason, sorry I should have been more clear, I was referring to the Directive you wrote. The directive doesn't seem to check for an empty option value...how is this working exactly? Thanks again and I appreciate all the help.


Import function works in IDLE but not as an exe

Question: I'm trying to import data from .py files, but when I run my game as an exe (I used pyinstaller to make my game into an exe), It dosen't work. I dont get an error or anything, it just dosent import the data. The weird thing is that when running this from IDLE, it works perfectly fine.
def achivementcheck():
    f = open("simplesavedata.py", "w")
    f.write("achivements = " + str(achivements) + "\n")
    f.close()

def option_save():
    f = open("optiondata.py", "w")
    f.write("volume = " + str(volume))
    f.close

from simplesavedata import *
from optiondata import *

EDIT: My game code
import random
import pickle
import os
from just_playback import Playback
import sys
playback = Playback()

init(convert=True)

volume = 0
achivements = 0
achivename = 0

def achivementcheck():
    f = open("simplesavedata.py", "w")
    f.write("achivements = " + str(achivements) + "\n")
    f.write("achivename = " + str(achivename) + "\n")
    f.close()

def option_save():
    f = open("optiondata.py", "w")
    f.write("volume = " + str(volume))
    f.close

#load saved data
from simplesavedata import *
from optiondata import *

playback.load_file("music/titlescreen.mp3")
playback.play()
playback.loop_at_end(True)

name = input("What is your name? ")

if name == "test":
     print("Test achivement")
     achivements += 1
     achivename += 1
     achivementcheck():

print("achivements = ", achivements)
print(gotten achivename", achivename, "times")

Answer: Using the code below and using pyinstaller -F filename.py the executable seems to work perfectly.  Make sure you are actually calling your functions so the code executes before trying to import the newly created python files.
optiondata.json
{
    "achievement": 0,
    "volume": 0
}

import json

def get_achievements():
    with open("optiondata.json", "rt") as jsonfile:
        data = json.load(jsonfile)
        achievements = data["achievements"]
    return achievements

def save_achievements(value):
    with open("optiondata.json", "rt") as jsonfile:
        data = json.load(jsonfile)
    with open("optiodata.json", "wt") as jsonfile:
        data["achievements"] = value
        json.dump(jsonfile)

def save_volume(value):
    with open("optiondata.json", "rt") as jsonfile:
        data = json.load(jsonfile)
    with open("optiondata.json", "wt") as jsonfile:
        data["volume"] = value
        json.dump(jsonfile)

def get_volume():
    with open("optiondata.json", "rt") as jsonfile:
        data = json.load(jsonfile)
    return data['volume']

Comment: Mine dosent seem to work at all. In simplesavedata.py, I can see that achievements is set to 12, and yet running the game it says I have 0 achievements. Actually, the exe seems to work fine even if I delete simplesavedata.py
Comment: @user19901195  that is because the exe creates the `simplesavedata.py` in code so no matter what it will always create a new simplesavedata.py
Comment: @user19901195  I hope you understand that both your option_save and achivementcheck functions are completely overwriting whatever was in the files they are writing too. So after you run option_save()  `"achivements = " + str(achivements) + "\n"`  is the entire contents of simplesavedata.py
Comment: I do understand that. So how would I get the exe to not create `simplesavedata.py` inside of it?
Comment: @user19901195  I don't understand what you are asking.  Can you post the actual game code?
Comment: I edited my code into the original post
Comment: I still don't understand what the purpose of simplesavedata and optiondata is...
Comment: savedata is supposed to save the achievements that you've unlocked, and optiondata is supposed to save your settings (altough I dont have any settings or achievements at the moments)
Comment: It doesn't make any sense to save them in a .py file.  You are better off using a text file or a json file
Comment: How exactly would I do that?
Comment: @user19901195  I would show by integrating it into your code but you don't show how you are using the values in your example, so I don't really know how to work it in but I will try
Comment: @user19901195  see my updated answer.  That shows how you can get the achievement value, or save a new new one and the same with the volume value


Guessing number of colors of beads in an urn

Question: Motivation from cocktail bar
Every time when I order the cocktail "Latex and Prejudice" ("Латекс и предубеждение") in the Tesla bar in Saint Petersburg (Russia) the barkeeper selects by random a small interesting photo$^1$  and attaches it with a clamp to the cocktail glass. At the beginning I got always different pictures and started to collect them. The more cocktails I ordered the more often the motifs repeated. Finally, I had drunken so much that almost every time I had to ask for a different photo. I was wondering how many different pictures there are but due to drunkenness couldn't solve the problem by myself.

Mathematical form using urn model
Given is an urn with an unknown number of balls that have an unknown number of colors. It is assumed that every color has equal probability. From this urn in total $n$ balls with $m$ different colors were drawn, $k_i$ balls for color $i$ were sampled, i.e. $n=\sum_{i=1}^m k_i$. How many different colors $M$ are in the urn? Sampling with and without replacement is of interest.
Open questions
Some answers were already given. Now I am looking for either alternative answers or/and answers to the following more specific questions:

Let's only for the first question assume that we do not know if the balls were drawn with or without replacement. Is the maximum likelihood for drawing with replacement always higher than the maximum likelihood for drawing without replacement?

Is this answer helpful? If yes: Can we consider the calculated likelihoods as discrete probability distributions if they were be normalized (with support on integers in the range $(m,\infty)$)? What can we say about variance, standard error?

What can we say about variance, standard error of another answer?

Related problems
In this SE post the number of colors in the urn is also unknown but in the problem given here it is assumed that the colors have equal probability. Another SE post deals with lending books from a library that were already lent at an earlier time.
Annotation 2023
The bar was visited a lot of times before the war.

$\small{^1 \text{Because the site is accessible to minors,$\\$ the content of the photos is not discussed here.}}$
Comment: Hello, if a minor, like me, were to view this post on "adult content" and "cocktails", basically alcohol, they would not find it age appropriate, perhaps you could please change the names of the objects? This makes it more kid friendly even though you have the urn example.
Comment: Are you familiar with maximum likelihood or maximum posterior estimators? An MLE will always tell guess that there are $m$ colors present, but MAP would give more intuitive results with a reasonably tuned (say Poisson) prior for the number of colors.
Comment: @TymaGaidash why does it matter if you're a minor? no need to make arguments personal
Comment: I fully agree with @TymaGaidash. The mathematical problem can be stated completely without bringing in "explicit adult content".
Comment: I have edited out the "real life context". You are welcome to include context bearing in mind the site can be used by anyone over the age of 13.
Comment: @granularbastard you're very funny
Comment: A motivation was included that is conform with all ages.
Comment: @FrankSeidl I do not think that an MLE will guess there are $m$ colours present.  If $m=n$ I think the MLE is infinite.  To take [an earlier example](https://math.stackexchange.com/questions/615464/how-many-books-are-in-a-library) (with replacement), if $n=30$ and $m=27$ then I think the MLE is $135$ colours, while an estimate using means is about $135.49$.
Comment: Huh.  It's like a mashup of coupon collector's problem and German tank problem.
Answer: Drawing without replacement
Let $n$ be the number of balls that were sampled with $m$ distinct colors and color frequencies $k_i$  for $i=(1,\ldots, m)$. We call $M$ the number of colors in the urn and $K$ the number of balls per color. $M$ and $K$ are not known, except of the facts that $M\ge m$ and $K\ge \max(k_i)$. Also we have assumed (concerning the original post) that every color has same frequency in the urn. The likelihood to get the observed color counts $k_i$, if we assume values for $M$ and $K$, is given by the multivariate hypergeometric distribution
$$\frac{\prod_{i=1}^{m}\binom{K}{k_i}}{\binom{K\cdot M}{n}}.\tag{1}$$
As the order of the color frequencies in $k_i$ doesn't matter for our problem we have to multiply eq.$(1)$  by the number of their multiset permutations
$$\frac{M!}{(M-m)!\prod_{j=1}^lz_j!},\tag{2}$$
where $z_j$ are the multiplicities of the elements in $k$ and $l$ is the number of different elements in $k$. The factor $(M-m)!$ in eq.$(2)$ includes the multiplicity of $0$, i.e. all colors that are contained in the urn but that were not drawn. (Note that $k_i \ge 1$, because we count only the colors that were drawn but we do not count the colors that were not drawn.) Multiplication of eq.$(1)$ and eq.$(2)$ gives the likelihood for observing $k_i$ colors assuming values for $M$ and $K$
$$p_1(M,K)=\frac{\prod_{i=1}^{m}\binom{K}{k_i}}{\binom{K\cdot M}{n}}\frac{M!}{(M-m)!\prod_{j=1}^lz_j!}\tag{3}$$
Answer: The best guess for the number of colors in the urn is given by that value of $M$ that maximizes $p_1$ for an assumed $K$.
Drawing with replacement
This corresponds to the case $K\to \infty$ in eq.$(3)$ and the likelihood assuming $M$ converges to a multinominal distribution that as previously is multiplicated by eq.(2)
$$p_2(M)=\frac{n!}{\prod_{i=1}^m k_i!}\left(\frac{1}{M}\right)^n \frac{M!}{(M-m)!\prod_{j=1}^lz_j!}\tag{4}.$$
Answer: The best guess for the number of colors in the urn is given by that value of $M$ that maximizes $p_2$.
Example
Let's assume the frequencies of the colors of the drawn balls to be $k_i=(1, 2, 1, 1, 1, 2, 1, 1, 3, 1, 1)$. It follows that $n=15, m=11, K\ge 3, M\ge 11$. The multiplicities of the frequencies in $k$ are $z_j=(1,2,8)$ for $l=3$ different elements in $k$. Plotting the likelihoods shows that there are most likely $21$ different colors in the urn for drawing with replacement ($K=\infty$, black curve). For drawing without replacement and assuming that there are not more balls per color than given by the example ($K=3$, red curve), we get $16$ different colors in the urn as most likely variant. Assuming that in the urn were $K=6$ balls per color we get $18$ colors (blue curve). For higher $K$ the black curve is approached.
Answer: Let $n$ be the number of balls sampled, $m \leq n$ the distinct colors seen, and $k_c$ the frequency of color $c$.
When answering questions of this form (I drew from an unknown distribution, after seeing the observations, what's my guess of the distribution?), you can start by asking yourself: If there were $M \geq m$ colors, what would the likelihood be that you saw the draw that you did?
You could find some answer to that. It would have the shape you expect: if the $k_c$ are on average high, then your guess would be that it was pretty unlikely; if the $k_c$ are low then the opposite. Call this quantity $f(M;n, m, \{k_c\})$.
But how do you put this together? Where does this bring you? Can you answer a question such as "what's the expected number of distinct colors"?
It turns out we can't just yet. Why not? We have infinitely many $M \geq m$, and it's not so simple to just take an "average" over infinitely many terms. In terms of bayesian probability, you first need a prior -- before seeing the results of any draws, what was your guess on the (distribution of) the number of distinct colors in the bin?
Why do we need this? You might complain that, if there were finitely many possibilities, we could just happily take an average and move on. But this is the same as what we just discussed -- you just chose the prior that all of the finitely many outcomes were equally likely. You'll have to do the same here.
So, what are your priors? Well, I've never been to this bar, but as a silly upper bound I'd be pretty certain they have less than 1,000,000 different photos. It's probably likely to be less than 100, too. I'd guess it's more likely to be 15 than it is to be just 3 (and after you see your fourth independent picture, you update your prior such that the probability that there are only three pictures is now zero!).
If your prior beforehand was some function $p(M)$, where $\sum_{M=1}^{\infty} p(M) = 1$, then we can finally come up with what your posterior -- your updated view of the world -- is given your observation $(n, m, \{k_c\})$.
So, what's your new likelihood that there are $M$ distinct colors? Well, naively it'd be $p(M) f(M; m, n, k_c)$ (multiplying your prior guess with the likelihood of the observation), but you also have to normalize and divide by $\sum_M p(M) f(M; m, n, k_c)$, i.e. this quantity summed over all $M$. Calling your new likelihood $p'(M)$, you'd find that your guess of the number of distinct colors is simply
$$\sum_{M=1}^{\infty} M p'(M).$$
Of course, the sum of $p'(M)$ over all $M$ is $1$ by construction, so the above summation is really just the expected value of a random variable.
Apologies for the somewhat nebulous answer here, but hopefully this gives you a place to start for how one might think about questions like these.
Answer: A simple estimation is given by Good $[1]$:

the expected total chance of all species represented at all in the sample is approximately
$$1-\dfrac{n_1}{N}=\dfrac{2n_2+3n_3+\ldots}{N}\tag{1}$$

where $n_i$ tells how often a species was observed $i$ times and $N$ is the sample size.
For the problem given eq.$(1)$ guesses how much the $m$ colors in the sample represent the total number of colors in the urn. The total number of colors $M$ is then guessed by
$$M=\dfrac{m}{1-\dfrac{n_1}{N}}=\dfrac{m N}{2n_2+3n_3+\ldots}\tag{2}$$
The right term in eq.$(2)$ is only needed in case $n_1=0$. This estimator assumes that every color is often present in the urn (drawing with replacement) and is known as Good-Turing estimator in other areas.
Using the example from another answer $k_i=(1,2,1,1,1,2,1,1,3,1,1)$ we have $m=11,N=15,n_1=8$ and get for the number of colors in the urn
$$M=\dfrac{11}{1-\dfrac{8}{15}}\approx 23.6$$.
This number is not a bad guess compared to $21$ colors one got by more effort in the other answer.
$[1]$ Good, I.J. (1953). "The population frequencies of species and the estimation of population parameters". Biometrika. 40 (3–4): 237–264


ASP.NET in-place precompile doesn't work as expected

Question: I am trying to use ASP.NET precompile tool aspnet_compiler.exe to compile site after it has been deployed.
As per book definition running in-place precompile on web machine should improve first page load experience. The compilation tool compiles each ASP.NET page, storing the compiled version in the %WINDIR%\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files folder just like if the pages had each been visited for the first time from a browser. In-place precompilation can speed up the first request made to newly deployed ASP.NET pages on your site because it alleviates the runtime from needing to perform this step.
For some reason for me it does not work expected described way.
When running aspnet_compiler.exe locally on Web machine manually:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v /7.1 -p C:\MyPathToWebSite\www

It created folder of following structure structure:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\7.1\640c1f87\4be3507b

When I try to hit web page using browser, ASP.NET creates another cached version in the following folder on same server:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\7.1\bc8a1bb3\42b014d4

As you can see precompile works in both scenarios (manual and IIS), but for somehow IIS does not see that pages already precompiled and cashed and trying to re-compile everything again. I could not figure out what is missing or done wrong, since aspnet_compiler.exe has limited parameter options for in-place compilation.
So far, I have tried following during testing/investigation in regards of Temporary ASP.NET cache:

Seems like it's not user related, does not matter what user is running manually
Not related on Source/Target IP, since same folders are created on different servers in different subnets

Any ideas and help appreciated.
Answer: I faced the same issue. Only using metabase path to my site solved it.
aspnet_compiler.exe -m /LM/W3SVC/[site ID]/root

Answer: The files you see in the first folder were not jitted. You only compile your site to MSIL, and when you first access some page it gets compiled to native image code - these are the files you see in the second folder.
You might want to use Ngen - http://msdn.microsoft.com/en-us/library/6t9t5wcf(v=vs.110).aspx
Comment: Thanks for replying. In this case this defeat the purpose/goal of the pre-compiler, which suppose to create native code. Specifically when you run in place compilation on the machine itself?
Comment: Compilation doesn't necessarily mean the code is compiled to native code. In .NET (and java, for example) there are two stages of compilation - the first is from source-code to MSIL, and the second is from MSIL to  native. Pre-compilation refers only to the first stage, while Ngen compiles your source-code directly to native (I'm not too familiar with Ngen, but I guess there are some levels of compilation).

ASP.NET in-place precompile doesn’t work as expected


How to determine the magnitude of a resultant vector?

Question: I was able to determine a resultant vector based on the sum of two vectors and told to express them in vector units.  Here is my answer that was correct:
$\overrightarrow{C}=12.01\hat{i}+14.62\hat{j}$
I was told to then determine the magnitude of $\overrightarrow{C}$ but have no idea what to do.
Any tips are greatly appreciated.
Answer: In general, if $\vec{x} = a\vec{i}+b\vec{j}$, then the magnitude of $\vec{x}$, denoted $\lVert \vec{x}\rVert,$ is given by $\lVert \vec{x}\rVert = \sqrt{a^2+b^2}$. Does this help?
Comment: Yes! Thank you.
Comment: You're very welcome!


bluej program that returns all characters up to the first @ sign

Question: public class IndexOf_SOL
{

    /*
     *method getFirstChunk() should return
     *all letters up to the first @ sign
     */
    public static String getLastChunk( String line )
    {
        int loc2 = line.lastIndexOf("@");

        return line.substring(loc2);
    }
    public static String getMiddleChunk( String line )
    {
        int loc1= line.indexOf("@");
        int loc3 = line.lastIndexOf("@");

        return line.substring(loc1,loc3);

    }
    public static String getFirstChunk( String line )
    {
        int loc = line.indexOf("@");
        return line.substring(0,loc);

    }

}

When i do it in order from last,middle, to first chunk
I get @big@areElephants
 When I am suppose to be getting bigareElephants without the @ sign
Comment: Why don't you use Tokenizer ?
Comment: I am not familiarized. It is my first time taking a computer science class and it happens to be AP so I am struggling a bit. Do you use Bluej?
Comment: See my answer! It explains how to do it !
Comment: I tried it, but it doesn't work.
Comment: Try the edited piece of code!
Comment: I can't seem to be able to split the @ sign
Comment: The edited portion in my answer helps split the String whenever it encounters the @ symbol.

Try running the EDITed code.
Answer: Try using
String[] parts = str.split("@");
for(int i=0;i<3;i++)
{
 System.out.println(parts[i]);
}

Hope that helps.
EDIT :
public class IndexOf_SOL
{

    public static void main(String args[])
     {
       String str = "AP@computer@science";
       String[] parts = str.split("@");
       for(int i=0;i<3;i++)
       {
        System.out.println(parts[i]);
       }
     }

}

Try the code after edit !
Hope it helps!!


Validar linha javascript

Question: Pessoal estou tentando fazer um validação linha a linha em uma table da seguinte forma: Se o produto for marcado como sim em um fornecedor ele nao pode ser marcado para outro fornecedor. Alguem pode me ajudar por favor? Segue modelo...

$("button").click(function() {
  $('#selectProduto').change(function(){
    $('#msg').html('');
  });

  var vIdProduto = $('#selectProduto option:selected').val();
  var vProduto = $('#selectProduto option:selected').text();
  var mensagem = $('#msg');
  var linha = '
' +
        '' +
        '<input class="idprod" type="hidden" name="idproduto' + vIdProduto + '" value="' + vIdProduto + '">' + vProduto +
        '	' +
        '' +
        `<select class="form-control" id="autoriza">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '	' +
        '' +
        `<select class="form-control" id="autoriza">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '	' +
        '' +
        `<select class="form-control" id="autoriza">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '	' +
        '
'

  if($("tr#linha" + vIdProduto).length === 0) {
    $('#mytbody').append(linha);
  } else {
    $('#msg').html("⚠ Produto " + vIdProduto + " já foi adicionado!");
  }
  });
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

      <select class="form-control" id="selectProduto">
        <option value="A">Produto A</option>
        <option value="B">Produto B</option>
        <option value="C">Produto C</option>
      </select>

      <button type="button" name="button">Adicionar</button>

            Produto
            Forn01
            Forn02
            Forn03

Comment: Cara seu código está sujeito a gerar problemas, estão se repetindo os **ids** do `selects` criados.
Comment: Poderia explicar melhor seu problema? Estou confuso na sua pergunta rsrs.
Comment: Obrigado pelo retorno, posso sim. Nao posso deixar o sistema aceitar que o usuario compre o mesmo produto em fornecedores diferente, certo? Ex: Se ele marcar como sim no select forn01 o select forn02 e forn03 tera que ser não ou desbilitar entendeu?
Comment: Obrigado pelo retorno  LeAndrade , vou corrigir.
Answer: O mais sensato para esse tipo de formulário seria utilizar input type radio
Quando uma opção RADIO é marcada, esta só será desmarcada quando outra opção RADIO com mesmo NAME for selecionada.

Veja como funciona

Produto A <input type="radio" name="prodA" value="Forn01"/>
<input type="radio" name="prodA" value="Forn02"/>
<input type="radio" name="prodA" value="Forn03"/>

Produto B <input type="radio" name="prodB" value="Forn01"/>
<input type="radio" name="prodB" value="Forn02"/>
<input type="radio" name="prodB" value="Forn03"/>

Produto C <input type="radio" name="prodC" value="Forn01"/>
<input type="radio" name="prodC" value="Forn02"/>
<input type="radio" name="prodC" value="Forn03"/>

Portanto seu código funcionaria assim: veja esse form sendo recuperado no PHP

$("button").click(function() {
  $('#selectProduto').change(function(){
    $('#msg').html('');
  });

  var vIdProduto = $('#selectProduto option:selected').val();
  var vProduto = $('#selectProduto option:selected').text();
  var mensagem = $('#msg');
  var linha = '
' +
        '' +
        '<input class="idprod" type="hidden" name="idproduto' + vIdProduto + '" value="' + vIdProduto + '">' + vProduto +
        '	' +
        '' +
        '<input type="radio" name="prod'+vIdProduto +'" value="Forn01">'+
        '	' +
        '' +
        '<input type="radio" name="prod'+vIdProduto +'" value="Forn02">'+
        '	' +
        '' +
        '<input type="radio" name="prod'+vIdProduto +'" value="Forn03">'+
        '	' +
        '
'

  if($("tr#linha" + vIdProduto).length === 0) {
    $('#mytbody').append(linha);
  } else {
    $('#msg').html("⚠ Produto " + vIdProduto + " já foi adicionado!");
  }
});

      <select class="form-control" id="selectProduto">
        <option value="A">Produto A</option>
        <option value="B">Produto B</option>
        <option value="C">Produto C</option>
      </select>

      <button type="button" name="button">Adicionar</button>

    <form action="" method="post">

            Produto
            Forn01
            Forn02
            Forn03

              <input type="submit">
        </form>

Comment: Isso mesmo. Fica bem melhor.
Comment: Obrigado pelo retorno Sam e Leo. Tentei fazer dessa forma porem tenho que usar o name do input  como name[] dai da erro no momento de recuperar os dados no php.
Comment: @frodrigues, como assim `usar o name do input como name[]` ? E a qual input vc se refere?
Comment: Estou usando php com Laravel. No controllher quando recebo os requests para colocar dentro do laço para inserir no banco ele me da uma mensagem de objeto nao cotabil se nao colocar o name com chaves na frente.
Comment: Ex:   $cont = 0;
    while($cont < count($idproduto)){
      $detalhe = new RequisicaoDet();
      $detalhe->idrequisicao=$requisicoes->idrequisicao;
      $detalhe->idproduto=$idproduto[$cont];
      $detalhe->qnt=$qnt[$cont];
      $detalhe->detalhe=$detalhes[$cont];
      $detalhe->idcentrocusto=$idcentrocusto[$cont];
      $detalhe->save();
      $cont=$cont+1;
    }
Comment: Me refiro ao input de produto ok.
Comment: @frodrigues, blz, de Laravel entendo chongas :)
Comment: Kkkk. Vlw ja ajudou bastante.
Answer: Primeiramente iremos remover os id="autoriza" dos seus select, pois eles estão duplicados e isso é um problema.
Agora iremos adicionar uma nova classe nos seus select para podermos reconhecê-los no JavaScript. Coloque todos igual o código abaixo:
<select class="form-control select-comprar">

Por fim, adicione o JavaScript para tratar a habilitação e desabilitação dos selects:
$('.select-comprar').on('change', function () {
    if ($(this).val() == "Sim") {
        controlarHabilitacaoSelectComprar(false, $(this));
    }
    else {
        controlarHabilitacaoSelectComprar(true, $(this));
    }
});

function controlarHabilitacaoSelectComprar(habilitar, coluna) {
    //Pegamos todas as colunas da mesma linha do select que alteramos o valor
    var siblings = coluna.parent().siblings();

    //Iremos realizar um loop em todos os selects que possuirem a classe que definimos como "select-comprar"
    siblings.find('.teste-select').each(function () {
        if (habilitar) {
            $(this).removeAttr('disabled');
        }
        else {
            $(this).attr('disabled', 'disabled');
            $(this).val('Não');
        }
    });
}

Comment: Obrigado Pedro muito bom
Answer: Como já foi dito, repetir id's é incorreto e traz problemas. Na verdade você nem vai precisar de id's nos selects, então remova-os todos.
Basta apenas criar esse evento que irá desabilitar os outros selects da mesma linha ao selecionar uma das opções:
$(document).on("change", "#mytbody select", function(){

   if($(this).val() == "Sim"){
      $(this).closest("tr").find("select").not(this).prop("disabled", true);
   }else{
      $(this).closest("tr").find("select").prop("disabled", false);
   }

});

Caso volte a selecionar a opção "Comprar" (que tem valor vazio), as outras opções são habilitadas de novo.

Não entendi a função da opção "Não". Não bastaria apenas a opção "Sim"
  e o que não foi marcado com "Sim" deixar vazio na option "Comprar"?

Veja:

$(document).on("change", "#mytbody select", function(){

   if($(this).val() == "Sim"){
      $(this).closest("tr").find("select").not(this).prop("disabled", true);
   }else{
      $(this).closest("tr").find("select").prop("disabled", false);
   }

});

   $("button").click(function() {
  $('#selectProduto').change(function(){
    $('#msg').html('');
  });

  var vIdProduto = $('#selectProduto option:selected').val();
  var vProduto = $('#selectProduto option:selected').text();
  var mensagem = $('#msg');
  var linha = '
' +
        '' +
        '<input class="idprod" type="hidden" name="idproduto' + vIdProduto + '" value="' + vIdProduto + '">' + vProduto +
        '	' +
        '' +
        `<select class="form-control">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '	' +
        '' +
        `<select class="form-control">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '	' +
        '' +
        `<select class="form-control">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '	' +
        '
'

  if($("tr#linha" + vIdProduto).length === 0) {
    $('#mytbody').append(linha);
  } else {
    $('#msg').html("⚠ Produto " + vIdProduto + " já foi adicionado!");
  }
  });

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

      <select class="form-control" id="selectProduto">
        <option value="A">Produto A</option>
        <option value="B">Produto B</option>
        <option value="C">Produto C</option>
      </select>

      <button type="button" name="button">Adicionar</button>

            Produto
            Forn01
            Forn02
            Forn03

Comment: Não posso me arrepender e trocar de fornecedor?
Comment: isso tá meio miado, tem que explicar ao usuario esse esquema
Comment: não é isso, eu digo na página tem que instruir o usuario tipo `amigo se vc quiser mudar de fornecedor selecione a opção "Comprar" (que tem valor vazio) e escolha outro fornrcedor
Comment: Seria até válido, mas como eu achei a opção "Não" desnecessária, nem fui perder tempo com isso.
Comment: Na verdade, isso deveria ser um radiobutton.
Comment: Agora chegou onde eu queria
Comment: Obrigado Sasm, excelente exemplo, vou implementar. Vacilei nos ids mesmo. Ref ao Nao realmente nao faz sentido. Em relação ao radio estou com dificuldade no momento de receber isso no php pois tenho que usá-lo com (name[]) dai da um erro para inserir no banco.

Validar linha javascript


Jquery Resize event handler

Question: Can anyone help me in knowing about the resize event handler in jquery. I'm not able to understand the importance of ben-Alman 's jquery resize plugin. I got to know that we can handle resize events of DOM elements using jquery 1.7.1 version  library  and I did an example and getting executed successfully just with jquery library.. Then why is that plugin is used ? Thanking you..
Comment: Welcome to [so]! At this site you are expected to try to **write the code yourself**. After **[doing more research](//meta.stackoverflow.com/questions/261592)** if you have a problem you can **post what you've tried** with a **clear explanation of what isn't working** and providing a [**Minimal, Complete, and Verifiable example**](//stackoverflow.com/help/mcve). I suggest reading [ask] a good question and [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Also, be sure to take the [tour] and read **[this](//meta.stackoverflow.com/questions/347937/)**.
Comment: Version: 1.1, Last updated: 3/14/2010 ... this plugin is still used there were time stands still.
Answer: You can use jquery resize only on window event:
<code>$(window).resize(...)
</code>
Using the plugin you can handle resize event on DOM element you want:
<code>$("#id").resize(...)
</code>

Jquery Resize event handler


Babel error when running ./gradlew assembleRelease

Question: I receive this error after running ./gradlew assembleRelease:
    Plugin/Preset files are not allowed to export objects, only functions.
 In C:\..\node_modules\babel-preset-expo\index.js

    :app:bundleReleaseJsAndAssets FAILED

    **FAILURE: Build failed with an exception.**

This is what I have in package.json file:
{
  "name": "Mascota24",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "babel-preset-stage-0": "^6.24.1",
    "react-test-renderer": "16.3.1"
  },
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "test": "jest"
  },
  "jest": {
    "preset": "react-native"
  },
  "dependencies": {
    "@babel/preset-react": "^7.0.0-beta.53",
    "babel-preset-env": "^1.7.0",
    "babel-preset-expo": "^4.0.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-native": "^2.1.0",
    "babel-preset-react-native-stage-0": "^1.0.1",
    "react": "16.3.1",
    "react-native": "^0.56.0",
    "react-native-circle-checkbox": "^0.1.6",
    "react-native-modal": "^6.4.0",
    "react-native-phone-call": "^1.0.7",
    "react-navigation": "^2.6.2",
    "react-redux": "^5.0.7",
    "redux-thunk": "^2.3.0"
  }
}

And this is .babelrc file:
{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  }
}

I've followed almost every post here related with this and none of them helped me :( Thanks for any help
Comment: https://stackoverflow.com/questions/51210574/create-react-native-app-plugin-preset-files-are-not-allowed-to-export-objects
Check this link aroudn
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174906/discussion-between-ashutosh-pandey-and-guille).
Comment: Look in this issue https://stackoverflow.com/questions/51210574/create-react-native-app-plugin-preset-files-are-not-allowed-to-export-objects
Check this link it work for you .
Comment: Add you error please
Comment: @ashutoshpandey the error is: "Plugin/Preset files are not allowed to export objects, only functions.
 In C:\..\node_modules\babel-preset-expo\index.js

    :app:bundleReleaseJsAndAssets FAILED

    **FAILURE: Build failed with an exception.**"
Comment: let me check now
Comment: did you run any update command
Comment: i run "npm update" as part of the possible solutions i found, but before that it wasn't working neither...
Comment: can you check above link
Comment: i checked, i changed  the version to "react-native": "^0.55" but still the same :(
Comment: wait.., the error changed, now it's "Unable to resolve module `redux` from `C:\Users\Digital\Mascota24\store.js`: Module `redux` does not exist in the Haste module map"
Comment: Look in this issue https://stackoverflow.com/questions/51210574/create-react-native-app-plugin-preset-files-are-not-allowed-to-export-objects
Check this link it work for you .
Answer: Thanks to @ashutosh pandey for the help, I changed react-native version to:
"react-native": "^0.55"

Then I installed redux and could generate the .apk! :D
Comment: @ashutoshpandey can you chat 1 sec?
Comment: yeap. https://stackoverflow.com/questions/51330836/react-native-router-not-working


Calculating variance of a sum

Question: The number of students per day has the distribution N ∼ Poisson(10).
The students of CSUEB withdraw money from a cash machine according to the following probability function (X):
X        | 50 | 100 | 200
P(X = x) | 0.3| 0.5 | 0.2
Let $T_N = X_1 +X_2 +···+X_N$ be the total amount of money withdrawn in a day, where each $X_i$ has the probability function in the table, and $X_1,X_2,...$ are independent of each other and of N. Here $T_N$ is a randomly stopped sum, stopped by the random number of N customers.
Find $Var(T_N)$.
Attempt:
I've found E[X] = 105 and Var[X] = 2725
My attempt at solving this is:
$Var[T_N | N] = Var[X_1] + \cdot\cdot\cdot+Var[X_N] = 2725N = 27250$
I thought this was pretty straight forward but I'm not too confident. Is it correct to make the assumption that $Var[T_N] = 2725N$?
Update:
If I use the property
$V[X] = V[E[X|Y]]+E[V[X|Y]$
and
$E[T_N|N] = 105N$, $V[T_N|N] = 2725N$, $V[N] = 10$, $E[N] = 10$
then,
$V[T_N] = V[105N] + E[2725N] = 105^2N + 2725N = 137500$
Answer: No, it is not correct.
The variability in $T_N$ arises not only due to $X_i$ bit also due to random number of summands $N$.
Hint:
To calculate the required quantities, use the law of iterated expectations which results in following identities:
\begin{align}
E(X) &= E(E(X\mid Y))
\\V(X) &= V(E(X\mid Y)) + E(V(X\mid Y))
\end{align}
Note:
What you have calculated is in fact $V(T_N\mid N)$.
Comment: I've updated my question using the properties you've provided. It is very close to the simulation of the variance that I've done in R. Thank you.
Comment: @ThrmsNPrfs My pleasure

Calculating variance of a sum


Taking square root for weighted linear regression

Question: I am doing weighted linear regression. I decided to weight my data points on the number of genes per chromosome per species. The graph I made on the basis of that wasn't much different than the unweighted linear regression. However, when I took the square root of the number of genes per chromosome per species and use that as my weight, the graph was different from unweighted linear regression. Can someone tell me why I had such difference? And if taking a square root is a better way to weight my data points? If yes, then why is that? Could you give me a statistical reason? Because I read somewhere that taking square root for weight is a common practice.
Answer: I do not think that there is a statistical reason for what you happen to observe in this case.  Taking square roots or logarithms is commonly done applied to variables with skewed distributions to make them more symmetric.  I don't know if there is any other way that square roots are useful transformations.
Comment: The square-root transformation has a long history of being used to try to stabilize variance in count data, which might be related to its use in gene-number data. See [this discussion](https://stats.stackexchange.com/q/46418/28500). I still remember that from my long-lost copy of Snedecor and Cochran.


How to get facebook page posts on website

Question: Hi I have a facebook page (not an app), and I want to get the recent post on my website using PHP.
I don't know where to begin. I used google to look this up but all I could find was how to get post from an app.
Answer: Its a very broad question. Anyways, just follow these steps-

If you are not registered as a facebook developers, register here: https://developers.facebook.com/
Then, create an app from here: https://developers.facebook.com/apps
Copy the app access token (app-id|app-secret) to your php script- this is required, since to fetch the posts (public) from a page, you need a valid access token.
Get the contents using curl or file_get_contents of the url:
https://graph.facebook.com/{page-id/page-username}/posts?access_token={app-access-token}

(You can see the result by browsing above url in a browser) Just parse the JSON and get the posts as required. You'll not get all the posts in one go, but in the result you'll have the url to the next page.
Hope that helps!
Comment: Nope. You can do the same to fetch the public posts of any page on facebook.
Comment: Thanks, i'm going to try that. So the app doesn't need be connected to my page?
Comment: Okey Thanks! I will try that:) of course I'm gonna vote, just need to try it:)
Comment: I get an error:

'Syntax error \"Expected end of string instead of \"|\".\" at character 15: 000000000000000|xxxxxxxxxxxxxxxxxxxxxxxx'

How do I solve that?
Comment: Nevermind, found the problem, it should be access_token= instead of fields=.

But thanks a lot for all the help :)
Comment: With the latest API this solution doesn't work. You won't have permission to do so.


Chebyshev function - show that $\psi(x)>(x-2)\log2-\log(x+1)$

Question: The question I'm trying to do is this:
Assume $x>2$ and $n=\lfloor x/2\rfloor$. Show that $\psi(x)>(x-2)\log2-\log(x+1)$, given the inequality $2n\log2-\log(2n+1)<\psi(2n)$.
All I've really done is substitute $n$ in to get
$2\lfloor x/2\rfloor\log2-\log(2\lfloor x/2\rfloor+1)<\psi(2\lfloor x/2\rfloor)$
No idea what to do.. could it be a manipulation involving $\lfloor 2x\rfloor- 2\lfloor x\rfloor=0$ or $1$?
Answer: The Chebyshev function doesn't come into it much once you have what you are given (just $\psi(x)=\psi(\lfloor x \rfloor)$). Doing a check on the two case $1 \ge x-2n > 0$ and $2 > x-2n \ge 1$ gives
for the former: $2 \lfloor \frac{x}{2} \rfloor = \lfloor x \rfloor$,
for the second: $2 \lfloor \frac{x}{2} \rfloor = \lfloor x \rfloor - 1$.
In either case it is sufficient to prove:
$(x-2) \log 2 - \log(x+1) < \lfloor x \rfloor \log 2 - \log ( \lfloor x \rfloor +1 )$
$\log(x+1)-\log(\lfloor x \rfloor +1) > (x-\lfloor x \rfloor -2)\log2$
which is a given as the LHS >= 0 and the RHS < 0
Comment: Where did checking the two cases with $x-2n$ come from?
Comment: the floor function of x/2 goes up by one every two of x, hence there is two unit intervals of x to consider.
Comment: Got it, thank you
Answer: Also a bound $ax >\psi(x) > b x$ can be obtained from $$n \log 4 +O(\log n)= \log{2n \choose n} = \log(2n)! - 2 \log n! = \sum_{p^k \le 2n} (\lfloor 2n/p^k \rfloor - 2\lfloor n/p^k \rfloor) \log p$$
$$ \in [\psi(2n)-\psi(n),\psi(2n)]$$ as $\lfloor 2n/p^k \rfloor - 2\lfloor n/p^k \rfloor \in \{0,1\}$


CLion: Enable compiler errors/warnings

Question: I am using CLion 2016.1.1 on Ubuntu (16.04)
When I compile my project, the CMake output shows:
/opt/clion/bin/cmake/bin/cmake --build
/home/glapworth/.CLion2016.1/system/cmake/generated/project_name-f43e0982/f43e0982/Debug --target all -- -j 8
[ 33%] Linking C executable
/home/glapworth/src/project/project_name/bin/project_name

However, when I execute:
/opt/clion/bin/cmake/bin/cmake --build /home/glapworth/.CLion2016.1/system/cmake/generated/project_name-f43e0982/f43e0982/Debug --target all -- -j 8

I can see the compiler error:
...
CMakeFiles/project.dir/src/main.c.o: In function `main':
/home/glapworth/src/project/project_name/src/main.c:22: undefined reference to `curl_global_init'
...

How can I get CLion to show the compiler errors or warnings?
Comment: If `cilon` not show compile error, then this is a bug in `clion`
Comment: Build with VERBOSE=yes and find the difference in the compiler invocation.
Comment: When I build with `set(CMAKE_VERBOSE_MAKEFILE ON)` I still don't see the error.  The compiler invocation is `/usr/bin/gcc    -Werror -Wall -g   -o CMakeFiles/project.dir/src/main.c.o   -c /home/glapworth/src/project/project/src/main.c` which is correct.  When running the same command from a terminal, I can clearly see the compiler errors.  It looks like STDERR is being redirected away from the Messages tab in CLion :(
Answer: here's bug-report https://youtrack.jetbrains.com/issue/CPP-6559
No, CLion shows all compile errors.  You can't compile a project if you have errors.
But, CLion shows notices only once during build time, until you make a clean build, you will not see them again. Because you have already compiled object files and CLion (CMake) will not rebuild them if you haven't changed source files.
CMake assumes you know what your'e doing and does not rebuild all your codebase from scratch, so you don't see notices after the first compile run.
Comment: If I understand correctly:  Build -> it shows errors.  Build again, and no warnings or errors. If I then perform a clean, then build it should show me the errors and warnings.  I've tried this, and it doesn't.
Comment: @glapworth there's a temporary work-around here https://youtrack.jetbrains.com/issue/CPP-6325
Comment: got it, too it's a bug. For me it looks like abruptly broken link-time message, I'll
Answer: It seems that CLion only shows the error on the first compile. If you've accidentally compiled a second time, you'll not be able to see the error output.  I've since moved back to vim.
However, if you want to stick with CLion, and you are having the same problem, you can build the Makefile manually; In the source directory that contains the CMakeLists.txt
cmake .
make

This will allow you to compile on demand from a terminal.
I also tend to set the build directoy to ./bin by editing the CMakeLists.txt to include the following line
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/bin")
Answer: You have to check your CMakeLists.txt. What does it look like? You can also try and clean your code, tool -> cmake -> refresh (both options) and have a regular Makefile that your build with so if Clion doesn't inform you about what's wrong then you can build with a regular Makefile . My CMakeLists.txt looks like this
cmake_minimum_required(VERSION 2.8.12)
project(project001)
set(CMAKE_VERBOSE_MAKEFILE on)
file(GLOB SOURCES "./*.c")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -Wall -pedantic")
add_executable(project001 ${SOURCES})
target_link_libraries(project001 readline)

My Makefile for the same project is
CC = gcc
GIT_VERSION := $(project001 git describe --abbrev=4 --dirty --always --tags)
CFLAGS := $(CFLAGS) -pedantic -std=c99 -Wall -O3 -ledit -g -DVERSION=\"$(GIT_VERSION)\"

project001: main.o
    $(CC) -o project001 main.o errors.c util.c pipeline.c -ledit

main.o: main.c errors.c util.c

.PHONY: clean
clean:
    rm -f *.o

If Clion can't compile, then I fix the errors at the prompt and I use Clion to analyze my code so that it compiles without errors, then I can clean the project in Clion and run it from within Clion again.
Comment: Using the same CMakeLists.txt doesn't work. I only get error output on the first compile.  After that, just a % of the compilation is shown, where it stops.  This, is the same behaviour as before.  I've taken to compiling through the CLI, and I've moved back to vim.

CLion: Enable compiler errors/warnings


Is there a concise, specific name for a transform that consists of rotate, scale and translate?

Question: I'm working on software that involves transforming between different mapping coordinate systems. In one part of the maths/logic, I have to derive, then apply a transform between two cartesian coordinate systems using a rotate, uniform-scale, translate, and an optional flip operation.
The resulting transformation will preserve angles as well as the aspect-ratio (due to the uniform-scale).
Is there a specific mathematical name for this combined transform? I want to make sure I get the terminology in the code as correct (and succinct) as possible.
Comment: no linear transformation can be a translation
Comment: @janmarqz you are of course correct, the question has been corrected
Comment: An affine transformation (perhaps too general, affine can have different scales for different axes, for example).
Comment: @copper.hat an affine transform is more general, and can include skew as well as non-uniform scaling, which this type of transform explicitly excludes.
Comment: Hmm, rigid body transformation is too specific (no scaling).
Answer: Such a thing is commonly called a similarity, as it sends a geometric object $X$ to an object that's similar to $X$.
To quote the great Wikipedia,

A similarity (also called a similarity transformation or similitude) of a Euclidean space is a bijection $f$ from the space onto itself that multiplies all distances by the same positive real number $r$ [...]

You can even distinguish between direct similarities, that preserve orientation, and opposite similarities, that reverse orientation.
This convention is followed in Needham's Visual Complex Analysis, for example:

A similarity $\mathcal{S}$ is a mapping of the plane to itself that preserves ratios of distances.
Comment: Factoid, if I hadn't started reading that book today, I would have had no idea :)
Comment: I'm writing software, so verbose is ok as long as it's exact and specific - in fact when it reduces ambiguity it's often a good thing. A non-mathematically educated software developer is more likely to understand `SimilarityTransformation` out of context since they are likely to understand  the term `Transformation` than they are to understand `Similarity` on its own.
Comment: I've actually ended up with `SimilarityTransform`, since it's standard in software to use `Transform` instead of `Transformation` (`AffineTransform` is a common term used to describe the coefficients/matrix itself).
Comment: This perfectly describes the _properties_ of the transform, but is there a term that describes the transform itself? E.g. a Similar Transformation?
Comment: In the link, a few terms are used and the exact term "similarity," for the map itself, is one of them. "Similarity transformation" and "similitude" are listed also, but are kind of verbose, given the alternative.
Comment: That makes perfect sense then. I'd personally choose `SimilarityTransformation` in that case.


Integrity of a hashmap sent over network

Question: My servlet encrypts and sends a HashMap and its MD5 hash.
The client then receives them, and compares the MD5 with one it works out from the HashMap.
This works sometimes but not others, eg, if the HashMap is:
    HashMap<String, Object> result = new HashMap<String, Object>();
    result.put("error", 0);
    result.put("coun", 0);

That works
However, if it's:
    HashMap<String, Object> result = new HashMap<String, Object>();
    result.put("error", 0);
    result.put("count", 0);

It doesn't work - the two MD5 hashes are different. (only difference being the key 'count' instead of 'coun')
The program sends similar HashMaps, all containing keys/values that are only Strings or Integers, and this is the first time i've seen something wierd like this.
Details of how the HashMap/MD5 is actually sent -
Server does:
    //Work out MD5 of the HashMap result (convert it to bytes with objectOutputStream, and MD5 the bytes)
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    ObjectOutputStream out = new ObjectOutputStream(bos) ;
    out.writeObject(result);
    out.close();
    byte[] md5 = messageDigest.digest(bos.toByteArray();

    //Encrypt the httpURLConnection response stream, and send the HashMap result and the md5 over the stream
    Cipher symmetricCipher = Cipher.getInstance("DES");
    symmetricCipher.init(Cipher.ENCRYPT_MODE, symmetricKey);
    CipherOutputStream cipherOutput = new CipherOutputStream(response.getOutputStream(), symmetricCipher);
    BufferedOutputStream bufferedOutput = new BufferedOutputStream(cipherOutput);
    ObjectOutputStream objectOutput = new ObjectOutputStream(out);
    objectOutput.writeObject(result);
    objectOutput.writeObject(md5);
    objectOutput.flush();

The client does:
    //Decrypt the httpURLConnection response stream
    Cipher symmetricCipher = Cipher.getInstance("DES");
    symmetricCipher.init(Cipher.DECRYPT_MODE, symmetricKey);
    CipherInputStream cipherInput = new CipherInputStream(httpInput, symmetricCipher);
    BufferedInputStream bufferedInput = new BufferedInputStream(cipherInput);

    //read HashMap and MD5
    ObjectInputStream objectInput = new ObjectInputStream(in);
    HashMap<String, Object> result = (HashMap<String, Object>) objectInput.readObject();
    byte[] hash1 = (byte[]) objectInput.readObject();

    //workout hash of the Hashmap received.
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    ObjectOutputStream out = new ObjectOutputStream(bos) ;
    out.writeObject(result);
    out.close();
    byte[] hash2 = messageDigest.digest(bos.toByteArray();

    // Compare two hashes
    if (!Arrays.equals(hash1, hash2)) {
        System.out.println("Result received does not match hash, stopping list operation");
        return;
    }

decrypts using the same type of inputStreams, works out the md5 of the hashmap in the same way, and then compares using:
    if (!Arrays.equals(hash1, hash2)) {
            System.out.println("Result received does not match hash, stopping get operation");
            return;
    }

I don't understand why this has worked for sending all the HashMaps i've tried, but doesn't work now with this count key.
I've tested comparing the individual key/value pairs inside the HashMap on the client and servlet, and they are the same, but when comparing the two MD5's of the whole HashMap they don't match.
Also, I'm not sure i'm using the buffered stream at the correct part of the stream chain?
Comment: You say, "the two MD5 hashes are different", which two MD5 hashes are you talking about here, *specifically*?
Answer: There is no guarantee that two copies of Java will produce exactly the same bytes as a serialization of an object -- only that they will produce a semantically equivalent object.
You could make something like this work by running the digests on the keys and values, but you'd need to decide how to hash the Object values.
If you can render to XML, and canonicalize that, then you could go from there.
You could look in to the various web service standards for security instead of rolling your own.
Suggestion: copy the hash map into a TreeMap, which has an order, and try the same trick with that.
Comment: thx, just assumed there was a guarantee because its been working for lots of different hashmaps until now fine - thought it was ok because they only contained integers and strings...any idea of why this specific hashmap is the one that it stops working for? Have to roll my own, its for an assignment
Comment: No guarantee, is it is walking the map in an undefined order.
Comment: ok will try treemap, else i'll just MD5 the stuff in the hashmap rather than the serialized bytes...Thanks
Answer: May be just send JSON with key value pairs from one JVM and on the receiver side, you can deserialize and construct another HashMap


Best protocol for CDN hosted jQuery library

Question: I am using CDN hosted jQuery.
What is the effective difference between:

and

(with / without http prefix)
Which method is "best" (safest, fastest)?
Comment: I think the 2nd option tells the browser to use whatever protocol is in use for the page as a whole, so if you switch your site to https your script-loads will be via SSL too.
Comment: Keeping the option of `https` open is always safer than forcing `http`...
Comment: The difference is that with the second example, the protocol (http vs https vs file) is selected for you automatically by the browser depending on how the entire page is being loaded.
Comment: One other warning - this was a long time ago, but I actually had a client where aspnetcdn.com was blocked by their firewall! http://stackoverflow.com/questions/2145277/what-are-the-advantages-and-disadvantages-of-using-cdncontent-delivery-network/5277337#5277337
Comment: I don't understand why this question has 3 downvotes. Seems legitimate.
Answer: This code will use the HTTP protocol:

This code will use the HTTP or HTTPS protocol, depending on what protocol the page it's loaded on is using:

One important note is that when doing local development, the above will try to use the file:// protocol, which will fail.
To get around this issue, you can use this code:

Comment: Thanks Blake. What's the purpose of `document.write(unescape('%3Cscript` instead of just `document.write('<script`
Comment: That's a really good question. I sourced that portion from http://www.paulirish.com/2010/the-protocol-relative-url/ which references the HTML5 Boilerplate. But the HTML5 Boilerplate actually uses the syntax you noted: https://github.com/h5bp/html5-boilerplate/blob/master/src/index.html
Comment: By the way, Blake, I wish I could bump you another +1 for the note about local dev trying to use `file://` protocol -- a most useful tidbit. Hopefully others will help me out here.
Comment: You're too kind crashwap. Hopefully someone else can jump in here and enlighten us about your follow-up question.


Como saber se um elemento tem a propriedade html ou value?

Question: Tenho dois elementos que precisam ser atualizados um DIV e outro INPUT
Um tem deve ser atualizado o value e outro o html, exemplo
...
    $.each(json, function (index, value) {
       if (typeof $("#" + index).val() !== "undefined") {
           $("#" + index).val(value);
       } else {
           if (typeof $("#" + index).html() !== "undefined") {
               $("#" + index).html(value);
           }
      }
   });
...

Estou fazendo da forma acima mas não esta funcionando
Answer: Pode verificar pelo nome da tag:
...
    $.each(json, function (index, value) {
       if ( $("#" + index).prop("tagName") == "INPUT") {
           $("#" + index).val(value);
       } else {
           $("#" + index).html(value);
      }
   });
...

Só não ficou claro o motivo desse outro if dentro do else. Mas desta forma verificando nome da tag já resolve se vai usar .val() ou .html().
Comment: Como não tinha certeza de que pudesse gerar erro resolvi colocar outro if, vou usar seu exemplo
Comment: Blz. Dá um feedback se resolveu ou não.
Comment: DVD deu certo, valeu


Como somar um array com ele mesmo mais dados?

Question: É o seguinte galera. Eu tenho um for e dentro dele eu tenho um array ($smses) que recebe ($smses = $smses + 'os dados da minha aplicação'). O problema é que isso não funciona, gostaria de saber como eu add os novos dados a partir do novo indice.
     if ($campanha['Smse']['entity'] == 0) {
                for ($i=0; $i < $tamanho; $i++) {

                    $smses =  $smses + $this->Phone->find('list', array(
                        'fields' => array('Phone.phone'),
                        'conditions' => array(
                            $conditions,
                            'Phone.type' => 2,
                            'Phone.phone !=' => '',
                            ),
                        'joins' => array(
                            array(
                                'table' => 'contacts',
                                'alias' => 'Contact',
                                'type' => 'LEFT',
                                'conditions' => array('Phone.contact_id = Contact.id')
                                ),
                            array(
                                'table' => 'prospects',
                                'alias' => 'Prospect',
                                'type' => 'LEFT',
                                'conditions' => array('Prospect.contact_id = Contact.id')
                                ),
                            ),
                        ));
                    }
                }

Answer: Você não pode "somar" arrays dessa forma. Para fundir dois ou mais arrays você deve usar a função array_merge.
No seu caso ficaria algo assim:
$smses =  array_merge($smses, $this->Phone->find('list', array(
    'fields' => array('Phone.phone'),
    'conditions' => array(
        $conditions,
        'Phone.type' => 2,
        'Phone.phone !=' => '',
        ),
    'joins' => array(
        array(
            'table' => 'contacts',
            'alias' => 'Contact',
            'type' => 'LEFT',
            'conditions' => array('Phone.contact_id = Contact.id')
            ),
        array(
            'table' => 'prospects',
            'alias' => 'Prospect',
            'type' => 'LEFT',
            'conditions' => array('Prospect.contact_id = Contact.id')
            ),
        ),
)));

Comment: Obrigado! Funfou aq.


$\sum a_n$ converges, converge $\sum (a_n)/(1-a_n)$ too?

Question: Suppose that 0 < $a_n$ < 1 and you know that $\sum a_n$ converges. Is it right that $\sum (a_n)/(1 - a_n)$ converges too? I don't know how I can answer this. I have already considered the comparison test, but I don't exactly know how to work that out. Can somebody give a hint?
Answer: Hint: Given that $\sum a_n$ converges, you know that $a_n\to 0$ as $n\to \infty$. Therefore, what can you say about $1-a_n$ as $n\to \infty$?
Comment: That will obviously go to $1$
Comment: Right, now you have to write it formally. I suggest you using the $n_0,\varepsilon$ definition of limit and then use the comparison test.
Answer: $a_n \gt 0$, $ a_n\not=1,$ for $n \in \mathbb{Z+}$.
$ \lim_{n \rightarrow \infty} a_n= 0.$
There is $n_0$ such that $a_n \lt 1/2$ for $n\ge n_0.$
For $n \gt n_0:$
$\dfrac{a_n}{1- a_n} \le 2a_n.$
$\sum_{i=1}^{k} 2a_i$ converges.
$\rightarrow: $
1)$S_k := \sum_{i=1}^{k} \dfrac{a_i}{1-a_i}$ is bounded above
2) $S_k$ is monotonically increasing ,
hence convergent.


Cannot run command in Mongoose

Question: Problem Statement
I cannot run a MongoDB command in Mongoose's model.db.db.admin().command() method. It gives me the error: UnhandledPromiseRejectionWarning: MongoError: no such command: '0'

What I have tried

I have tried running it in my CLI and MongoDB Compass Shell to see if it is an error with my command, and it seems it is, and it gives me this error:

SyntaxError: Unexpected token, expected ";" (1:15)
mongoexport -c appointment -o appointments_2021_04_10_9_52.json

I have googled for many hours trying to find out how to fix these errors and run a proper command in Mongoose.

Please note: I am quite new to Mongoose/NodeJS and MongoDB. Also, I am running MongoDB locally.

My Code (app.js)
app.get('/exportAllAppoinments', (req, res) => {

    mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {

        const dateTime = moment().format('yyyy_mm_dd_hh_mm');
        console.log(dateTime);

        modelAppointment.db.db.admin().command('mongoexport --collection=appointment --out=appointments_' + dateTime + '.json').then(result => {
            console.log(result);
        });
    },
        err => console.log(err)
    );
});

Expected Results
Mongoose should export the entire collection and send the file back to the frontend.

Actual Results
It does nothing and gives me an error as shown in the beginning.
Comment: With `--out=appointments_' + dateTime + '.json'` the file is stored locally on your server. Maybe try `--out=-` which sends the output to STDOUT. Also you did not specify any database (but maybe it is already part of the connection URI).
Comment: @WernfriedDomscheit It already knows which database it needs to run on (since the model is connected to the specific database). Also, I have tried what you said with the `--out=-` where there is a `-` in it, and it didn't work. Same error.
Answer: modelAppointment.db.db.admin().command() is used to submit a database command to MongoDB.
mongoexport is a command line tool, not a database command.
You might try using exec from child_process to run the command.

Cannot run command in Mongoose


The Chrome extension. Assign buttons with functions in Popup menu

Question: Please help! How assign buttons with functions in Popup menu?
popup.html

<title>Common Messages for Intercom</title>

Message 1

Message 2

popup.js
function Button1() {
  // Something
}

function Button2() {
  // Something
}

Thanks!
Comment: Provide more insight on what do you want to achieve?
Comment: Try the code: `Message 1` `Message 2`
Comment: @gui47 Harmful advice [because reasons](https://developer.chrome.com/extensions/contentSecurityPolicy#JSExecution).
Comment: By the way, this is best practice to put the scripts at the end of the body.
Comment: @Xan Thanks! I forgot the Content Security Policy.
Comment: @Elad Is it? Chrome documentation suggests using `DOMContentLoaded`.
Comment: So? Twice are best parctices. Place the script at the buttom, improve the loading speed.
Answer: popup.html

<title>Common Messages for Intercom</title>

Message 1

Message 2

popup.js
document.getElementById('button1').onclick = Button1;
document.getElementById('button2').onclick = Button2;

function Button1() {
  // Something
}

function Button2() {
  // Something
}

Comment: Nice theory. In fact, if you put the script at end of the body this will work.
Comment: **If**. Your answer as is was at first would not work.
Answer:
You need to be able to identify your elements. Therefore, give them unique IDs:
Message 1

Message 2

You need to bind your functions to the click event:
function Button1() {
  // Something
}

document.getElementById("btn1").addEventListener("click", Button1);

The above will not work yet, as it will execute before DOM is built (and therefore #btn1 does not exist yet). Wrap things in DOMContentLoaded listener to make sure DOM is ready:
function Button1() {
  // Something
}

function Button2() {
  // Something
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("btn1").addEventListener("click", Button1);
  document.getElementById("btn2").addEventListener("click", Button2);
});


Result of K-Means Algorithm Not Desired

Question: I am learning about K-means algorithm, and I have generated a dataset with 150000 data points, with 10000 points per cluster. (Scatter plot at the bottom)
When I run K-means on the dataset, I first randomly pick 15 data points as initial centers, and then use the traditional iterative approach to update the centers until convergence. However, this gives undesired results, a sample as follows:
Cluster 0: 14.136004, 48.625093
Cluster 1: 82.353156, 43.582929
Cluster 2: 45.823547, 61.650882
Cluster 3: 58.467780, 90.994505
Cluster 4: 79.734026, 78.028310
Cluster 5: 58.467912, 91.018907
Cluster 6: 89.781302, 26.638219
Cluster 7: 75.079899, 97.764001
Cluster 8: 63.669296, 73.583218
Cluster 9: 41.334973, 19.812627
Cluster 10: 75.589260, 97.997850
Cluster 11: 73.342196, 63.601545
Cluster 12: 81.802223, 43.727663
Cluster 13: 93.317351, 91.788683
Cluster 14: 82.203258, 44.138953

I have two questions:

Note that Cluster 1, 12, and 14 correspond to the same cluster, yet the algorithm converges there. Is this normal for the outcome of K-means algorithm?
Is it possible that when we re-calculate the location of a new center, the set of points we average over is empty? i.e. for all data points, they are nearer to some other center than the particular center we try to calculate?
Comment: How is your image related to the question? I was not able to find Cluster_0 there.
Comment: @SalvadorDali The clusters are un-ordererd final results given by the algorithm. And yes, cluster_0 does **not** correspond to a real cluster in the dataset. Also, Cluster 1, 12,14 all correspond to a same cluster. That's why I asked this question...
Comment: still can not understand: 1, 12, 14 are the same cluster (s they shown as one, which I can not see on the picture). But there are 15 clusters there (almost none of them corresponds to the numbers above).
Comment: There isn't a spot at (14, 48) in the plot. That's what @SalvadorDali is referring to.
Comment: @gung That's correct. My guess is that the center (14, 48) corresponds to a weighted average of the two left-most (by x-coord) clusters in the dataset.
Comment: So then the spots refer to your actual data? & each spot is 10k points? If so, those are *highly* clustered.
Answer:
Yes, perfectly normal. I don't think this can be avoided if you choose random starting points.
Yes, in principle. In R, if this happens and you try to run k-means clustering, it will throw an error as in this example:
x <- matrix(c(1,2,1.1,1.1,1,1,2,1.1,1,1.1), nc=2)
kmeans(x, 4, centers=matrix(rnorm(8), nc=2)) -> out  # random starting points
Error: empty cluster: try a better set of initial centers

However, I don't think this can happen if you assign the cluster centres to be random points in the dataset, which is the default behaviour of the kmeans function in R.
x <- matrix(c(1,2,1.1,1.1,1,1,2,1.1,1,1.1), nc=2)
kmeans(x, 4)

Result of K-Means Algorithm Not Desired


An alternative definition of open sets using the following property?

Question: Recently I have gone through the following problem.

Let $E$ be a subset of a metric space with the following property: If a sequence $(x_n)_{n\in\mathbb{N}}\in X$ converges to $x\in E$ then there exists $n_0\in\mathbb{N}$ such that $x_n\in E$ for all $n\ge n_0$. Prove that $E$ is open.

Before proving this, I have proved that,

Let $(X,\tau)$ be a topological space and $Y\subseteq X$. Then $Y$ is closed iff it contains all its adherent points.

After writing a complete proof I found that if we assume that in a topological space $(X,\tau)$ every adherent point of $Y\subseteq X$ is the limit of some sequence $(x_n)_{n\in\mathbb{N}}\in Y$ then (using the above theorem) we can give a definition of open sets of that topological space in terms of sequences in the following way,

Let $X$ be a non-emptyset and $E\subseteq X$. We will say $E$ to be an open set in $X$ if a sequence $(x_n)_{n\in\mathbb{N}}\in X$ converges to $x\in E$ implies the existence of $n_0\in\mathbb{N}$ such that $x_n\in E$ for all $n\ge n_0$.

My questions are,

Can the above idea be used as an alternative to define open sets of arbitrary topological spaces, not necessarily in terms of sequences but maybe for some suitable generalization of the notion of sequences?

If so, then can some related literature be mentioned?
Answer: As Tim Raczkowski says, your definition does not work as is (consider the uncountable well ordered set with a point at $\infty$). But there is a generalization of sequence which may help. That generalization is nets. Nets are mappings of arbitrary directed sets into the topological space, so they are like sequences, but may have uncountably many terms. For more information, you could take a look at General Topology by Stephen Willard. You can even see the original exposition of nets here, though the article is almost 100 years old, and a bit dense.
Comment: Does the property that I have mentioned at the beginning hold for nets?
Comment: You'd have to prove that. What is true is that every adherent point is the limit of a net, so you stand a good chance of applying the same method.
Answer: This idea only works for topological spaces which are 1-st countable.  That is, that every point has a countable basis.  We can't define closed spaces in terms of sequences because of this.  If a space $X$ is not 1-st countable, it may have too many open sets to guarantee that a closed set contains all it's sequential limits.
Check Munkres - Topology $\S 21$.
Comment: Is it an answer to one of my questions?
Comment: Yes. What are you not understanding?
Comment: Which question(s) does it answer?
Comment: Both of your questions.


Strict Mode complains on resource leak

Question: Strict mode complains the following: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.:
**response = httpclient.execute(httpPost);**

Below is my code:
    HttpClient httpclient = new DefaultHttpClient();

    String url = "example";
    HttpPost httpPost = new HttpPost(url);

    HttpResponse response;
    String responseString = "";
    try {
        httpPost.setHeader("Content-Type", "application/json");

**response = httpclient.execute(httpPost);**

        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    return responseString;

Thanks in advance.
Comment: are you closing you HTTP client in the final block.. `httpClient.getConnectionManager().shutdown();...`
Answer: As of 4.3 the method pointed out by kenota is deprecated.
Instead of HttpClient you should now use CloseableHttpClient as shown below:
    CloseableHttpClient client= HttpClientBuilder.create().build();

Then you can close it using:
    client.close();

Comment: [Apache Docs](http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/CloseableHttpClient.html) -

Apparantly Android doesn't actually use a specific release version of Apache HTTP ([source](http://stackoverflow.com/questions/2618573/what-version-of-apache-http-client-is-bundled-in-android-1-6)). Which I guess means it's okay to use the deprecated method mentioned by kenota (although I haven't actually tested this).
Comment: The funny thing is the compiler warns about resource leak, and so when we want to fix it, there is no `close()` method. Then they had to come up with the `Closeable` version to solve this problem. **Messy!**
Comment: @ADTC: From the docs: `This interface represents only the most basic contract for HTTP request execution. It imposes no restrictions or particular details on the request execution process and leaves the specifics of state management, authentication and redirect handling up to individual implementations.`  I guess they just decided it didn't belong there - can't say why though.
Comment: [Can't find it](http://developer.android.com/reference/packages.html#q=CloseableHttpClient) in the documentation, do you have a link ?
Comment: Why doesn't `HttpClient` interface have a `close` method when it should be closeable?
Answer: As Praful Bhatanagar pointed out, you need to release resources in finally block:
HttpClient httpclient = new DefaultHttpClient();
//... code skipped
String responseString = "";
try {
//... code skipped
} catch (IOException e) {
} finally {
     httpClient.getConnectionManager().shutdown();
}

Comment: The method getConnectionManager() from the type HttpClient is deprecated

Strict Mode complains on resource leak


How is IPsec (strongswan) working without opening ports in UFW?

Question: I needed to setup a site-to-site VPN between servers A and B, where server A is being managed by me and server B is being managed by a client.
Server A is running Ubuntu 20.04 and I am using strongswan to setup the VPN on my end. I am using UFW to manage server A's firewall.
Public IP address of A: 16.XX.XXX.17
Public IP address of B: 14.XXX.XXX.94
Now after making the necessary configuration changes for setting up the VPN and turning it on, I am able to see the following logs in /var/log/syslog
Mar 21 13:58:47 worker0 charon: 01[ENC] parsed IKE_AUTH response 1 [ IDr AUTH N(ESP_TFC_PAD_N) SA TSi TSr ]
Mar 21 13:58:47 worker0 charon: 01[IKE] authentication of '14.XXX.XXX.94' with pre-shared key successful
Mar 21 13:58:47 worker0 charon: 01[IKE] IKE_SA s-to-s[1] established between 16.XX.XXX.17[16.XX.XXX.17]...14.XXX.XXX.94[14.XXX.XXX.94]
Mar 21 13:58:47 worker0 charon: 01[IKE] scheduling reauthentication in 2644s
Mar 21 13:58:47 worker0 charon: 01[IKE] maximum IKE_SA lifetime 3184s
Mar 21 13:58:47 worker0 charon: 01[IKE] received ESP_TFC_PADDING_NOT_SUPPORTED, not using ESPv3 TFC padding
Mar 21 13:58:47 worker0 charon: 01[CFG] selected proposal: ESP:AES_CBC_256/HMAC_SHA2_256_128/NO_EXT_SEQ
Mar 21 13:58:47 worker0 charon: 01[IKE] CHILD_SA s-to-s{1} established with SPIs c97fea32_i f60175ca_o and TS 10.132.86.142/32 === 10.128.28.96/27
Mar 21 13:58:53 worker0 charon: 14[NET] received packet: from 14.XXX.XXX.94[4500] to 16.XX.XXX.17[4500] (80 bytes)
Mar 21 13:58:53 worker0 charon: 14[ENC] parsed INFORMATIONAL request 0 [ ]
Mar 21 13:58:53 worker0 charon: 14[ENC] generating INFORMATIONAL response 0 [ ]
Mar 21 13:58:53 worker0 charon: 14[NET] sending packet: from 16.XX.XXX.17[4500] to 14.XXX.XXX.94[4500] (80 bytes)
Mar 21 13:58:58 worker0 charon: 07[NET] received packet: from 14.XXX.XXX.94[4500] to 16.XX.XXX.17[4500] (80 bytes)
Mar 21 13:58:58 worker0 charon: 07[ENC] parsed INFORMATIONAL request 1 [ ]
Mar 21 13:58:58 worker0 charon: 07[ENC] generating INFORMATIONAL response 1 [ ]
Mar 21 13:58:58 worker0 charon: 07[NET] sending packet: from 16.XX.XXX.17[4500] to 14.XXX.XXX.94[4500] (80 bytes)
Mar 21 13:59:03 worker0 charon: 05[NET] received packet: from 14.XXX.XXX.94[4500] to 16.XX.XXX.17[4500] (80 bytes)

Output of ipsec status:
Security Associations (1 up, 0 connecting):
   s-to-s[1]: ESTABLISHED 5 minutes ago, 16.XX.XXX.17[16.XX.XXX.17]...14.XXX.XXX.94[14.XXX.XXX.94]
   s-to-s{1}:  INSTALLED, TUNNEL, reqid 1, ESP SPIs: c97fea32_i f60175ca_o
   s-to-s{1}:   10.132.86.142/32 === 10.128.28.96/27

The ufw status
Status: active

To                         Action      From
--                         ------      ----
666                        LIMIT       Anywhere                   # For ssh
62626                      ALLOW       Anywhere                   # For wireguard
Anywhere on pv0            ALLOW       Anywhere
666 (v6)                   LIMIT       Anywhere (v6)              # For ssh
62626 (v6)                 ALLOW       Anywhere (v6)              # For wireguard
Anywhere (v6) on pv0       ALLOW       Anywhere (v6)

How is the server able to receive packets on 4500 port (according to the ipsec logs in /var/log/syslog) without me opening that port? What am I missing here?
I have not touched IP tables directly at all.
I have verified by running a simple http server on 8000 port (using python3 -m http.server) that I am not able to access other unopened ports from outside the server)
Answer: ufw is not the sole firewall module present in the system, it merely controls its own chain(s) in the global INPUT iptables/nftables chain. You can verify that the required rules are installed by running iptables -S on server A, you should see that there are some ACCEPT rules for UDP:4500 somewhere reachable from INPUT.
Alternatively, there is more than one routing/filtering table, and while ufw operates on "general" table (IIRC index 254) VPN systems usually allocate one of the tables with a smaller number (200 seems to be a common choice) and set up traffic that's subject to VPN control to be routed/filtered by that table. Verify by running nft list tables, then you can inspect a table by running nft list ruleset table (table). Check with your man pages for exact syntax please.
Answer: According to the log, the host is acting as client, not as server. That is, it is initiating the IKE_SA and sending the first message. Outbound connections are usually not blocked, by default. Check the default policies on your host with ufw status verbose.


'Get-Content' fails from a file in a shared folder?

Question: The script below works like a dream on a local drive:
 $File = 'c:\scripts\File.reg'
 $Content = Get-Content -Path $File |
 ForEach-Object {
    $_ -replace 'user',$ENV:USERNAME
 }
 Set-Content -Path $File -Value $Content

How can I get this script to work for a file found on a shared drive ?
Obviously this does not work:
 $File = '\\server\sharedfolder\file.reg'
 $Content = Get-Content -Path $File |
 ForEach-Object {
    $_ -replace 'user',$ENV:USERNAME
}
 Set-Content -Path $File -Value $Content

I'm just right clicking on the ps1 file and running with powershell, I get this error:

"Get-Content : Cannot bind argument to parameter 'Path' because it is
  null.  At C:\users\bob\desktop\script.ps1:2 char:30
  +$Content = Get-Content -Path $file |
Comment: Your code should work fine, PS has no issues with UNC paths and should be able to read a file from a share (assuming you have permissions to access it!) in the same manner it does from a local drive. What error do you get with your code?
Comment: Why "obviously this does not work"?
Comment: There is no **"Obviously"**. You need to tell us what happens when you try it. Are you trying to run this as a service or scheduled task, where the process is likely using a different user account?
Comment: You guys are definitely correct. Allow me to make amends. The error message  that I get  is added to my original question.
Comment: However the `$file` variable is constructed, the result is empty and does not contain the shared folder path you think it does
Answer: Because you are handling files with regextension, I suspect you are running your code from Registry provider. In that case you have to specify the Filesystem provider in your UNC path: (notice double colon)
$File = 'Filesystem::\\server\sharedfolder\file.reg'

Answer: What is in your file...
The code should work as is. If not something else is amiss.
Example:
PS C:\Scripts> ($file = '\\fs01\Data\New Text Document.txt')

\\fs01\Data\New Text Document.txt

PS C:\Scripts> Get-Content -Path $File

New text doc

user
user1
2user

PS C:\Scripts> $Content = $null

PS C:\Scripts> $Content

PS C:\Scripts> $Content = Get-Content -Path $File |
ForEach-Object {
$_ -replace 'user',$ENV:USERNAME
}

PS C:\Scripts> $Content
New text doc

Administrator
Administrator1
2Administrator

PS C:\Scripts> $File

\\fs01\Data\New Text Document.txt

PS C:\Scripts> Set-Content -Path $File -Value $Content

PS C:\Scripts> Get-Content -Path $File

New text doc

Administrator
Administrator1
2Administrator


Transpose Present Value of an Ordinary Annuity Formula for Interest Rate

Question: I'm having trouble transposing the formula for Present Value of an Ordinary Annuity in order to find the interest rate. The formula is:

Where
P=Present Value of an Ordinary Annuity
PMT=Payment
i=Interest Rate
n=Number of Terms
Not sure if it helps, but I managed to simplify the formula to this:

Thanks in advance.
Answer: It exists no closed-form expression for $i$ if $n>1$. Let $1+i=q$, your second equation becomes
$P=PMT\cdot \frac{q^n-1}{(q-1)\cdot q^n}$
Multiplying both sides by $(q-1)\cdot q^n$
$P\cdot (q-1)\cdot q^n=PMT\cdot (q^n-1)$
Multiplying out the brackets
$P\cdot q^{n+1}-P\cdot q^n=PMT\cdot q^n-PMT$
$P\cdot q^{n+1}-(P+PMT)\cdot q^n+PMT=0$
This is a polynomial with a degree of $n+1$. For $n=1$ it is a quadratic equation. It can be solved by using the quadratic formula. For $n=2$ the cardano formula can be maybe used. But for $n>2$ there exist no closed-form formula. In general you have to apply an approximation method, for instance the Newton-Raphson method.