store/load numpy array from binary files

Question: I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix.
def saveArrayToFile(data, fileName):
    with open(fileName, 'w') as file:
        a = array.array('f')
        nSamples, ndim = data.shape
        a.extend([nSamples, ndim]) # write number of elements and dimensions
        a.fromstring(data.tostring())
        a.tofile(file)

def readArrayFromFile(fileName):
    _featDesc = np.fromfile(fileName, 'f')
    _ndesc = int(_featDesc[0])
    _ndim  = int(_featDesc[1])
    _featDesc = _featDesc[2:]
    _featDesc = _featDesc.reshape([_ndesc, _ndim])

    return _featDesc, _ndesc, _ndim

An example on how to use the functions is:
myarr=np.array([[7, 4],[3, 9],[1, 3]])
saveArrayToFile(myarr,'myfile.txt')
_featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt')

However, an error message of 'ValueError: total size of new array must be unchanged' is shown. My arrays can be of size MxN and MxM. Any suggestions are more than welcomed.
I think the problem might be in the saveArrayToFile function.
Best wishes,
Javier
Answer: Use numpy.save (and numpy.load) to dump (retrieve) numpy arrays to (from) a binary file.
Comment: @Javier: I could understand why you might want to save the dimension of the array in say the first few bytes of the file if you wanted to grab that data without reading the entire file. However, `_featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt')` suggests you are reading the entire file (no peeking at header bits). So why not simply use `arr=np.load(...)`, and then `_ndesc,_ndim = arr.shape`?
Comment: OK, thanks! however, I really need to store the MxN dimension of the array into the file.
Comment: Would it be sufficient to name the file something like `myfile_MxN.npy`?


join using two column in sql

Question:     ProjectMaster
     ProjectID ITManagerID DevelopmentManagerID

--------------------------------------------------
        1         1000         1001

     UserTable

     UserID UserName
     ----------------
      1000   Sam
      1001   Ram

    Result
      Project   ItManagerName DevManagerName
------------------------------------------------
        1          sam          ram

Help to write query
Edit:
I tried
select
    projectid,projectName,projectdescription,startdate,enddate,
    apsmanagerid,projectmanager,ragstatus,projectstatus,projectpriority,
    categoryid,inactivedate,comments,it.userName AS ITProjectManagerName,
    dev.userName as DevManagerName
from pmis_project p,pmis_user It,pmis_user dev
where p.DevprojectManager = It.userid
  and p.ITmanagerid = dev.userid
  and p.projectid IN (Select Projectid from SelectedProject)

Answer: You can JOIN a table as many times as needed.
In this case

one JOIN to Users to get the ITManager's name.
one JOIN to Users to get the DevManager's name.

SQL Statement
SELECT  ProjectID
        , ITManagerName = m.UserID
        , DevManagerName = d.UserID
FROM    ProjectMaster pm
        INNER JOIN UserTable m ON m.UserID = pm.ITManagerID
        INNER JOIN UserTable d ON d.UserID = pm.DevelopmentManagerID

Answer: You can include the same table multiple times in the FROM clause of a SELECT query. If you're doing this, you frequently want to introduce an alias for one or more of these tables, so that they can be referred to in the rest of the query. You introduce an alias by adding AS alias after the name of the table, e.g.:
SELECT
    *
FROM
    Table As t
WHERE
    t.Column = 'x' --<-- using the alias here

(the AS is actually optional)
Joining tables in a FROM clause is performed by using the JOIN keyword, and placing the conditions for the join in the ON:
FROM
    Table1 t1
        inner join
    Table2 t2
        on
             t1.ColumnA = t2.ColumnB

Answer:
SELECT * FROM ProjectMaster PM
  INNER JOIN UserTable UT ON UT.UserId = ITManagerId
  INNER JOIN UserTable UT1 ON UT1.UserId = DevelopmentManagerId

join using two column in sql


Minimum sample size to observe certain outcomes

Question: Given a categorical random variable with large number of possible outcomes and a sufficiently large sample, I observe that 90% of the sample falls into some relatively small number of categories, say, 30 out of 1000. How can I estimate minimum sample size such that these 30 categories are observed?
A sort of a solution is, I guess, to produce smaller datasets resampling with replacement from the original one.
Comment: A particular set of 30 categories, or at least 30 different unspecified categories? What is your goal? What kind of statistical analysis is planned?
Comment: @RussLenth Yes, a particular set of 30 most frequent categories. I'd like to merge the remaining categories into 'others', for the purpose of doing $\chi^2$ tests and stuff.
Comment: What are the probabilities of the 5 or so least frequent categories? Are you sampling from your dataset, or collecting new data?
Comment: @RussLenth Counts of the least frequent categories are 1. Original post is really a simplified description, actually I have thousands of categories and nearly 1/3 of them are observed once in 3 million sample. If the exact numbers are important, I can look it up.
Comment: @RussLenth I would like to estimate sample size when collecting new data. What I would like to do is to compare new samples to the original one, but using only most frequent categories + 'others' to avoid sparsness introduced by categories with low counts.
Comment: Sorry I meant the least frequent 5 or so from among those 30 key ones.
Comment: @RussLenth Oh, ok. In the actual sample I have 30000 categories, out of which top 1000 sums up to 90% of the sample. Least frequent categories have frequencies around 250/3000000.
Answer: With the probability you provided of $250/3000000 = 8.33 \times 10^{-5}$, then in order to have a 99% probability of obtaining at least one observation in that category, you need $n \ge -\ln(1-.99) / (250/3000000) \approx 55300$.
However, to do $\chi^2$ tests and such, you generally want at least 5 observations in each category (the standard rule of thumb). You have less than half a chance of that happening with only $55.3$K observations. By experimenting, I was able to find that with $n=140,000$ observations, you have a bit more than a 99% chance of having at least 5 observations in that category.
Perhaps these sample sizes are larger than what you expected? Well, it isn't easy to collect enough data to do a $\chi^2$ test on 31 categories. Maybe you need to reduce your requirements...
Comment: So, in general, to estimate minimum sample size I need to calculate $-{ln(1-\alpha)\over \hat p}$? Could you please point out where this formula comes from?
Comment: It comes from the Poisson approximation and solving $.99 := P(X>0) = 1 - e^{-np}$


Replacing some values in a column based on another df with the same columns R

Question: I would like to swiftly replace NA values in the vector id in first df based on x0 column value in second df without long steps of merging and deleting columns. In other words x0 is the common record identifier. Simple example is following:
first <- data.frame(x0=1:5,
                     x3=90:94,
                     id=c("a1","a2","a3",NA,NA))`

  x0 x3   id
1  1 90   a1
2  2 91   a2
3  3 92   a3
4  4 93 <NA>
5  5 94 <NA>`

second <- data.frame(x0=4:8,
                     x2=seq(104,108,1),
                     id=c("a4","a5","a6","a7","a8"))`

  x0  x2 id
1  4 104 a4
2  5 105 a5
3  6 106 a6
4  7 107 a7
5  8 108 a8`

The expected result would be:
  x0 x3 id
1  1 90 a1
2  2 91 a2
3  3 92 a3
4  4 93 a4
5  5 94 a5`

Answer: You are looking for a update-join or a gap-fill-join which could be done like:
first$id  <- as.character(first$id)
second$id  <- as.character(second$id)

idx <- match(first$x0, second$x0) #Update join
idxn <- which(!is.na(idx))
first$id[idxn]  <- second$id[idx[idxn]]
first
#  x0 x3 id
#1  1 90 a1
#2  2 91 a2
#3  3 92 a3
#4  4 93 a4
#5  5 94 a5

Comment: Perfect, did exactly what I needed! Thank you


Turbo C not working in my laptop

Question: I just bought a Dell laptop and Windows 8.1 Pro is installed on it. I want to run Turbo C on my laptop (x64 build).  When I install and run a program in Turbo C it shows output only once then my cursor stops working. I try to click on Run or compile in turbo c menu nothing happens. It appears like my click is not affecting anything. I have tried Windows 7 also and the same thing is happening. And I have tried all the versions of Turbo C.
Comment: How about the 'not Turbo C' version?
Comment: you say x64 build... I assume you mean your laptop is a 64 bit laptop, which pretty much would seem to answer the question assuming you mean Turbo C, the classic tool from the 90's which is a 16 bit app and therefore probably won't work under Windows 7/8 on 64 bit
Comment: actually, a quick google shows I'm probably wrong and you did mean Turbo C for Windows which is in fact supposed to work on Windows 8.  Yowsers...
Comment: There is 32-bit Turbo C, but nobody knows how it survived the K-T event.
Comment: okay You mean to say that it wont work in my laptop. But i am confused it installed properly and i run a " hello world" program. it showed the output but after the that i wasnt be able to run it again. its is happening with all the versions i install, this same thing.
Comment: wHat i am suppose to do now?? please tell
Comment: Learn C and C++ on latest available compilers. For windows you can go for MinGW GCC or Microsoft Visual C++. Even if your school/college is using TurboC or BorlandC suggest them to switch to newer version, as its decade old and full of bugs and non-standard stuff. AT SO don't expect somebody answering TurboC question. SO community hates this.
Comment: Yes , in my college they are still using Turbo c or Older version compilers. I agree with you i should switch to new Compilers.
Comment: Somehow i want to run C compiler in my laptop. And i am helpless to do so.
Comment: Just to make sure I understand, you're trying to run a program from within Turbo C, and when you do it locks up?  Is it just locking up the Turbo C application, or the whole system?  Are you sure there isn't a problem in the program you are trying to run (such as an infinite loop)?  Have you tried to run it outside of Turbo C?
Comment: Only My Turbo c Lock up And i can only use my keyboard just to write and i have run a simple "hello world" program to check all the versions.@JohnBode
Answer: Try to install the 64 bit version of Turbo C if you haven't already. If that isn't an option, you might be able to get it to work by running in compatibility mode.
Right click the icon -> Properties -> Compatibility then select Run this program in compatibility mode for Windows XP.
Answer: Dont worry. Just press
Alt+Space and then press enter.
With this we are giving repaint desktop command, which is available in drop down menu left to file menu.
Answer: Install dosbox from here and then follow the tutorial here
DOSBox can run old MS-DOS software on modern computers which would not work otherwise, because of incompatibilities between the older software and modern hardware and operating systems.
Turbo C is a 16 bit software,you are trying it on a 64 bit OS
Comment: Then i suggest you to go for MS Visual C++
Comment: If i use Visual C++. Is there a difference in coding?
Comment: No. Infact  you will love coding on it. You can easily switch over to it and I suggest that you should. Because its an IDE. :)
Comment: @SamDunk, MS Visual C++ doesn't support many features of C99, is not the appropriate compiler for C.
Comment: @AkshitVerma Do you aim using it for educational programming or professional development?
Comment: @AkshitVerma Then don't think much,just install Visual Studio and have a good coding time :)

Turbo C not working in my laptop


passing function into function java

Question: I'm working on implementing some basic Computational Mathematics in Java. One method for finding the roots of a function f(x) (where roots are the values xi where f(xi) = 0) is the Newton-Rhapson method. To implement in Java I first created a basic class (class to contain Newton-Rhapson method) and some definition of a function f(x):
public class CompMaths {

    public double Newton(double x)  {
        //find root of f(x)
    }

    public double f(double x)  {
         //definition of f(x)
    }

}

In doing so, if I want this to be compatible with any definition of f(x) that a user wants, i.e. say f(x) = x^2 , f(x) = x*sin(x) , I would have to create a separate class for each definition of f(x) that would also have to contain the definition of Newton-Rhapson method (and the many others comp math methods I need to implement). This seems overkill. Also, it exposes my CompMaths class to the user and I don't want that. Instead it would be great to be able to define each function and just 'pass it in' i.e
public double Newton(double x, f(x)) ...

This, as I'm sure everyone knows is not supported by Java. My initial thought was, well what if you passed in an object that had a definition of f(x), call it Func, i.e
public double Newton(double x, Func func) ...
So initially I thought that this wouldn't be the best solution as I would have to have multiple definitions of CompMaths for each different Func like object. And that would obviously be ridiculous, and is simply inverting the problem from before. To overcome this, I thought, "Well I want multiple different definitions of a function f(x) using a sole class definition Func. And one solution that came to mind was - Make Func abstract with an abstract method f(x) i.e.
public abstract class Func {

   public abstract double f(double x);
}

So now I simply have to create separate classes for each function that extend Func and have their own separate definitions of f(x), some examples  for f(x), call them f1(x)=x^2 and f2(x) = x - sin(x^2) i.e.
public class f1 extends Func {
  @Override
  public double f(double x) {return x*x;}
}

public class f2 extends Func {
  @Override
  public double f(double x) { return x - Math.Sin(x*x);}

}

Now if I want to use either f1 or f2 in the Newton method I use
double x1 = 3, x2 = 4;
CompMaths compMaths = new CompMaths();
compMaths.Newton(x1, new f1());
compMaths.Newton(x2, new f2());

This seems to work incredibly well (note - could define Newton as static to avoid having to create the CompMaths object). The user need only create their functions by extending Func and defining their own f(x). Nothing about the CompMaths class is exposed whatsoever as well. So I'm happy, but in no way do I consider myself an expert whatsoever, so I thought I would present to see what people think, and to see if there was a better approach.
Any comments would be greatly appreciated.
Thanks, David
Comment: This belongs over at codereview stack exchange...
Comment: I'm not entirely sure what you're asking here.  Are you asking about functional programming?  That's become a recent addition to Java.  Are you asking for a review of what you've written?  If so, please submit for a [Code Review](https://codereview.stackexchange.com/).  Is it something else?  Then please edit your question to make this clearer.
Comment: There is no question here. You should use an interface rather than an abstract class. Among other advantages, that would allow passing a lambda: `compMaths.Newton(x1, x -> x * x)` or a method reference: `compMaths.Newton(x1, Math::sqrt)`. There is already such an interface, BTW: DoubleUnaryOperator. You should also learn and respect the Java naming conventions.
Comment: Hi guys, many apologies for the lack of clarify, I will edit my post.
I posted to see if my mode of thought on the situation was correct. The code presented was part of it.
I'm not sure if that constitutes Code Review? I'm very new to this and am ignorant to a lot of the terminology (I will correct that).
Comment: Will in future do posts of this nature in codereview stack exchange. Thanks for letting me know.
Answer: Why not use the existing Function interface of Java 8 to define your newton method?
public double newton(double x, Function<Double,Double> f) {
    ...
}

and call it with lambda expressions :
double x1 = 3, x2 = 4;
CompMaths compMaths = new CompMaths();
compMaths.newton(x1, x -> x * x);
compMaths.newton(x2, x -> x - Math.sin(x*x));

EDIT: As JB Nizet commented, if all your functions take a double parameter and return a double value, it would be more efficient to use a DoubleUnaryOperator instead of a Function<Double,Double>, since DoubleUnaryOperator operates on a primitive type, so no boxing/unboxing is involved.
Comment: I'd use a DoubleUnaryOperator instead.
Comment: @JBNizet That would certainly be more efficient for the specific example in the OP's question.
Comment: I wasn't aware that existed, thanks for the comment, I will adapt to use that instead. Thanks again.

passing function into function java


How to enable WYSIWYG in a text field summary?

Question: I have a body field (Text field with summary) with WYSIWYG CKeditor enabled.
However, the "summary" part of the field lacks a WYSIWYG editor.
How can I enable it?
Comment: Under your content type -> manage fields for the summary field you can enable text processing to be filtered text (user selects input format).
Comment: @zarsiwala, you should post this as an answer to the question; it'll help your reputation and the organization of the site.
Comment: Here's a recent blog post that solves this problem: [Drupal 7: How to Add a WYSIWYG Editor to a "Text with Summary" Field](http://theunraveler.com/blog/2012/drupal-7-how-add-wysiwyg-editor-text-summary-field)
Answer: The WYSIWYG module's logic acts on text fields with input formats, if you want to explicitly target a form element by its ID you can use the CKEditor module instead.
Answer: Under your content type -> manage fields for the summary field you can enable text processing to be filtered text (user selects input format). Hope that helps.
Comment: It seems to refer to the main field, not to the summary. At least, I have it already set to be filtered and have the WYSIWYG editor only in the main field (not in the summary).
Answer: I had created my own summary field in CCK. I use the CKeditor and this only worked after I realised I had to configure the field as a multiline text area and not as a single line text field.
Answer: I just tried WYSIWYG module version 7.x-2.x-dev with CKEditor (the editor, not the Drupal module), and it actually worked -- the summary field now displays with a wysiwyg editor instead of the plain textarea.
Answer: If you are using the wysiwyg module you can enable/disable this in the wysiwyg profile settings. It's in the fieldset at the bottom: «Basic settings - Enable on summary fields».


jQuery selector differences after page refresh

Question: When the page is first loaded the snippet below alerts the correct value. If I F5 the page however I get an alert of the first option in the select, which is not the correct value. If I put the cursor in the URL bar and hit Enter then I again get the correct value.
This snippet comes out of the idealforms.js file which isn't working properly and I'm trying to correct it. It's possible that this issue influenced from somewhere else in the code but I have my doubts.
Any idea why this is happening, does a page refresh somehow behave differently then when the page is first loaded?
form.find('select').each(function () {
    var select = $(this);
    nu_title = select.find(':selected').html();
    alert(nu_title);
});

Comment: You have an extra `}`on the end of your code, is that a typo or is it in the real code?
Comment: What browser are you using? With Firefox, form fields remember the value you entered even on a refresh of the page so you can get unexpected results. You have to navigate to the page again to have a real "refresh" of form fields.
Comment: @bfavaretto it's a typo, omitted now
Answer: On some browsers after F5, values filled in forms stay. CTRL+F5 (or re-entering the page from the url bar, like you suggested) should clear those under most settings.


What is the interpretation of the eigenvectors of the jacobian matrix?

Question: I'm trying to think about the jacobian matrix as a abstract linear map.
What is the interpretation of the eigenvalues and eigenvectors of the jacobian?
Comment: I think you cannot obtain a good interpretation since that linear map (usually called the tangent map) is between different vector spaces (tangent spaces, even of distinct dimensions), therefore not a linear operator.
Comment: You can think of where the unit sphere in the tangent space of the domain gets sent, and the eigenvalues give you some measures of that image.
Comment: But on Riemannian manifolds you work in terms of orthonormal basis of the range and domain.
Comment: There isn't a computational edifice that has no meaning, just sometimes it's meaning is subtle.
Answer: Suppose that $F:M\rightarrow N$ is a smooth mapping of Riemannian manifolds, with $F(p)=q$.  Let $<\ , \ >_p$ and $<\ , \ >_q$ denote the metrics in $T_pM$ and $T_qN$.
We can define a bilinear pairing on $T_pM$ by $B(\vec{v},\vec{w})=<DF_p(\vec{v},DF_p(\vec{w})>_q$.  Assuming we used orthonormal bases at $T_pM$ and $T_qN$ to express the matrix for $DF_p$, this is the same as $<DF_p^tDF_p(\vec{v}),\vec{w}>q$.  The matrix of the pairing with respect to the basis at $T_pM$ will be the matrix $DF_p^tDF_p$.  By Lagrange's theorem we can find an orthogonal matrix $P$ so that $P^t(DF_p^tDF)P$ is diagonal. The diagonal entries of that matrix are the eigenvalues of $DF_p^tDF_p$.  They tell you how much the mapping $F$ is distorting distances near $p$, as you map into $N$.
It isn't exactly the eigenvalues of $DF_p$, but you could say things about the eigenvalues of $DF_p^tDF_p$ in terms of the eigenvalues of $DF_p$.
Admittedly it's not pithy and aha.  But it is an understanding of how the eigenvalues of the matrix $DF_p$ are reflected in the local geometry.
Comment: Notice that $DF^t_pDF_p$ and $DF_pDF^t_p$ are square. The smaller of the two is the pertinent one. The norm of $F$ at $p$ is the determinant of the smaller one.  It plays a central role in the geometric interpretation of certain integrals via the {\em coarea formula}.
Answer: What Frank Science has said in the question comment above is right. I'm simply expanding on his comment here:
Since the Jacobian has eigenvectors, it is square i.e. the input and output space have same dimensions. If there is some kind of natural interpretation to the input and output basis and they can be mapped to each other, the eigenvectors of the Jacobian represent those directions in the input space, where if you move locally (small amount), you move in the same direction in the output space. This interpretation is no different from that of the eigenvectors of any matrix. The only addition is that of local (small) movement, because the Jacobian approximates the original function locally.


Dpkg force stop after preinst

Question: I build my own package and I need to check something on the system before the install process.
So in my dpkg I add a preinst script which is written as follow. As an example I want to check if the arduino-cli command is available:
echo 'Check arduino cli install ...'
if ! command -v arduino-cli &> /dev/null
then
   exit 0
fi

The postinst script seems to be execute. Here is the result of the dpkg execution:
....
dpkg: error processing archive myserver-server_0_amd64.deb (--install):
...

How can I stop the other script ? I thought the exit command should work.
https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html
Comment: It is ugly and not done for such things. I think you should consider to reframe your problem and solve it properly. `arduino-cli` should come from a package, so just depend your package from such arduino package. Else you are abusing the system, so you never know if it will work on all cases (e.g. you can always `force` ignoring errors). `exit 0` will just exit the script without errors. Just exit with an error if you want to let caller known you raise an error
Comment: Thank you for the answer. What do you mean by exit "Just exit with and error". I try to replace with "exit 1" an error occurded but the other post scripts are still running.
Comment: Yes. Each package is independent. You are trying to do something that should not be done by packaging software. And personally I find no reason to do what you are trying to do. For this reason I asked you to reconsider, and try a different way (in other words, I think it is XY problemL you have a problem, but you are trying to solve in the wrong place).
Comment: As an aside, `&>` is not available in `sh` scripts; you want `>/dev/null 2>&1`
Answer: Agreed with what was said in comments.
Stopping an installation is not the way to go, instead assist the user at the maximum in order to install your package correctly.
Why asking people to install things manually while you can automate it?
Thus:

Add the dependency to the debian/control file

OR

Add curl dependency to the debian/control file
Modify your existing code to install arduino-cli by using

    if ! command -v arduino-cli &> /dev/null
    then
       curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | sh
    fi

Dpkg force stop after preinst


What's included in the base image?

Question: FreeBSD has some software included in the "base system", and optional software can be installed from pkg and the ports collection. What exactly is included in the base system? Is the list maintained somewhere?
Answer: FreeBSD base system is a binary distribution, and best representation of its contents is a source tree. You can go up and under the base select releases and see contents of a particular release. There's an ongoing effort to make base system contents available as FreeBSD packages and this is somewhat working with FreeBSD 11, but with some reservations.

What's included in the base image?


Xamarin Forms Unit Testing a Command

Question: I am trying to unit test a Command in Xamarin.Forms.
I have my view-model class as an example like this
public class CarViewModel
{
    public Command SelectedCommand { get; } => new Command(OnSelected);

    public Car SelectedCar
    {
      get { return _selectedCar; }
      private set { _selectedCar = value; }
    }

    private void OnSelected(object obj)
    {
      if (obj is Car car)
      {
        SelectedCar = car;
      }
    }
}

This class is the BindingContext for my view and the SelectedCommand above is fired when user taps on a ListView item, so it is a method that is bound to a Command in XAML using a TapGestureRecognizer like
<TapGestureRecognizer Command="{Binding SelectedCommand}" .../>

I am trying to unit test this class, so my CarViewModel class is subject under test (SUT) inside my test.
I just started looking at mocking libraries / isolation frameworks and I see Moq is quite popular.
My questions are:

Since I dont have any dependencies in my CarViewModel below, I dont think I need to mock that class in my test.  It is subject under test which to my understanding should not be mocked.  Only dependencies should be mocked.  Is this correct?
How do I unit test to confirm that my SelectedCommand has been called and that it has set SelectedCar property?  If I am right in 1 above, then Moq is not even needed to test this since I have no dependency to mock for my CarViewModel class.
Answer: Based on the current code in the example provided there really is no need to mock anything.
Execute the command on the SUT with a known parameter and verify the expected behavior via the SelectedCar.
[Test]
public void SelectedCommand_Should_Set_SelectedCar {
    // Arrange
    var expected = new Car();
    var subject = new CarViewModel();

    // Act
    subject.SelectedCommand.Execute(expected);

    // Assert
    var actual = subject.SelectedCar;
    Assert.AreEqual(expected, actual);
}

Xamarin Forms Unit Testing a Command


I've recently had a power cut, now all my guitar and bass amps are making a humming/buzzing noise?

Question: I recently had a power cut in my area this Monday just gone, power was restored quickly, in about 5 seconds. However now whenever I go to plug in and turn on any of my amplifiers in my studio or anywhere in my house for that matter they are all making a humming/buzzing noise without the guitars plugged in. What's even stranger is that I had both my electric and bass amp plugged into the mains (on at the mains but the amps were off) however my acoustic guitar amp wasn't plugged into anything and is still making the same noise. This wasn't a problem before the power cut, I'm assuming this has something to do with there being too much voltage going around the house but that's just a wild guess. My studio in question was a contracted build so the electrics were fitted by professionals, also worth mentioning the power cut wasn't just localized to my house. Everything else in the studio (equipment wise) is working fine, I was actually working on the studio computer when the power went out and I writing this question from it. My KRK Rokit 6's (studio monitors) are fine and are not buzzing, my external sound card, a Focusrite Saffire Pro 40 is fine. This issue only seems to be affecting guitar amplifiers.
The amplifiers in question are:
Peavey Vypyr 15w modeling amplifier
Wuhan Eleca Eleconics AB-30 30w bass amplifier
Fishman Loudbox Mini acoustic guitar amplifier
Thanks for reading and I look forward to hearing your responses to this problem if you have any solutions. :)
*Also if you have any other questions feel free to ask them!
Comment: I'd check in some other place to find out if it's your mains related. Could be in theory some ground wiring issue but that's just a wild guess. If your gear seems ok in other places I'd call electrician to check things out as that might indicate some problems with your mains wiring that can be actually dangerous
Comment: Sounds like a call to your electricity supplier is in order.UK juice is normally unproblematic - I've had no problems in over 50 yrs. Try unplugging everything else in the house/studio. There may be another appliance that's gone faulty and is causing problems. A multimeter will tell you how many volts are available - normally between 230 and 240. Doubt it's over-voltage.
Comment: Your amps haven't changed, your power supply has. Any chance you are running on a backup generator or battery backup now? Either one of those would most likely inject a lot of noise into the power supply, which can leak into the audio path of the amp. Also, have you made any changes to your guitar?
Comment: Thanks Todd, I don't think it has anything to do with the guitars in general, like i said they're making noise without even having the guitars plugged into them. I also don't have any other generators or power supply, running purely on the mains electricity. I should probably also mention I am based in England, UK. So the way you set things up will probably be a bit different.
Answer: My first instinct would say its unrelated to the outage and more likely a ground loop issue. Have you tried taking your amp to another part of the house (or at least a new outlet) and trying to plug it in and see if it still makes the same noises?
I know there are some product from EbTech and Furman (plenty others too) that are suppose to condition or eliminate ground loop hum. The HumX by Ebtech is expensive, but has some magic I have yet to be able to figure out.
Anyway, try a new outlet in a different room. Try it without fx pedals or even without a chord plugged in the input jack, and you can, from there, eliminate the source of the problem.
Answer: Talk to your power company.  Sounds very like whatever alternative power supply took over after the outage is poor quality.
Answer: The first thing I would check is to take one of the amps that buzzes to another location, perhaps another neighborhood, plug it in and see if it still buzzes there. That might give you a clue as to whether the problem is in the amplifier or whether the problem is in the house power. Either way, I'd recommend having a professional help you sort it out. Also, keep in mind, it's possible that both the house power and the amplifiers are now afflicted. An extreme voltage spike can do a lot of damage.


Joining two tables with date ranges

Question: I have two SQL tables that contain start and end dates.
 Table 1: Name, AddedDate
 Table 2: Name, RemovedDate

I'm am looking to join these two tables and dump the data into a temp table to show when a name was added and removed from a list.

The same name may have been added and removed multiple times.

Desired Output Example
- Name, AddedDate, RemovedDate
- Jane, 2017-02-01, 2017-02-03
- Bill, 2017-01-28, (blank)
- Mike, 2017-01-15, 2017-01-19
- Jane, 2017-01-13, 2017-01-14

Can someone please help? Thanks.
Comment: Possible duplicate of [MySQL LEFT JOIN?](http://stackoverflow.com/questions/12438392/mysql-left-join)
Answer: Another option is an OUTER APPLY (If SQL Server)
Example
Declare @Table1 table (Name varchar(25),AddedDate date)
Insert Into @Table1 Values
('Jane', '2017-02-01'),
('Bill', '2017-01-28'),
('Mike', '2017-01-15'),
('Jane', '2017-01-13')

Declare @Table2 table (Name varchar(25),RemovedDate date)
Insert Into @Table2 Values
('Jane', '2017-02-03'),
('Mike', '2017-01-19'),
('Jane', '2017-01-14')

Select A.Name
      ,A.AddedDate
      ,B.RemovedDate
 From  @Table1 A
 Outer Apply (
                Select RemovedDate=min(RemovedDate)
                 From  @Table2
                 Where Name=A.Name
                  and  RemovedDate>=A.AddedDate
             ) B

Returns
Name    AddedDate   RemovedDate
Jane    2017-02-01  2017-02-03
Bill    2017-01-28  NULL
Mike    2017-01-15  2017-01-19
Jane    2017-01-13  2017-01-14

Comment: Nice job deriving the input from the output. +1
Comment: @SqlZim Pretty much mastered Copy-and-Paste.  After all, I'm a coder  :)
Comment: @CST1126 Happy it helped
Comment: @CST1126 Just in case. the OUTER APPLY will include null values while a CROSS APPLY will excluded them  i.e. Bill
Answer: Using correlated subquery to consider only the last time the name was added (and potentially removed)...
select Name,
       AddedDate,
      (select max(RemovedDate)
         from table_2
        where Name=q1.Name
          and RemovedDate >= q1.AddedDate) as RemovedDate
 from (select Name,
              max(AddedDate) as AddedDate
         from table_1
        group by name) as q1
order by AddedDate desc,
         Name;

Same correlated subquery approach to show every time a name was added and removed...
select Name,
       AddedDate,
      (select min(RemovedDate)
         from table_2
        where Name=q1.Name
          and RemovedDate >= t1.AddedDate) as RemovedDate
 from table_1 t1
order by AddedDate desc,
         Name;

Answer: You could use left join on name
  select t1.name, t1.AddedDate, t2.RemovedDate
  from table1 t1
  left join table2 t2 on t1.name = t2.name
  order by name, t1.AddedDate, t2.RemovedDate

Answer: For SQL Server Use the below script
;WITH CTE
AS
(
    SELECT
        SeqNo = ROW_NUMBER() OVER(PARTITION BY T1.Name ORDER BY T1.AddedDate DESC,T2.RemovedDate DESC)
        T1.Name,
        T1.AddedDate,
        T2.RemovedDate
        FROM Table1 T1
            LEFT JOIN Table2 T2
                ON LTRIM(RTRIM(T1.name)) = LTRIM(RTRIM(T2.name))
)
SELECT
    *
    FROM CTE
    WHERE SeqNo = 1

If you want all the records for a Name, such as if a name was added and removed multiple times and you want each of the dates, then just execute without the
WHERE SeqNo = 1

part

Joining two tables with date ranges


Memcached logrotate file not being installed. Bug with memcached 1.4.2?

Question: My memcached logs are getting huge (in excess of 5GB). This isn't a huge problem in itself.  I can easily remove them.
I've sourced the problem to the memcached 1.4.2 package not installing a logrotate file in /etc/logrotate.d/memcached.  It's listed as being included but when I used apt-file list to get a list of installed files it's not there.  Is this a bug or is memcached supposed to be rotating it's logs some other way?
Answer: I think you are talking about ubuntu package as it is clear from your question (mentioning apt-file).
It seems that memcached package does not come with a logrotate file. I did not find on my system. It is not a big issue because you can create one easily. You can also complain to ubuntu maintainers.
Comment: Yes.  Sorry for not making ubuntu clear.  The logrotate file is listed as being included here: http://www.rpmseek.com/rpm/memcached-1.4.2-1mdv2010.0.i586.html?hl=com&cx=0:-:0:7870322:0:0:0: but maybe thats not relevant to the current package.
Comment: This is rpm package NOT debian/ubuntu package. So, they are not related!


Field Collections & Checkboxes

Question: I am trying to alter a field collection which has a couple of select/ textfields and a checkbox. When the checkbox is checked and another item is added to the form, in the  previous instance the checkbox remains checked. This is the correct behavior and also this is the desired behavior in my case.
If, on the second instance added with "add another item", the user checks the associated checkbox then what I would like to accomplish is to have the previous checkbox unchecked.
Is there way to configure/ alter the checkbox so if we have multiple field collections items added when the user selects a checkbox all the other checkboxes are unchecked ?
Code that alters the field collections part of the form:
        $tenant['field_org_tn_ud']['und']['add_more']['#ajax']['progress']['type'] = null;
        $tenant['field_org_tn_ud']['und']['add_more']['#ajax']['progress']['message'] = null;
        //$tenant['field_org_tn_ud']['und']['add_more']['#attributes']['class'][] = 'add-more-button';
        $tenant['field_org_tn_ud']['und']['add_more']['#value'] = t('Add');
        foreach ($tenant['field_org_tn_ud']['und'] as $delta_k => $user) {
            if (is_numeric($delta_k)) {
                $user['field_org_tn_ud_cp_pre']['und'][1]['#prefix'] = t('
');
                $user['field_org_tn_ud_cp_pre']['und'][2]['#suffix'] = t('
');
                $user['field_org_tn_ud_cp_pre']['und'][3]['#attributes']['style'] = t('margin-left: 5px');
                if ($delta_k > 0) {
                    $user['field_org_tn_ud_email']['und'][0]['value']['#title'] = null;
                    $user['field_org_tn_ud_actions']['und']['#title'] = null;
                    $user['field_org_tn_ud_permission']['und']['#title'] = null;
                    $user['field_org_tn_ud_cp_pre']['und']['#title'] = null;
                }
                $user['field_org_tn_ud_email']['und'][0]['value']['#autocomplete_path'] = t('vf-users-autocomplete');
                $user['field_org_tn_ud_email']['und'][0]['value']['#attributes']['style'] = t('background-color: #FFFFD6; ');
                if ($delta_k > 0) {
                    $user['remove_button']['#prefix'] = t('
');
                    $user['remove_button']['#suffix'] = t('
');
                }
                else {
                    $user['remove_button']['#prefix'] = t('
');
                    $user['remove_button']['#suffix'] = t('
');
                }
                $user['remove_button']['#ajax']['progress']['type'] = null;
                $user['remove_button']['#ajax']['progress']['message'] = null;
                $user['remove_button']['#weight'] = '3';
                //$user['remove_button']['#attributes']['class'][] = 'remove-button';
                $user['remove_button']['#attributes']['style'] = t('');
                $user['remove_button']['#value'] = t('Del');
                if ((isset($form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_cp_pre']['und'][4])) &&
                    ($form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_cp_pre']['und'][5] ==
                    1)) {
                    $duplicate_delta = $delta_k;
                    //dpm($duplicate_delta);
                }
                if (isset($duplicate_delta)) {
                    $user['field_org_tn_ud_actions']['und']['#default_value'] = $form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$duplicate_delta]['field_org_tn_ud_actions']['und'];
                    $user['field_org_tn_ud_permission']['und']['#default_value'] = $form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$duplicate_delta]['field_org_tn_ud_permission']['und'];
                }
                // add custom class to select tags for user
                $user['field_org_tn_ud_actions']['und']['#attributes']['class'][] = t('field-custom-select-user');
                $user['field_org_tn_ud_permission']['und']['#attributes']['class'][] = t('field-custom-select-user');
                // add custom class to input tag for user
                $user['field_org_tn_ud_email']['und'][0]['value']['#attributes']['class'][] = t('field-custom-input-user');
                // hide the parent node field as we are not using it within the Plex demand form
                $user['field_parent_nodes']['#access'] = false;
                $tenant['field_org_tn_ud']['und'][$delta_k] = $user;
            }
        }

field_org_tn_ud_cp_pre - is the checkbox
Initial

After another item is added

Undesired behavior: If the user checks the Copy checkbox for the second item in this field then the 'Copy' checkbox on/ for the first item should uncheck.

On the last image when the second Copy checkbox is selected i would like that the first one to become unchecked.
Thank you
Answer: I have solved this using Drupal behaviors:

Created file plex.js and attached to the form in hook_form_alter()
$form['#attached']['js'] = array(drupal_get_path('module', 'plex') . '/plex.js', );

added a custom class to the checkbox e.g.: form-checkbox-custom. (The checkbox has a default class .form-checkbox so we need to apped it to the 'class' array)
$instance['field_org_tn_ic_cp_pre']['und'][1]['#attributes']['class'][] = t('form-checkbox-custom');

Drupal.behaviors.plex code (paste inside plex.js attached to form in 1. above)
(function($) {
  Drupal.behaviors.plex = {
    attach: function(context, settings) {
      $(".form-checkbox-custom, .form-checkbox").on('change', function(e) {
        e.preventDefault();
        //if ''this' checkbox is checked uncheck all the other checkboxes
        if (this.checked) {
          $(".form-checkbox-custom, .form-checkbox").not(this).prop('checked', false);
        }
      });
    }
  };
})(jQuery);

Done.
Whenever a check box is checked all the other checkboxes will be unchecked. The nice part is that the behavior work for dynamically generated form (field collection) elements (add another item).

Thank you & I hope this helps someone

Field Collections & Checkboxes


Paste a chart from Excel to a specific placeholder in a specific layout. Powepoint 2010

Question: I need to paste multiple charts from excel to powerpoint.
I found some excellent VBA code (mainly on Jon Peltier's site).
Now my powerpoint template has a number of layouts (e.g. with 1 chart occupying most of the slides or 1 chart and one text box in a slide, etc etc).
What I want is the chart to become part of the slide layout so that if I reformat the slide - e.g. I change the layout as in the example given above - the chart will move accordingly.
Currently I am able to paste in the spot where the placeholder is, with right size and everything, but it is not IN the placeholder, it's ON the placeholder (and therefore it stays there if I change layout).
Ideally I would like to be able to choose the layout (from 15) and choose the placeholder in the selected layout (typically I have a title, a footer, and then from 1 to 4 placeholders for charts, images, text or all of the above).
I am not a VBA programmer, I just use a little bit of logic and grab codes which is kindly shared on the net. I have not clue how to identify the proper layout (they have names, but is that the variable?) nor the proper placeholder within the layout (here I do not even know how to identify them).
Any help much appreciated.
DF
In the following, the code I copied here and there (mainly Jon Peltier's site).
Sub ChartToPresentation()
' Set a VBE reference to Microsoft PowerPoint Object Library

Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim PPSlide As PowerPoint.Slide
Dim AddSlidesToEnd As Boolean

AddSlidesToEnd = True

' Make sure a chart is selected
If ActiveChart Is Nothing Then
  MsgBox "Please select a chart and try again.", vbExclamation, _
  "No Chart Selected"
Else
' Reference existing instance of PowerPoint
Set PPApp = GetObject(, "Powerpoint.Application")
' Reference active presentation
Set PPPres = PPApp.ActivePresentation
PPApp.ActiveWindow.ViewType = ppViewSlide
' Reference active slide
Set PPSlide = PPPres.Slides _
(PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)

' Copy chart
ActiveChart.ChartArea.Copy

' Paste chart
PPSlide.Shapes.Paste.Select

' Position pasted chart
' This is the keypoint
' I want to replace this with the selection of appropriate layout
' and placeholder in that layout
PPApp.ActiveWindow.Selection.ShapeRange.Left = 19.56
PPApp.ActiveWindow.Selection.ShapeRange.Top = 66.33
PPApp.ActiveWindow.Selection.ShapeRange.Width = 366.8
PPApp.ActiveWindow.Selection.ShapeRange.Height = 424.62

If PPApp.ActivePresentation.Slides.Count = 0 Then

' Other key point
' can I add a specific layout, for example one named Two Content Layout + takeout
 Set PPSlide = PPApp.ActivePresentation.Slides.Add(1, ppLayoutBlank)
Else
    If AddSlidesToEnd Then
         'Appends slides to end of presentation and makes last slide active
        PPApp.ActivePresentation.Slides.Add PPApp.ActivePresentation.Slides.Count + 1, ppLayoutBlank
        PPApp.ActiveWindow.View.GotoSlide PPApp.ActivePresentation.Slides.Count
        Set PPSlide = PPApp.ActivePresentation.Slides(PPApp.ActivePresentation.Slides.Count)
    Else
         'Sets current slide to active slide
        Set PPSlide = PPApp.ActiveWindow.View.Slide
    End If
End If

'Clean up
Set PPSlide = Nothing
Set PPPres = Nothing
Set PPApp = Nothing

End If

End Sub

Answer: If I understood your problem then I think this is what you want.
You are currently pasting the chart "On" Slide 1. You have to paste it "In" relevant Place Holder in Slide 1.
Amend your code to incorporate this (TRIED AND TESTED)
Dim nPlcHolder As Long

With PPPres
    nPlcHolder = 2 '<~~ The place holder where you have to paste

    .Slides(1).Shapes.Placeholders(nPlcHolder).Select msoTrue
    .Windows(1).View.PasteSpecial (ppPasteMetafilePicture)
End With

Now even if you change your layout, the charts will move accordingly.
SNAPSHOT

HTH


zend undefined URL handling

Question: hello I am working in Zend. I want to know some thing about undefined URL handling. I have a url like http://localhost/concierge/login and it has the following rule in url rule file.
'admin/login'                  =>array('login',                                array('module'=>'admin','controller' => 'index','action' => 'login'),array(),'login'),. It all works fine.
But if if change the url like http://localhost/concierge/lgin which I have not defined it goes to a blank page where an empty array is shown and there is written Page not Found. IT looks bad. I want to know if user writes any thing wrong in url, My application should show 404 error.
Now I want to know How can I achieve my task? Will I have to define an other rule for url rules files to handle all these errors? If so how this url rule will look like? And for controllers what should I do? Any help ?
Comment: Check http://framework.zend.com/manual/en/zend.controller.plugins.html, search for `404` on that page (no direct link available). Basically you can drop in the error handler plugin to handle 404s
Comment: Direct link - http://framework.zend.com/manual/en/zend.controller.plugins.html#zend.controller.plugins.standard.errorhandler.fourohfour
Answer: I do this using the preDispatch hook of a front controller plugin.
public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $disp = Zend_Controller_Front::getInstance()->getDispatcher();
    if ( !$disp->isDispatchable($request) ) {
            $request->setModuleName('default');
            $request->setControllerName('error');
            $request->setActionName('error404');
    }

}
if the thing doesn't exist (  /registerxxx   instead of /register  for
example ) then they get bounced to a 404 page.  It has worked so far for me.

zend undefined URL handling


Matlab + Ordinary Least Squares (OLS) method

Question:
I'll be very grateful if you'll help me to solve the equation with Ordinary Least Squares (OLS) method + Matlab.

Given:
$P=\frac{mt}{b+t}$

Also:
t=[1,3,4,7,8,10]
P=[2.1, 4.6, 5.4, 6.1, 6.4, 6.6]
1) Write P in Matlab.

2) Find b,m by solving the equation with Ordinary Least Squares (OLS) method.

Thank's.
Answer: Hint:
Write the equation this way
$$\frac{1}{P}=\frac{b}{m}\cdot\frac{1}{t}+\frac{1}{m}$$
Comment: Nice trick. Now it's clear. Thank's for you hint!


What is the difference between Polymer paper-tabs and iron-selector?

Question: I was looking at the source code for the header on the Polymer website so I could build a similar one for my app.
They use iron-selector for the menu items.
But on their documentation page for responsive-navigation-pattern they use paper-tabs for the same kind of header implementation with tabs.
What is the difference between iron-selector and paper-tabs and which one should I use if I want a similar header for my app?
Answer: The <iron-selector> element manages item selection and has no template or styling (i.e., it doesn't look like the top nav on Polymer's site out of the box). If you want a barebones control, where you could fine-tune the styling of the selected items yourself, this element would be ideal.
The <paper-tabs> element also manages item selection, but includes its own styling (which follows material design) and navigation controls to access the tabs out of view. If you prefer a responsive control that uses material design and other customizable styles, this might be a better choice.
The <iron-selector> on the main page of the Polymer site is styled similarly to the <paper-tabs> element's default style, and since that's the look you're after, I recommend <paper-tabs> mainly because it achieves your goal with less effort required.
Comment: @Diyarbakir No problem :)


Notes don't add up to time signature

Question: I'm a complete noob when it comes to sheet music and I have a (probably) very stupid question regarding this:
The way I see it, the notes and pause don't add upp to 4 beats? First a dotted quarter, 3/8ths of the bar, then an eighth pause, 4/8ths, then an eighth note, 5/8ths, followed by half notes, 9/8ths?
Comment: @guidot Not really.
Comment: Possible duplicate of [Two adjacent notes of same pitch seemingly occupying the same beat?](https://music.stackexchange.com/questions/61200/two-adjacent-notes-of-same-pitch-seemingly-occupying-the-same-beat)
Comment: It is not a stupid question but there are plenty of sources from you can get an answer quicker, e.g. searching "dotted quarter note"
Answer: The dot above the quarter note is a staccato articulation which doesn't affect its rhythmic value. It's still a quarter note. If the dot was to the right of the note it would change its rhythmic value.
The sample has two voices. The top voice (sticks upwards) has a half note rest followed by a half note.
The lower voice (sticks downwards) has a staccato quarter note followed by an eighth note rest then an eighth note tied into the following half note. The eighth note rest is vertically misaligned - it should be further up the staff.
Comment: I think the eighth rest is further down the staff to indicate that it corresponds to the lower voice. But it's so far down, and the lower voice in such a high register, that it's more confusing than helpful in this particular situation.
Comment: I'd agree with @Kevin that the eighth rest should have been placed somewhere around the 2nd or third staff line.

Notes don't add up to time signature


Materialize 1.0.0-beta (CSS Transitions)

Question: Sou novo em front end em geral, tenho conhecimento básico de html e css, gostaria de usar o materialize e entender esta função aqui.
http://materializecss.com/css-transitions.html
pois eu tento usar estes códigos presente na página só que não consigo usar o "Toggle Scale" em minha página

    add

    add

já inspecionei a própria página para ver como eles fizeram mas na prática eu nunca consigo usar essa função de clicar e esconder um objeto, copiei os códigos para a minha mas mesmo assim não da certo (os arquivos do materialize estão organizados e copiei o html que eles recomendam)
Toggle Scale

até mesmo usei este código fonte acima presente na página para ativar o "Toggle Scale" mas mesmo assim não dá certo, gostaria de um exemplo funcional se possível para mim entender na prática, desde já, obrigado.
Comment: Setou os scripts da biblioteca?
Comment: Pelo que vi. Você não setou a biblioteca. Neste link está explicando. Pegue a opção por cdn por ser a mais rápida. http://materializecss.com/getting-started.html
Comment: Sim, setei tudo corretamente como está no site, pois os outros componentes estão funcionando, eu não sabia que no caso este "css transition" do materialize tinha que definir o uso via javascript.
Answer: na verdade você precisa criar um código que altere as classes, fiz um exemplo em que o clique faz desaparecer e volta 1 segundo depois:

var scale = document.getElementById('scale-demo')

var b = true

scale.addEventListener('click', function() {
  if (b) {
    scale.className = 'btn-floating btn-large scale-transition scale-out'
    setTimeout(function() {
      scale.className = 'btn-floating btn-large scale-transition scale-in'
    }, 1000)
  } else {
    scale.className = 'btn-floating btn-large scale-transition scale-in'
  }
})
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" media="screen,projection" />

  add

O Materialize tem essas classes mas são só o efeito de "diminuir" e "aumentar", eles não acontecem por conta própria, você deve definir o uso
Answer: Achei uma solução interessante que fica igual ao modelo de referência do site

function toggleButton() {
  var scale = document.getElementById('scale-demo');
  scale.classList.toggle('scale-out');
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  add

            Toggle


Compound interest with penalty in withdrawal amount

Question: Carl puts $10000$ into a bank account that pays an annual effective interest rate of $0.04$ for $10$ years. If a withdrawal is made during the first five and a half years, a penalty of $5\%$ of the withdrawal amount is made.Carl withdraws $K$ at the end of years $4$, $5$, $6$, $7$. The balance in the account at the end of year $10$ is $10000$.  Calculate $K$.
From the effective interest rate, we get the compound interest rate to be $0.04$.
Then at $t=4$: $A(4)-K-0.15K=10000(1.04)^4-1.05K=11698.58-1.05K$
The, afterwards, I do not exactly know what to do.
Comment: hope this may help http://interpretmaths.blogspot.com/2015/03/two-basic-models-for-loaninvestment.html - pure theory
Comment: Is there penalty on the 6th and 7th years?
Comment: @N.S.JOHN,there is no penalty on 6th and 7th yr, do you have any idea of the working?
Answer: Let $i=4\%$, $p=5\%$, $n=10$, $C=10000$ and $S=10000$.
At the end of the 4th year we have $C(1+i)^4-pK-K=P$ and at the end of the 5th year we have $P(1+i)-pK-K=Q$. At the end of the 6th year we have $Q(1+i)-K=M$ and at the end of 7th year $M(1+i)-K=N$. So the sum $N$ will produce $N(1+i)^{n-7}=S$ at the end of the $n$-th year.
That is
$$\Big(\underbrace{\{\underbrace{[\underbrace{(\underbrace{C(1+i)^4-(1+p)K}_{P})(1+i)-(1+p)K }_Q](1+i)- K}_M\}(1+i)-K}_N\Big)(1+i)^{n-7}=S\tag 1$$
and after some products
$$\scriptsize
\begin{align*}
S &=\left(\Big\{\Big[C(1+i)^4(1+i)-(1+p)K(1+i)-(1+p)K\Big](1+i)-K\Big\}(1+i)-K\right)(1+i)^{n-7}\\
&=\left(\Big\{C(1+i)^4(1+i)(1+i)-(1+p)K(1+i)(1+i)-(1+p)K(1+i)-K\Big\}(1+i)-K\right)(1+i)^{n-7}\\
&=\left(C(1+i)^4(1+i)(1+i)(1+i)-(1+p)K(1+i)(1+i)(1+i)-(1+p)K(1+i)(1+i)-K(1+i)-K\right)(1+i)^{n-7}\\
&=C(1+i)^4(1+i)(1+i)(1+i)(1+i)^{n-7}-(1+p)K(1+i)(1+i)(1+i)(1+i)^{n-7}-(1+p)K(1+i)(1+i)(1+i)^{n-7}-K(1+i)(1+i)^{n-7}-K(1+i)^{n-7}\\
&=C(1+i)^{4+1+1+1+n-7}-(1+p)K(1+i)^{1+1+1+n-7}-(1+p)K(1+i)^{1+1+n-7}-K(1+i)^{1+n-7}-K(1+i)^{n-7}\\
&=C(1+i)^{n}-(1+p)K(1+i)^{n-4}-(1+p)K(1+i)^{n-5}-K(1+i)^{n-6}-K(1+i)^{n-7}\\
&=C(1+i)^n-(1+p)K\Big[(1+i)^{n-4}+(1+i)^{n-5}\Big]-K\Big[(1+i)^{n-6}+(1+i)^{n-7}\Big]
\end{align*}
$$
or
$$C(1+i)^n-(1+p)K\Big[(1+i)^{n-4}+(1+i)^{n-5}\Big]-K\Big[(1+i)^{n-6}+(1+i)^{n-7}\Big]=S\tag 2$$
and finally
$$
K=\frac{C(1+i)^n-S}{(1+p)\left[(1+i)^{n-4}+(1+i)^{n-5}\right]+\left[(1+i)^{n-6}+(1+i)^{n-7}\right]}
$$
Comment: I could not understand how you factorised it @alexjo
Comment: @Toshina11 Do you mean  eq. 1 or eq. 2?
Comment: I mean  it is eq 2
Comment: @Toshina11 I've added some calculations
Comment: I had an aha moment as you factorised it out so easily.
Answer: Your expression for the value at $t=4$ is fine, though you have a typo of $0.15$ instead of $0.05$.  If you define $A(4)$ as the value at the end of year $4$, it should just be $A(4)=10000\cdot 1.04^4-1.05K$ and the first equal sign is not correct.  Now keep going $A(5)=1.04A(4)-1.05K$ and so on.  Plug in $A(4)$ to this, the evaluate $A(6)$, but you will not have the factor $1.05$ because there is no penalty.  Once you get to $A(7)$ you have $A(10)=A(7) \cdot 1.04^3=100000$  You will have a quadratic equation in $K$.  Perhaps you are expected to use a spreadsheet and goal seek.
Comment: Actually, you won't have a quartic equation in $K$...
Comment: @alexjo:  I missed that there was only a penalty for two years.  Fixed.


Searching for a vector inside another vector

Question: I want to search thorough a vector to see if an element appears. Once this element appears along with others, i want to re-search through the original to see if this second element appears else where within the vector. The end result should show the first element being found and then the information of where the second element appears.
void searchband()
{

    ifstream artist("newartist.txt");
    string SBand;
    cout << "Please enter the band you want to seach" << endl;
    cin >> SBand;
    system("CLS");
    while (artist >> forname >> surname >> bandnum)
    {

        band.clear();
        for (int i = 0; i < bandnum; i++)
        {
            string tmp;
            artist >> tmp;
            band.push_back(tmp);
        }
        artist >> role;
        if (find(band.begin(), band.end(), SBand) != band.end())
        {

            cout << forname << " " << surname << endl;
            cout << "Played for: ";
            ostream_iterator<string> output_iterator(cout, " ");
            copy(band.begin(), band.end(), output_iterator);
            cout << " " << endl;
            cout << " " << endl;
            newband = band;

        }
            if (find(band.begin(), band.end(), newband) != band.end())
            {

                cout << forname << " " << surname << endl;
                cout << "Played for: ";
                ostream_iterator<string> output_iterator(cout, " ");
                copy(band.begin(), band.end(), output_iterator);
                cout << " " << endl;
                cout << " " << endl;

            }
            system("pause");
            cin.get();
            main();

    }
}

This gets the error code

error C2678: binary '==' : no operator found which takes a left-hand operand of type std::basic_string<char,std::char_traits<char>,std::allocator<char>> (or there is no acceptable conversion)

I think it may be because
vector<string> = newband

but that is the only way i can think of to pass the vector information over is to another vector
Comment: What exactly do you mean by "find a vector of variables"? Please show an example input and a corresponding desired outpiut.
Comment: i dont really understand what you want to do. Is it [`std::find_first_of`](https://en.cppreference.com/w/cpp/algorithm/find_first_of) you are looking for? Can you provide an example input and output?
Comment: I don't understand what you mean. Please try an clarify with a more rigorous explanation and with some concrete examples.
Comment: A different approach would be to sort the vectors and then compare. You can also remove duplicates from a vector and optionally collect the duplicates in another vector. I can post some examples if you are interested.
Comment: Are you the same person that posted [these](https://stackoverflow.com/q/55710467/2610810) [two](https://stackoverflow.com/q/55575623/2610810) questions? The code is basically identical.
Comment: @Caleth No, but we are working together on this problem. The second of those questions has been answered but the first one is the same problem.
Answer: std::find_first_of does what you are looking for:

Searches the range [first, last) for any of the elements in the range [s_first, s_last).

Example (also taken from cppreference):

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{0, 2, 3, 25, 5};
    std::vector<int> t{3, 19, 10, 2};

    auto result = std::find_first_of(v.begin(), v.end(), t.begin(), t.end());

    if (result == v.end()) {
        std::cout << "no elements of v were equal to 3, 19, 10 or 2\n";
    } else {
        std::cout << "found a match at "
                  << std::distance(v.begin(), result) << "\n";
    }
 }

Comment: @SeanHeaney erm... only now I realized that the code is about bands not places to visit.... really no offense, but note that it does not help if you make things up, if you can show the real thing then do it instead of adding an extra layer of confusion by talking about something that is not the code you are looking at. Nevermind, it is just that I have to turn to other things for a while
Comment: @SeanHeaney the last part of the example prints where the match was found. Note that `find_first_of` only returns the first occurence. It does not find all of them, though you can utilize `find_first_of` to do exactly that. From your question it is still not perfectly clear what you want to find. The edit say you merely want to see if **any** of the elements appear in the first vector. While the first paragraph talks about finding **all** of the elements. If you need more help, please include input and expected output in the qeustion
Comment: @SeanHeaney please include an example of input and output. for example: input vector: "Rome Paris NewYork" search vector: "Rome Paris", expected output: "Rome Paris", is this what you want?
Comment: expected input "Rome" Expected output:"Visited By Ryan who also visited Paris, Prauge" Expected input "paris , prauge output:visited by Henry an ryan , Visited by henry and jenny
Comment: @SeanHeaney sorry, this is not sufficient information. Where are the names coming from? Ryan who? Imagine you talk to someone who has not the slightest idea about the problem you are currently trying to solve, you can only communicate in written form. How would you explain what you need? ;)
Comment: @SeanHeaney in different words, the only meaningful way I could come up with to get "Visited By Ryan who also visited Paris, Prauge" when the only input is "Rome" would be `std::cout << "Visited By Ryan who also visited Paris, Prauge";`
Comment: Pretty much i have a vector of strings for each person. I am searching for a specific thing. The code will output all people who contain that particular string inside their vector. It will be output as a vector containing strings. These people will have other strings in their vectors. I want to re-search using a different search and it'll will given a new list of people based on that new place i've searched. I want to be able to keep both sets of information so that you can trace form the first search, who's been there, then look and where that person's been and look who has also been there.
Comment: @SeanHeaney what you describe is your code. Code is much better at describing code rather than text. I can only speak for myself, but I am completely lost already after the one third of you comment. Please read about [mcve]. Try to concentrate on only one part of the code: searching the vector and think of that as a function taking some input and producing some output. I still dont understand what the input/output to/from that function would be
Comment: Edited the question hope this makes more sense
Comment: @SeanHeaney this seems like a completely different question now. Fine in this case, because there is only my answer, and I dont really care about it getting useless. Normally when in the course of clarification it turns out the your question is different you better open a new one in case there are already answers. Anyhow just leave it like that, I will maybe come back later and fix the answer, if not someone else answers in the meantime
Comment: Was simply trying to describe the problem using holiday destinations as i thought it would make it clearer to understand. The problem at hand is still the same. Still trying to search for a vector within another vector. I added the error code as thought it would be helpful because there obviously wasn't enough detail originally. Any immediate help would be appreciated, thanks
Comment: Sorry for the added confusion, was trying to make it clearer to understand but obviously didn't. If you have any spare time to help it would greatly appreciated
Comment: @user4630355818 For your answer is there a way to find all rather tham just fimd first of?


Apache Spark - Map Reduce Debugging Tips

Question: I am trying to implement Kafka - Spark environment. I am trying to debug my MapReduce logic (implemented in Java). Spark submit step is making it complicated to debug with break points in my algorithms. Incoming live data patterns are complex. It will be very time consuming process to simulate the complex algorithms. Better development environment will help developers to validate their map reduce logic on live stream data.
Please suggest any tips and tricks. Is it possible to have IDE breakpoints, or remote debugging with Apache-Spark.
Answer: I don't think it matters if you are developing streaming or batch spark application. You can always use intellij idea for graphical debugging of your application.
Also look at this video: https://www.youtube.com/watch?v=kkOG_aJ9KjQ. In the end if you want to debug reactivity of your application according to data patterns I suggest to use Spark's internal tools to see for example how DAG is being created or how it's being distributed.
One thing I myself am working on is to use spark debugging tools, and build a log according to my application execution graph with added information that I get from profilers (usual OS tools like iotop or iostat) to find for example where I am not utilizing resources enough.
In the end you need these information together to make a decision and ironically it itself can become a data intensive application.


Examples of uncountable sets with zero Lebesgue measure

Question: I would like examples of uncountable subsets of $\mathbb{R}$ that have zero Lebesgue measure and are not obtained by the Cantor set.
Thanks.
Comment: "not obtained by the Cantor set" has no formal meaning. I asked this because all examples of uncountable subsets of $\mathbb{R}$ with zero Lebesgue mesure that I have seen is Cantor set or a set "obtained by Cantor ser", like this: http://math.stackexchange.com/questions/175559/example-of-measure-zero-sets?rq=1 Thanks.
Comment: You need to specify what you mean by "not obtained by the Cantor set". Any Borel set (and more) is the image of the Cantor set by a Borel function.
Comment: "not obtained by the Cantor set"?
Answer: Let $(r_n)_{n\in\mathbb{N}}$ be a dense sequence in $\mathbb{R}$ (it could, for example, be an enumeration of the rationals). For $k \in \mathbb{N}$, let
$$U_k = \bigcup_{n\in\mathbb{N}} (r_n - 2^{-(n+k)},\, r_n + 2^{-(n+k)}).$$
$U_k$ is a dense open set with Lebesgue measure $\leqslant 2^{2-k}$, thus
$$N = \bigcap_{k\in\mathbb{N}} U_k$$
is a set of the second category (Baire), hence uncountable, and has Lebesgue measure $0$.
Comment: I don't know if this counts as being not obtained from a Cantor Set. $N$ is Borel Set. It has the perfect set property. Since $N$ is uncountable, $N = P \cup C$ where $P$ is nonempty perfect and $C$ is countable. So $N$ is really just a Cantor set union a countable set.
Comment: @S717717 Yes, it's dense in $\mathbb{R}$ (as a superset of the dense $\{r_n:n\in\mathbb{N}\}$). We don't need to show that $N$ is complete to see that it's of the second category (in $\mathbb{R}$, also in itself). It's completely metrisable, but it's not complete in the standard metric. Directly from the construction we have $$\mathbb{R}\setminus N=\bigcup_{k\in\mathbb{N}}\bigl(\mathbb{R}\setminus U_k\bigr),$$ that is, $N$ is co-meagre. Since $\mathbb{R}$ is not meagre in itself, it follows that $N$ is not meagre in $\mathbb{R}$. And as a co-meagre set in a Baire space, $N$ is a Baire space.
Comment: Sure, the sequence of centres is already dense.
Comment: I didn't see the union in front of the intervals.
Comment: @DanielFischer: Awesome!!! *(You might link this to the Baire thread)* http://math.stackexchange.com/questions/165696/your-favourite-application-of-the-baire-category-theorem
Comment: I'm trying to understand the Liouville numbers, or U-numbers, which are uncountable, measure 0 and dense.

The Cantor set is uncountable, measure 0 and not dense.

So, could we isomorphize each other?
Comment: @ViníciusFerraz What do you mean by "isomorphize"? Are you asking whether the sets are homeomorphic?
Comment: I want to classify aleph_1 uncountable sets up to isomorphism. It seems that Liouville's is not isomorphic to Cantor's set.
Comment: @ViníciusFerraz What does "isomorphism" mean here? Homeomorphism? Order isomorphism?
Comment: Example: the ring $\mathbb{Z}$ is not iso. to the ring $\mathbb{Q}$.
What is necessary and sufficient for X to be ring-isomorphic to $\mathbb{R}$? Example. (0, 1) = Ball(0.5, r = 0.5) $\simeq \mathbb{R}$. Uncountable, aleph_1, dense, Lebesgue measure > 0, in addition to... what?
Comment: I'm sorry, @ViníciusFerraz, but that's quite unclear. The interval $(0,1)$ doesn't carry a standard ring structure, so in what sense is it isomorphic to $\mathbb{R}$ when considering ring structures? Of course you can endow every set of cardinality $2^{\aleph_0}$ with a ring structure that makes it isomorphic to $\mathbb{R}$, but that's not particularly interesting. If we have a given ring structure on $X$, then $X$ is ring-isomorphic to $\mathbb{R}$ if and only if it is a complete Archimedean ordered field. Thus the only subring of $\mathbb{R}$ that is isomorphic to $\mathbb{R}$ is
Comment: $\mathbb{R}$ itself. But that isn't particularly interesting either. And neither the Cantor set nor the set of Liouville numbers is a subring of $\mathbb{R}$.
Comment: $\mathbb{Q}$ is the "field of fractions" of $\mathbb{Z}$.
Let $C$ be Cantor's set of real numbers.
Is $\mathbb{L}$ like the "field of fractions" of $C$? The "densification"?
Comment: $C$ isn't a ring, @ViníciusFerraz, I'm lost as to what you want. You should figure out what exactly you want to ask, and ask a question on main. This comment thread is not the right place to find out what you actually are interested in.
Comment: See http://math.stackexchange.com/questions/1610098/example-of-an-uncountable-dense-set-with-measure-zero#comment3752974_1610098

$[\mathbb{Q} \cap (0,1)] \cup C = A$.
I want a function $f : A \rightarrow \mathbb{L}$, which is Liouville's set.
Comment: @DanielFischer I've some questions regarding to your answer. $U_k$ is dense in which space? Is it dense in $\Bbb R$ ? To show $N$ is of 2nd category by Baire's theorem we have to show $N$ is complete. How I can show that $N$ is complete ?
Answer: Your question is in some part historically related to the investigation of the Continuum Hypothesis CH, i.e. whether every uncountable subset of $\mathbb{R}$ is in bijection with $\mathbb{R}$. A perfect subset is closed set with no isolated points. It is well-known that the Cantor set continuous injects into all perfect subsets. (So perfect sets cardinality $2^{\aleph_0}$.) One way of solving CH was to show whether all uncountable set was the union of a perfect set and an countable set. This is called the perfect set property.
So one way of formalizing your idea of "not obtained from a Cantor Set" is to say that your set is not the Cantor set union a countable set. So taking this interpretation of question, a satisfactory answer would be to produce an uncountable measure zero set without a perfect subset.
Note that without the axiom of choice and with the axiom of determinacy, all uncountable sets have the perfect set property. So in such universe, you will not be able to produce any such example. In particular, if you are working $ZF$ set theory, you will not be able to produce such example (unless the axiom of determinacy is inconsistent, which no one knows.)
I am not sure if such a set exist in ZFC. However, by assuming some more axioms that are shown to be equiconsistent with ZFC, such a set does exist.
$Add(null)$ is the additivity of ideal of measure sets. That is if $\kappa < Add(null)$ is a cardinal, then the union of $\kappa$ many measure zero sets is still measure zero. $ZFC + \neg CH + Add(null) = 2^{\aleph_0}$ is consistent with $ZFC$.
So in such a universe, you can take any the Cantor set $C$ of measure zero. Use the axiom of choice to well order $C = \{a_\xi : \xi < 2^{\aleph_0}\}$. Then $\{a_\xi : \xi < \aleph_1\}$ is an uncountable measure zero set since $\aleph_1 < 2^{\aleph_0} = add(null)$.
You may not be too happy with this example I actually did use a Cantor set and carved out a uncountable measure zero subset. If you would like: Using the axiom of choice there exists disjoint uncountable set $A$ and $B$ such that $A$ and $B$ intersect every perfect subset of $\mathbb{R}$. In particular $A$ is does not contain any perfect subsets. (You can find this construction in $\textit{Descriptive Set Theory}$ 2C.4.) So this $A$ is very different from a Cantor set. In fact, if you look at the construction it is not clear if $A$ is even meaureable. Then apply the same construction above to carve out a uncountable measure zero subset of this set $A$.
So in conclusion, in the equiconsistent extension $ZFC + \neg CH + add(null) = 2^{\aleph_0}$ such a measure set exists. Using only $ZF$ and no choice, no such example can be found (if AD is actually consistent). I am still not sure if $ZFC$ can produce such an example.
Comment: The answer to the question in your last paragraph is yes, see my answer. (And +1.)
Comment: I thought the "perfect set property" was just that every uncountable set contains a perfect set. As for "all uncountable set was the union of a perfect set and an countable set" the set of irrational numbers is a counterexample to that.
Answer: A very simple example is the set of numbers not normal in base $10$.  This set is not obtained from a Cantor set in any way (and is in fact dense in $[0,1)$) and has zero measure and is obviously uncountable.  Additionally it has full Hausdorff dimension and is of the second category.
The set of badly approximable numbers works for this, too.
Comment: Just a remark: the Cantor set is a subset of the set of numbers not normal in base 3.
Comment: @Freeze_S maybe I'm missing something obvious but I don't see how this has any similarities to the Cantor set construction.  What are you thinking of that's similar?
Comment: What is a number "not normal in base 10" ?
Comment: See http://mathworld.wolfram.com/NormalNumber.html for a definition of normal number.
Comment: Yeah I don't see how this is 'much' different to the cantor construction...
Answer: In his answer, William defined "not obtained from the Cantor set" as "not the union of a [perfect] set and a countable set." In particular, any set not containing a perfect set is not obtained from the Cantor set. He then asked whether an uncountable, measure zero set of this type exists provably in ZFC.
The answer is yes. ZFC proves the existence of a Bernstein set - a set $B$ such that for every perfect set $P$, $B\cap P$ and $B^c\cap P$ are each nonempty. Now if $B$ is Bernstein and $P$ is perfect, we have in fact that $B\cap P$ is uncountable and does not contain a perfect set; clearly $B\cap P$ can't contain a perfect set (since then $B^c$ wouldn't meet it), and if $B\cap P$ were countable, then $P\setminus (B\cap P)$ would be an uncountable Borel set, hence (since Borel sets have the perfect set property) would have a perfect subset which would not meet $B$.
OK, so fix a Bernstein set $B$ and a measure zero perfect set $P$ (say, the usual Cantor set) and let $X=B\cap P$. Clearly $X$ has measure zero, and by the above $X$ is uncountable and does not contain a perfect subset, hence is not obtained from the Cantor set in the sense defined in the first paragraph.

Here's a sketch of the ZFC-proof that a Bernstein set exists. We use transfinite induction, and the observation that there are exactly as many reals as perfect sets. At stage $\alpha<2^{\aleph_0}$, look at the $\alpha$th perfect set; pick two reals not already used in this set, and put one of them in $B$, and the other in the complement of $B$. Since perfect sets have size continuum, and by induction we've only used $2\alpha$-many reals so far, we can always find such a pair of reals.
Comment: @CuriousKid7 To set up the transfinite induction, we need to fix well-orderings of the reals and of the perfect sets. This requires choice.
Comment: How exactly is AC used in this last paragraph?
Comment: If you just wanted a measure zero set which is "not obtained from the Cantor set" according to William's definition, you could just take $\mathcal C+\mathbb Q$ where $\mathcal C$ is the Cantor set. Of course "not containing a perfect set" is much stronger.
Answer: Let $E_n \subset [0,1] $ be the set of real numbers whose binary expansion starts with a $n$-bit string which contains at most $\lfloor p\, n \rfloor$ zeroes, for $ 0 \le p < 1/2$. For example, if $ p = 1/3$ then
$$ E_3 = [0.011,0.011\bar1]\cup [0.101,0.101\bar1] \cup [0.110,0.110\bar1] \cup [0.111,0.111\bar1]$$
Let
$$ E = \bigcap_{k\in\mathbb N} \bigcup_{n \ge k} E_n $$
Then $E$ is uncountable, has zero Lebesgue measure, and I cannot see any connection with the Cantor set.
Answer: Denote $E_2^c =$ the set of real numbers $x$ on the interval $[0, 1]$ such that in the decimal form of $x = 0.i_1 i_2 i_3 \dots$ there is no digits $2$.
Write $x \in E_2^c$ in decimal form
    $$
 x = 0. i_1 i_2 i_3 \dots, \ \
 i_k = 0, 1, 3, 4, 5, 6, 7, 8, 9, \ \
 x = \sum_{k=1}^{\infty} \frac{i_k}{10^k},
 $$
    and assume that the first digit $2$ appeals at $k$th decimal of $x$.
Denote $E_{2,1}$ as the set of real numbers $x$ on the interval $[0, 1]$ such that the first digit $2$ appeals at $1$th decimal of $x$:
    $E_{2,1}
 = \{x | x = 0. 2 \dots\}
 = [0.2, 0.3)$,
    then $m(E_{2,1}) = 10^{-1}$;
Denote $E_{2,2}$ as the set of real numbers $x$ on the interval $[0, 1]$ such that the first digit $2$ appeals at $2$th decimal of $x$:
    $E_{2,2}
 = \{x | x = 0. i_1 2 \dots\}
 = \cup_{i_1} [0.i_1 2, 0.i_1 3)$,
    $i_1 \in \{0, 1, 3, 4, 5, 6, 7, 8, 9\}$,
    then $m(E_{2,2}) = 9 \times 10^{-2}$;
Inductively,
    \begin{align}
 E_{2,k}
 &= \{x | x = 0. i_1 \dots i_{k-1} 2 \dots\} \\
 &= \cup_{i_1, \dots, i_{k-1}} [0. i_1 \dots i_{k-1} 2, 0. i_1 \dots i_{k-1} 3),
 \end{align}
    where $i_1, \dots, i_{k-1} \in \{0, 1, 3, 4, 5, 6, 7, 8, 9\}$,
    then $m(E_{2,k}) = 9^{k-1} \times 10^{-k}$;
Define $E_2 =$ the set of real numbers $x$ on the interval $[0, 1]$ such that in the decimal form of $x = 0.i_1 i_2 i_3 \dots$ there is digits $2$.
Then the measure of $E_2$ is
    $$
 m(E_2)
 = m(\cup_{k=1}^{\infty} E_{2,k})
 = \sum_{k=1}^{\infty} m(E_{2,k})
 = \sum_{k=1}^{\infty}  9^{k-1} \times 10^{-k}
 = 1.
 $$
Thus, the measure of $E_2^c$ is
    $$
 m(E_2^c)
 = m([0, 1] \setminus E_2)
 = m([0, 1]) - m(E_2)
 = 1 - 1
 = 0.
 $$


Window.print() sets default copies to 2

Question: I have a requirement that by clicking on a button, the printer dialog will open with the number of copies set to 2 instead of the default number 1.
Comment: Is this still not possible in 2019?
Comment: No it's not possible.
Answer: No it is not possible using pure javascript with window.print().
However, if you are open to using Java Applet, take a look at qz-print aka jzebra. I have personally used this in some past projects for some advance printing requirements and the result is very satisfying. Take a look at their printHTML() method
***************************************************************************
    * Prototype function for printing plain HTML 1.0 to a PostScript capable
    * printer.  Not to be used in combination with raw printers.
    * Usage:
    *    qz.appendHTML('
Hello world!
');
    *    qz.printPS();
    ***************************************************************************/
    function printHTML() {
        if (notReady()) { return; }

        // Preserve formatting for white spaces, etc.
        var colA = fixHTML('
*  QZ Print Plugin HTML Printing  *
');
        colA = colA + '<color=red>Version:</color> ' + qz.getVersion() + '
';
        colA = colA + '<color=red>Visit:</color> http://code.google.com/p/jzebra';

        // HTML image
        var colB = '';

                //qz.setCopies(3);
        qz.setCopies(parseInt(document.getElementById("copies").value));

        // Append our image (only one image can be appended per print)
        qz.appendHTML('

' +
        '' + colA + '	' +
        '' + colB + '	' +
        '

');

        qz.printHTML();
    }

Of course if you just want to print 2 copies, this may be way too over killed and too complicated to implement. But I'm not aware of any other way that can help you interfere with the browser's printing.

Window.print() sets default copies to 2


Is there a way to define significance to say something has "fatter" tails?

Question: I have two distributions of data. The means are about the same, but one data set has longer, fatter tails. Is there a way I can say one distribution has significantly "fatter" or "longer" tails than the other? The population size for both distributions are equal. Ideally, Id like to implement the solution in R.
Comment: The notion of an outlier doesn't have anything to do with whether a distribution has heavy or light tails. An outlier tends to be an "inconvenient" data point that is not well explained by the preferred model/explanation for the data.
Comment: There's multiple possible ways to measure heaviness of tail. Some guidance about what you want to achieve may help narrow it down a bit. Can you say more about what this conclusion would be used to do?
Comment: I agree with dipetkov (whats an outlier depends on the model) but let's say we were to try to proceed ... all you have done is shifted the question from how to define tail heaviness to that of precisely defining an outlier. Replacing one imprecise term with another gets nowhere. This is why I raised the question of your *purpose*. If it really is about outliers, why do more outliers matter?
Comment: A *post hoc* test based on an observation made in the data is invalid.  (It's an example of HARKing).  Thus, we should look askance at answers that propose hypothesis tests of any sort. But you legitimately ask for a way to "say," rather than formally test.  One of the most specific ways to *see* and *quantify* a difference in distributions is a QQ plot, which is native in `R` (and most statistical computing platforms).
Comment: @whuber Yes, I am using the wrong terminology. I agree a QQ plot is likely what I want to show the differences in the distributions.
Comment: Do you mean something like a test of kurtosis equality like we have tests of mean equality?
Comment: @Dave, yep, that's what I'm looking for.
Comment: @Glen_b Im trying to say that one of the distributions has more outliers than the other distribution, and I want to say this doesn't happen by chance.
Comment: @dipetkov Please forgive my misuse of language. The outlier comment was incorrect. The observation I am seeing is one distribution of data has fatter tails, and by comparison to the control distribution, these fatter tails appear to be "outliers". Clearly I am lacking the correct terminology to explain this. The comments and suggested solutions should get me closer. I need to do some reading and learning. Thank you for your help and insight.
Answer: The kurtosis of a distribution is a measure of how much mass there is in its tails. From the mathematical definition below, you can tell that kurtosis cannot be negative; the kurtosis of the normal distribution is 3. $$Kurtosis=\frac{E[(Y-\mu_Y)^4]}{\sigma^4_Y}$$ The plot below shows that the t distribution with d.f.=5 (red) has fatter tails than the normal distribution (black).

library(moments)
set.seed(10)

nobs = 1000000
norm <- rnorm(nobs)
tdist <- rt(nobs, df=5)
plot(density(norm), xlim=c(-4, 4), ylim =
c(0, 0.45), col="black", lwd=2, main="",
ann=F)
par(new=T)
plot(density(tdist), xlim=c(-4, 4),
     ylim = c(0, 0.45), col="red", lwd=2,
     main="", ann=F)
text(-3, 0.4, paste0("kurtosis=",
     round(moments::kurtosis(norm), 2)))
text(3, 0.4, paste0("kurtosis=",
     round(moments::kurtosis(tdist), 2)),
     col="red")

Comment: The moments library is what I'm looking for. Thank you.
Answer: For example, consider the following fictitious
datasets sampled from exponential and gamma
distributions in R. All have 1000 observations and
all three populations have mean $15,$ but gamma distributions with larger shape parameters have
thinner right tails. Note: $\mathsf{Exp}(1/15) \equiv \mathsf{Gamma}(1, 1/15).$
set.seed(2022)
x1 = rexp(1000, 1/15)
x2 = rgamma(1000, 3, 1/5)
x3 = rgamma(1000, 5, 1/3)

boxplot(x1, x2, x3, horizontal=T,
               col="skyblue2", pch=20)

Boxplots of the three samples (x1 at bottom).

The plot below shows the histogram of each sample along with its population distribution, with a
vertical line at the 95th percentile of the distribution. (Smaller 95th percentiles are associated with thinner right tails.)

R code for figure:
par(mfrow=c(3,1))
hist(x1, prob=T, ylim=c(0,.07), xlim=c(0,120),
     col="skyblue2")
curve(dexp(x, 1/15), add=T, col="brown", lwd=3)
abline(v = qexp(.95, 1/15))
hist(x2, prob=T, xlim=c(0,120), col="skyblue2")
curve(dgamma(x, 3, 1/5), add=T, col="darkgreen",
      lwd=3)
abline(v = qgamma(.95, 3, 1/5))
hist(x3, prob=T, xlim=c(0,120), col="skyblue2")
curve(dgamma(x, 5, 1/3), add=T, col="purple",
     lwd=3)
abline(v = qgamma(.95, 5, 1/3))
par(mfrow=c(1,1))

In the right tails the purple density function lies below the green one, which in turn lies below the brown one.
Comment: Histograms work poorly for comparing tails.  At a minimum, consider histograms of strongly transformed data (such as logs for positive data).  Better, consider alternative visualizations.
Comment: Kurtosis isn't _exactly_ the same thing as 'fat tail'.
Comment: This was educational. Plotting the 95th percentile helps, but I the metric I was looking for is kurtosis.


Load http url image like a texture in X3DOM

Question: I´m learning X3DOM and I want to know why when I exceute in my browser from local this html code the texture (URL http link, no local image) isnt loading. The cylinder looks black.

    <link rel="stylesheet" href="http://www.x3dom.org/download/dev/x3dom.css">
    <title>DOM Field Interface Test</title>

X3DOM Scene:

        <x3d width='500px' height='400px'>
            <scene>
                <shape>
                    <appearance>
                    <ImageTexture  url="http://drive.google.com/uc?export=view&id=0B0GIfItPpsqjMEUyLU9Fam9aQ0E"><ImageTexture/>
                </appearance>
                    <Cylinder ></Cylinder>
                </shape>
            </scene>
        </x3d>

Or if anyone knows do it the same with "inline" tag for an .x3d http url link (no local too)
Comment: Because x3dom works internally with XHR which brings some restrictions like CORS. I don't know actually how it behave for local pages but at least for hosted pages this is a major show stopper when it comes to loading external resources.
Comment: I undestand that the only way of change that would be change X3DOM.jar to avoid CORS or change server to avoid CORS? Thanks a lot
Comment: You would have to change the server settings in order to handle CORS. This is due to the fact, that the Javascript (not Java) is run within the web browser. The underlying mechanisms are the same and can't be changed by adjusting simply x3dom.
Answer: X3DOM runs in the JavaScript sandbox. That means without putting special code on your server, you cannot access files not on your server. In the case of local files, there is no server. You are restricted to local files only.
In my experience on a PC, you can use local files in Firefox and IEV11, but not Chrome.


Como chamar o valor de uma Subquery dentro de uma outra Subquery sendo que elas estão na mesma View

Question: Tenho uma View com várias Subqueries, uma delas deverá ser utilizada para gerar uma outra Subquery dentro da própria View porém estou recebendo erro, exemplo:
(SELECT COUNT(0)
   FROM `LICENCAS`
  WHERE (`LICENCAS`.`FK_PEDIDO` = `A`.`FK_PEDIDO`) AND Dia_Corrido_Assinatura > `LICENCAS`.`CICLO`) AS `DownloadCount`,
(SELECT CEILING((TIMESTAMPDIFF(SECOND, `A.``ASSINATURA_DATA_INICIO`, NOW()) / 86400))) AS `Dia_Corrido_Assinatura`,
FROM `N_ASSINATURAS` `A`

Estou tendo problema na Subquery DownloadCount pois dentro dela eu chamo o valor da Subquery Dia_Corrido_Assinatura porém eu recebo a mensagem:

Error Code: 1247. Reference 'Dia_Corrido_Assinatura' not supported (forward reference in item list)

Eu até entendo que como é uma Subquery, ela talvez possa nem ter sido gerada para ser chamada, existem alguma opção em cima disso?
EDIT: já tentei mudar de ordem colocando a sub 'Dia_Corrido_Assinatura' primeiro, mas continuo com o mesmo erro.
Answer: Voce pode usar seu subselect dias_ocorridos no from.
Como por exemplo:
SELECT
--esse é seu subselect download
(SELECT COUNT(0)
   FROM `LICENCAS`
  WHERE (`LICENCAS`.`FK_PEDIDO` = `A`.`FK_PEDIDO`) AND tab.dias_ocorridos > `LICENCAS`.`CICLO`) AS `DownloadCount`
  tab.dias_ocorridos
FROM (SELECT referencia_id, 10 dias_ocorridos FROM N_ASSINATURAS) tab, N_ASSINATURAS
WHERE
N_ASSINATURAS.referencia_id = tab.referencia_id

Ou fazer uma função que retorne esse valor, ou uma outra view separada.
Voce não pode colunas criadas dentro da mesma clausula select. Tipo isso:
 select 1 um,
           2 dois,
           um+dois as soma
    from dual

Não funciona
Comment: Eu vou dar certo pois a sua ideia de criar uma view separada funcionou ! Obrigado.
Comment: Opa, que bom que deu certo


How would I perform this query in Django?

Question: class ExternalUser(models.Model):
    user = models.ForeignKey(User)
    external_account_id = models.CharField(max_length=200, null=True, blank=True)

class ExternalFriends(models.Model):
    external_user = models.ForeignKey(ExternalUser)
    external_account_id = models.CharField(max_length=200, null=True, blank=True)

Suppose I first get all ExternalFriends:
all_friends = ExternalFriends.objects.all()

OK, now I have a query set.
How do I SELECT * FROM ExternalUser WHERE external_account_id IN [ ...all_friends's external_account_ids... ]?
What would be the Django equivalent?
Comment: Do you really need the "external_account_id" field on both models? As your ExternalFriends already relate to ExternalUser it could be sufficient to store the id on the ExternalUser model. That would also simplify your queries.
Comment: maybe: ExternalUser.objects.filter(external_friends__external_account_id__is_null=False)
Answer: Sure it can be done more efficiently but...
ExternalUser.objects.filter(external_account_id__in=[friend.id for friend in all_friends])

Comment: was hoping someone else could answer that! I think get just ids all_friends = ExternalFriends.objects.all().values('id') then replace frield.id with friend['id']
Comment: +1 IN clauses are not efficient in general, but your query is correct in this situation. How we got "all_friends" is the question to avoid IN, and make joins if possible.