a cylindrical tank question with diff equations

Question: we hae a cylindrical tank which is full and depth is 10 meters. The rate at which the depth of liquid drops is proportional to the square root of the depth of the liquid. After draining for 20 minutes, the tank has now depth 5 meters. How long it takes for tank to empty?
attempt:
Let $H(t)$ be the height of the tank. We know $H(0)=10$ an $H(20)=5$. Also, since
$$ H' = \sqrt{H} \implies \int \frac{ \mathrm{d} H }{\sqrt{H}} = \int \mathrm{d} t \implies 2 \sqrt{H} = t + C$$
So, $2 \sqrt{5} = 20+ C $ so $C = 2 \sqrt{5}-20$. Thus,
$$ \sqrt{H} = \frac{t}{2} + \sqrt{5} - 10  $$
so, $H=0$ if $ t = \dfrac{ 10 - \sqrt{5} }{2} $
is this correct?
Comment: I think $H(20)$ is known! not $H(30)$
Comment: As time increases, height **decreses**. Does your equation of $H$ and $t$ say so?
Comment: Always ask yourself whether the answer could possibly be true. In this case your answer, $\frac{10-\sqrt{5}}{2}$, is a little less than $4$, so you would be claiming that the tank empties in less than four minutes, although the problem statement says it takes $20$ minutes to drop to $10$ meters. Clearly the answer is wrong. The correct answer must be greater than $20$; since the rate of drainage is slowing down, moreover, the answer should be greater than $40$.
Answer: $$ \frac{dH}{dt} = k\sqrt{H} \implies \int \frac{ \mathrm{d} H }{\sqrt{H}} = \int k ~\mathrm{d} t \implies 2 \sqrt{H} = kt + C$$
$H(0)=10$ and $H(20)=5$
$$ C=2\sqrt{10}~~ k=\frac{\sqrt{5}-\sqrt{10}}{10}$$
Hence $$ 2\sqrt{H} = \left(\frac{\sqrt{5}-\sqrt{10}}{10}\right)t+2\sqrt{10}$$
$$\Leftrightarrow H= \left(\left(\frac{\sqrt{5}-\sqrt{10}}{20}\right)t+\sqrt{10} \right)^2 $$
At $H=0$ $\implies$ $t=20\sqrt{2}+40$
Answer: I would say no.
The question says the rate of fall in liquid level is proportional to $√H$ and not equal to.
SO you should take $dh/dt=-k√h$.
Then integrate this equation with the limits for h as 10 to h and for t as 0 to t.
You will get $2(√h -√10)=-kt$.   ----(1)
Now put $t=20$ and $h=5$ in this equation to get the value of k.
Then simply substitute this value of k in equation(1) and put $h=0$ to get the value of t.
Also, please correct your question, in description you said time taken for height to reduce to 5m was 20mins but you had put 30mins everywhere in the solution


Is the stationarity property invariant by transformation?

Question: In other words, if $X_t$ is $I(0)$, is $f(X_t)$ also $I(0)$?
I would say yes:

The mean stays constant.
The autocovariance still depends only on the lag between the terms.
Comment: You have not defined or restricted $f$ in any way. For an arbitrary $f$, why should the mean stay constant or the ACF only depend on the lag between the terms?
Answer:
You will at least need strict stationarity, because even in the $X_t$ all have the same mean (and variance), the distributions can be different and so the $f(X_t)$ does not necessarily have the same mean if $f$ is nonlinear.
So then assume strict stationarity, then the answer becomes yes for marginal transformations $f$. That is really a consequence of the well-known result that $\DeclareMathOperator{\E}{\mathbb{E}} \E f(X) = \inf f(x) \; dF(x)$, see wikipedia.
For a question about the converse see If the square of a time series is stationary, is the original time series stationary?


Approximations to series of Ramanujan-type

Question: Recently I have been playing around with series of the form
$$\sum_{k=1}^{\infty}\frac{k^{s}}{e^{kz}-1} =  \sum_{k=1}^{\infty}\sigma_{s}(k)e^{-kz}$$
for $s \in \mathbb{Z}$ and where $\sigma_s(k)$ is the sum of divisors function of order $s$.  These series have generated quite a bit of interest over the years, due in large part to some beautiful modular identities of Ramanujan.  The most famous example being
$$\alpha^{-n}\left(\frac{1}{2}\zeta(2n+1)+\sum_{k=1}^{\infty}\frac{k^{2n-1}}{e^{2\alpha k}-1}\right) = \\ (-\beta)^n\left(\frac{1}{2}\zeta(2n+1)+\sum_{k=1}^{\infty}\frac{k^{2n-1}}{e^{2\beta k}-1}\right) - 2^{2n}\sum_{k=0}^{n+1}(-1)^k\frac{B_{2k}}{(2k)!}\frac{B_{2n+2-2k}}{(2n+2-2k)!}\alpha^{n+1-k}\beta^k$$
where $\alpha,\beta > 0, \alpha\beta=\pi^2$ and $B_k$ are the Bernoulli numbers and $\zeta(k)$ is the Riemann zeta function.  As far as I know there aren't any similar relations or closed forms when $s \in 2\mathbb{Z}$. In my investigations I was able to find some approximation formula for general $s > 0$ but which unfortunately perform poorer and poorer as $s \rightarrow \infty$.
For instance, at $s=2$ we have
$$\sum_{k=1}^{\infty}\frac{k^2z}{e^{kz}-1} \approx \frac{2\zeta(3)}{z^2} - \frac{1}{2}-\frac{z}{24} -\sum_{j=0}^{N}B^{(2)}_{j+2}B_{j}\frac{z^{j}}{(j+2)!}$$
where $B^{(k)}_n$ are the Norlund polynomials.
I was excited to find this, but then unfortunately realized that since  the sum on the right hand side diverges as $N \rightarrow \infty$ we can only achieve a finite number of accurate digits as the RHS approaches the left from below then surpasses it, growing without bound.
For instance letting $N=37$ we have
$$\sum_{k=1}^{\infty}\frac{k^2}{e^{k}-1} \approx 2 \zeta (3)-\frac{707928034947324016593079681811720894660110227517}{8567110474102926210628918330759216889856000000000}$$
with the right hand side being correct to the 14-th decimal place.  This is about the best we can do with the above formula.
I am curious as to whether someone would be able to provide a better approximation. I am not very familiar with sort of thing... so maybe there is a standard way of achieving approximations like the one above?
Answer: I figured I would go ahead and provide an answer to my own question just in case someone else comes across this post and is interested in what else is known about formulae such as the one above.
Through my research I discovered two things.  The first being that the above formula should be thought of as an asymptotic expansion.  In particular, as $z \to 0$ we have
$$\sum_{k=1}^{\infty}\frac{k^2}{e^{kz}-1} = \frac{2\zeta(3)}{z^3} - \frac{41}{72z}-\frac{1}{24} -\sum_{j=1}^{N}B^{(2)}_{j+2}B_{j}\frac{z^{j-1}}{(j+2)!} + \mathcal{O}(\vert{z^{N}}\vert)$$
The second thing being, that there is some precedent for an identity of this sort.  Namely, Wigert showed in 1916 that for any $N \geq 1$ the following asymptotic expansion holds as $z\to 0$ in any angle $\vert{\arg(z)}\vert<\pi/2$
$$\sum_{n=1}^{\infty}d(n)e^{-nz} = \frac{\gamma-\log(z)}{z}+\frac{1}{4}-\sum_{k=0}^{N-1}\frac{B^2_{2k+2}}{(2k+2)!(2k+2)}z^{2k+1}+\mathcal{O}(\vert{z^{2N}}\vert)$$
which when considering the identity
$$\sum_{n=1}^{\infty}\frac{x^n}{1-x^{n}} = \sum_{n=1}^{\infty}d(n)x^{n}$$
makes plain the connection between my identity and Wigert's.
My general conjecture is that for any $n,N \geq 1$ the following asymptotic expansion holds as $z\to 0$ in any angle $\vert{\arg(z)}\vert<\pi/2$
\begin{multline*}
\sum_{k=1}^{\infty}\frac{k^{n+1}}{e^{kz}-1} = (-1)^{n}\sum_{k=0}^{n}k!S_2({n+1},{k+1})\sum_{j=0}^{k}B^{(k+1)}_j(-1)^{k-j}(k+1-j)\zeta(k+2-j)\frac{z^{j-k-2}}{j!} \\ + (-1)^{n+1}\sum_{k=0}^{n}k!S_2({n+1},{k+1})\sum_{j=0}^{N}B^{(k+1)}_{j+k+1}B_{j}\frac{z^{j-1}}{(j+k+1)!} +\mathcal{O}(\vert{z^{N}}\vert)
\end{multline*}
where $S_2(n,k)$ are the Stirling numbers of the second kind.


Using object Helper Methods to implement authorization rules

Question: I have the following:-

I am working on an asset management system using Asp.net MVC4 with windows authentication enabled.
The system allow to specify what actions a group of users can do(for example certain group can have the authority to add new physical asset , while they can only read certain logical asset, and so on).
So I found that using the build-in Asp.net role management, will not allow me to have the level of flexibility I want. So I decided to do the following:-

I have created a table named "group" representing the user groups. Where users are stored in active directory.
I have created a table named "Security Role" which indicate what are the permission levels each group have on each asset type(edit, add, delete or view)per asset type.
Then on each action methods , I will use Helper methods to implement and check if certain users are within the related group that have the required permission ,, something such as

On the Car model object I will create a new helper method
Public bool HaveReadPermison(string userName) {

//check if this user is within a group than have Read permission on CARS, //OR is within a GROUP THAT HAVE HIGHER PERMISON SUCH AS EDIT OR ADD OR //DELETE.
}

Next, On the Action method, I will check if the user has the Read permission or not by calling the action method:-
public ActionResult ViewDetails(int id) { // to view transportation asset type
Car car = repository.GetCar(id);
if (!car.HaveReadPermision(User.Identity.Name)) {
if (car == null)
return View("NotFound");
else
return View(car);
}
else
return view ("Not Authorized");

So can anyone advice if my approach will be valid or it will cause problem I am unaware about.
Regards
Comment: Well first of all I would check for null before checking authorization! :)
Comment: you are right ,, this is just a demo code
Answer: In my opinion, once you have decided to use the ASP membership and role providers you can keep leveraging them also for authorization, simply using the Authorize attribute. This will also allow to restrict access by user names and roles.
What the attribute won't do is Action-based authorization. In that case there are a few options but in my opinion this could be brilliantly resolved by a Custom Action Filter based loosely on the following code:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CheckUserPermissionsAttribute : ActionFilterAttribute
{
    public string Model { get; set; }
    public string Action { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var user = filterContext.HttpContext.User.Identity.Name; // or get from DB

        if (!Can(user, Action, Model)) // implement this method based on your tables and logic
        {
            filterContext.Result = new HttpUnauthorizedResult("You cannot access this page");
        }

        base.OnActionExecuting(filterContext);
    }
}

Yes, it is vaguely inspired to CanCan, which is a nice Ruby gem for this kind of things.
Returning Unauthorized (401) will also instruct your server to redirect to the login page if one is specified. You may want to work on that logic if you want to redirect somewhere else. In that case you should do:
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary { { "Controller", "Home" }, { "Action", "Index" } });

and choose the appropriate controller/action pair.
You can use the attribute like this:
[CheckUserPermissions(Action = "edit", Model = "car")]
public ActionResult Edit(int id = 0)
{
    //..
}

Let me know if that works nicely for you.
Comment: thanks for the reply; can you explain what u mean by "What the attribute won't do is Action-based authorization"
Comment: Yeah that is confusing. What I mean is that the AuthorizeAttribute can authorize on a per-user basis or on a per-role basis but not on a specific model action (like "view" cars but not "edit" cars).
Answer: The approach you took looks reasonable, but I would add few changes:

What if you forgot to call HaveReadPermision method? And checking authotization from Actions is not the cleanest solution either, that is not an Action reponsibility.

It is better to keep authorization logic separately. For instance you can create a decorator over you repository which will check the permissions of the current User:
public class AuthorizationDecorator: IRepository
{
     public AuthorizationDecorator(IRepository realRepository, IUserProvider userProvider)
     {
        this.realRepository = realRepository;
        this.userProvider = userProvider;
     }

    public Car GetCar(int id)
    {
       if(this.UserHaveReadPermission(this.userProvider.GetUserName(), Id))
       {
          return this.realRepository.GetCar(id);
       }
       else
       {
           throw new UserIsNotAuthorizedException();
       }
    }

    private bool UserHaveReadPermission(string username, int id)
    {
      //do your authorization logic here
    }
}

IUserProvider will return curent user name from httpRequest.
After doing the change you don't need to warry about authorization when writing Actions
Comment: thank for the reply, so creating my own Groups and Roles tables is not a bad practice in asp.net. as usually i relay on the built-in role provider, but on this application i have many scenarios for managing the authorization which could not be achived by the built-in authorization.
Comment: As far as I undestand you have a authorization for each entity in database, so in this case it is acceptable solution


What is the difference between $q.race to Promise.race?

Question: I am using Angularjs version 1.5.7 and $q.race function added in version 1.5.8.
I saw that there is function Promise.race and my question if there is any difference between those functions.
If there is difference should I copy the function from here: AngularJS: $q.race() in old angular versions
and it will works the same like $q.race?
Thanks in advance and sorry for my english!
Comment: The obvious difference would be that one returns an angular promise while the other returns an ES6 promise :-)
Answer: The core difference is that $q.race will call $rootScope.$apply() under the hood to digest any changes that may occurred after executing your promise callback.
Promise A+ spec has noting to do with that since Promise.all, Promise.race are defined in ES6/ES2015 spec not in Promise A+ spec
Comment: where did you read that $q.race triggers all the $rootScope $apply method? Are you sure that this is not related in general with $q and this has nothing to do with the specific `.race` method?
Answer: JavaScript ES6 specifications introduced the method you described above, like Promise.race, Promise.all etc..
The difference is basically that angular has a built-in $q service in order to manage with promises.
This will trigger automatically the digest cycle in order to change everything that could be related to the data returned by the promises or all the involved operations.
If you are allowed to use ES6 specification, you can use directly all the built-in Promises of JavaScript, but then you have to manually trigger the $digest in order to make all the changes happen.
This is one of the main differences between the usage of $q or standard Promises in angularjs.
Moreover, there are a lot of related methods in angular which integrates with $q, like $http for example, and for your tests, you will have your life easier treating directly with $q.
So my suggestion is to use $q if possible.
Comment: yes and be sure to trigger the $digest relative to the scope which contains the involved changes.
Comment: If I use `Promise.race` then I should trigger `$digest` in the `then` function of the promise that returns from the race?


Drupal 7 and CSS - How to have a default style for links without affecting other css styles?

Question: I'm theming a Drupal 7 website using Bootstrap and a sub theme that I have put together. I have used CSS to design some of the menus. For this I have included code in the overrides file so as not to hack the original Bootstrap file.
Here's an excerpt from the CSS file to customize the look of a menu.
#block-menu-office li {
  display: inline;
  list-style-type: none;
  padding-right: 20px;
  font-size: 1.1em;
  font-style: bold;
  text-decoration: none;
  text-transform: uppercase;
  padding-right: 0.1em;
  padding-top: 0.1em;
}
This works well.
Now I want to customize how links on the website look like. For some reason they seem to be black with no underline. I want them blue with an underline.
When I add this code, the links do turn blue and show up with an underline. However the menu items also get underlined.
a:link {
    color: red;
}
How do I alter the default appearance of the links without affecting how the menu items look? I added a class to the CSS and used this class in the CKEditor when adding the link to the node. However this seems tedious. I would prefer to have a default appearance or alternatively a default class assigned to each link within the node when it is being created. Thanks!
Answer: First, I would expect that the styling of menu links by Bootstrap would be more specific than the (general) CSS rules you provide for styling links. But a workaround would be to reapply the styling on the menu links in your sub-theme (with more specific CSS rules).
Comment: That's a very useful link. Unfortunately I'm not able to apply it here. I don't know CSS. What I have done is changed the value in the Bootstrap variables file to this: `@link-color:            blue;`  That seems to have solved it for now. Thank you!
Answer: put your general code first... and add a: link to your menu rule... CSS Cascades... and  the more specific you are naming your element the fewer things it touches
Comment: I understand. One of these days I will try and learn CSS. Thanks.


How do I set a color other than black to image created with makeTransparent()

Question: I am using the MakeTransparent() function call on the c# Bitmap object to convert images to transparent images. When this method is called, it will convert a background color to be transparent by setting the alpha channel, but it then converts the background color to black.
I need to find a fast way of converting this background color back to white or whatever the original color was, as occasionally I need to flatten the image to a non-alpha channel enabled format.
Make transparent doesn't seem to have any flags or overloads that allows you to tell it to leave the background color alone, and altering the image pixel by pixel is way to inefficient.  Anyone have any suggestions or GDI tricks to solve this problem?
Comment: It is an internal optimization that you'll have to deal with.  If you want the background to be white then just draw it on a white background.  If you want to restore the original background color then you'll have to remember what it was.
Comment: I can write a function to flatten the image with a background, but it seems like there should be a simpler solution.
Comment: Simply don't use the function then. Do it manually.
Answer: There doesn't seem to be a fast way to do this using the managed code interface. Using individual pixel manipulation, or using unmanaged code to update the pixels seem to be the only real options.
Answer: This is actually possible in managed code, by using Marshal.Copy to copy the backing byte array out of a bitmap object, then editing it, and then copying it back.
So basically, with that general method in mind, you just go over the pixels, line by line, detect which pixels have the colour you want replaced, and set their alpha byte to 0.
Note that "ARGB" refers to the order of the components inside the Int32 value of one read pixel. Since this value is little-endian, the actual order of the bytes at a given offset is the reverse; B = offset + 0, G = offset + 1, R = offset + 2, A = offset + 3.
///
/// Clears the alpha value of all pixels matching the given colour.
///
public static Bitmap MakeTransparentKeepColour(Bitmap image, Color clearColour)
{
    Int32 width = image.Width;
    Int32 height = image.Height;
    // Paint on 32bppargb, so we're sure of the byte data format
    Bitmap bm32 = new Bitmap(width, height, PixelFormat.Format32bppArgb);
    using (Graphics gr = Graphics.FromImage(bm32))
        gr.DrawImage(image, new Rectangle(0, 0, width, height));

    BitmapData sourceData = bm32.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bm32.PixelFormat);
    Int32 stride = sourceData.Stride;
    // Copy the image data into a local array so we can use managed functions to manipulate it.
    Byte[] data = new Byte[stride * height];
    Marshal.Copy(sourceData.Scan0, data, 0, data.Length);
    Byte colR = clearColour.R;
    Byte colG = clearColour.G;
    Byte colB = clearColour.B;
    for (Int32 y = 0; y < height; y++)
    {
        Int32 inputOffs = y * stride;
        for (Int32 x = 0; x < width; x++)
        {
            if (data[inputOffs + 2] == colR && data[inputOffs + 1] == colG && data[inputOffs] == colB)
                data[inputOffs + 3] = 0;
            inputOffs += 4;
        }
    }
    // Copy the edited image data back.
    Marshal.Copy(data, 0, sourceData.Scan0, data.Length);
    bm32.UnlockBits(sourceData);
    return bm32;
}

This can easily be enhanced with a tolerance level instead of an exact match, with something like Math.Abs(data[inputOffs + 2] - colR) < tolerance, or by actually converting the bytes to a colour object and doing some other kind of approximation (like hue/saturation/brightness).


Watch channel in rust

Question: I need help in understanding borrow() and borrow_and_update() both looking similar to me.
#[tokio::main]
async fn main() {
    use tokio::sync::watch;
    use tokio::time::{Duration, sleep};

    let (tx, mut rx) = watch::channel("hello");
    let mut rx2 = tx.subscribe();
    tokio::spawn(async move {
        loop {
            println!("{}! ", *rx2.borrow_and_update());
            if rx.changed().await.is_err() {
                break;
            }
        }
    });

    sleep(Duration::from_millis(1000)).await;
    tx.send("world").unwrap();
    sleep(Duration::from_millis(1000)).await;
}

this is the example that I am using and I can't see any difference while using borrow() and borrow_and_update().
I have read the docs which say borrow_and_seen() will mark the value as seen while borrow doesn't.
can anyone help me understanding these two by giving a suitable example.
Answer: There is a dedicated section in the documentation on when to use which:

borrow_and_update versus borrow
If the receiver intends to await notifications from changed in a loop,
Receiver::borrow_and_update() should be preferred over
Receiver::borrow().  This avoids a potential race where a new value is
sent between changed being ready and the value being read. (If
Receiver::borrow() is used, the loop may run twice with the same value.)
If the receiver is only interested in the current value, and does not intend
to wait for changes, then Receiver::borrow() can be used. It may be more
convenient to use borrow since it's an &self
method—borrow_and_update requires &mut self.

Giving an example that consistently reproduces the loop running twice is hard because it relies on consistently hitting the race condition.

Watch channel in rust


Azure blob storage directory download (win, python)

Question: My goal is to download part of the blob storage that looks like a directory inside other directories.
Official Download to a file path function request a self argument that I don't get how to use and other stack overflow questions often suggest outdated solutions implementing BlockBlobService. I also found  this but it seems not work.
Generally, it seems that I have to loop over blob_list but I have trouble to recreate locally structure of a "directory" in blob storage for different reasons. Sometimes I have .parquet files that are actually folders with snappy compression and etc.
So far I have this code:
import pathlib
blob_service_client = BlobServiceClient.from_connection_string(conn_str)
container_client = blob_service_client.get_container_client(container="container_name")
blob_list = container_client.list_blobs("dir_1/sub_dir_2/desired_dir/")
local_directory = pathlib.Path("local_directory/")

for blob in blob_list:
    local_file_path = local_directory / pathlib.Path(blob.name)
    local_file_path.parent.mkdir(parents=True, exist_ok=True)
    with open(local_file_path, "wb") as local_file:
        print('yes it is downloaded')
        blob_client = container_client.get_blob_client(blob)
        blob_data = blob_client.download_blob()
        blob_data.readinto(local_file)

What is current best way to download a sub_directory to mirror structure on azure blob storage on win machine ?
Answer: After reproducing from my end, I could able to achieve this using os module. Below is the complete code that worked for me.
from azure.storage.blob import BlobServiceClient
import os

ACCOUNT_NAME = "<YOUR_ACCOUNT_NAME>"
CONTAINER_NAME = "<CONTAINER>"

blob_service_client = BlobServiceClient.from_connection_string("<STORAGE_ACCOUNT_CONNECTION_STRING>")
container_client = blob_service_client.get_container_client(CONTAINER_NAME)

local_path = "C:\\Users\\<YOUR_PATH>\\Downloads\\folder"
for blob in container_client.list_blobs():
    blob_client = container_client.get_blob_client(blob)
    blob_props = blob_client.get_blob_properties()
    download_path = os.path.join(local_path+"\\"+"\\".join(blob.name.split("/")[1:-1]), blob.name.split("/")[-1])
    if(os.path.exists(local_path+"\\"+"\\".join(blob.name.split("/")[1:-1]))):
        with open(download_path, "wb") as download_file:
            download_stream = blob_client.download_blob()
            download_file.write(download_stream.readall())
            print(f"Downloaded blob: {blob.name}")
    else:
        os.makedirs(local_path+"\\"+"\\".join(blob.name.split("/")[1:-1]))
        with open(download_path, "wb") as download_file:
            download_stream = blob_client.download_blob()
            download_file.write(download_stream.readall())
            print(f"Downloaded blob: {blob.name}")

In Storage Account:

Here the path is taken from dir2 to the location of the file.
Local Results:
Comment: Thank you greatly for the reply! I had to add a container subdirectory to `.list_blobs():` and this narrowed down selection as I wanted. BUT I still am getting the error `FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\\\new_file.parquet\\_SUCCESS'`
Comment: @euh, Have you tried the same code? if not, can you add what you have tried in the question
Comment: yes almost, I have tried your code but with one modification in the for loop instead of `for blob in container_client.list_blobs():` i have used `for blob in container_client.list_blobs('dir/subdir/'):` to loop over specific directory. it seems to work but in there i have Parquet tables snappy compressed which are ending in `.parquet` but kindof folders themselves, maybe that is causing the issue
Comment: Can you add structure of the folders that you are trying?
Comment: yes it is simply `/main_dir/sub_dir/target_dir/` and target_dir contains multiple `.parquet` files-folders made with snappy compression as i mentioned previously. each of those `.parquet`s has several metadata binary files (like the one with `_SUCESS` that has 0 KB size and give me an error when i try to download blob in the loop) and actual `.parquet` files (so `.parquet` file/folder has inside binary files and other actual `.parquet` files_


P2V Server 2008R2 with vmware converter 4.3.0 No source volumes

Question: I'm trying to P2V a Windows Server 2008R2 to vmware vsphere 4.1 using Vmware vCenter Converter standalone 4.3.
Source Box
<code>Windows Server 2008R2
24GB ram
Dual Quad-Cores
1 Raid 5 drive 680 GB
  3 GB "Recovery" partition
  40 GB OS partition
  637 GB Data partion
</code>
When we try and convert using the stand alone converter and the built in vCenter converter there are no source volumes listed. Has anyone dealt with this before?
Answer: Found out how to do it... On server 2008R2 if you install Vmware vCenter Converter standalone 4.3 on the machine you want to convert and then run the converter as admin it will show you your drives and you'll be able to P2V it.
Comment: Also you can do it remotely but log in as a local administrator.
Comment: So, how do you do this on a Domain Controller???
Comment: This solution aslo applys to a P2V of a Windows 7 Pro computer.


C++ call method from the main Thread

Question: In one of my class i'm launching a thread using the following method:
HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &myThread, NULL, 0, &threadID );

And from this thread I would like to call a method that has to be called from the main thread (the method is interacting with the UI) but I really don't know how to do it since the main thread can't wait until "myThread" notifies it.
I have seen a lot of
while(true){
  //wait something from myThread
}

But I can't wait this way!
Any ideas?
Comment: I can't see how to use EnterCriticalSection() to solve my problem!
Comment: You can use PostMessage()/PostThreadMessage() to notify your main thread from your created thread while staying in the traditional message loop. Depdning on whether your thread needs a response it can then wait for a response using some other synchronisation object and shared resource or you could use a message loop in your created thread and PostThreadMessage() to get the result back.
Comment: What platform or platforms does this have to run on? Threading in C++ is a very platform dependant thing.
Comment: My plateform is Windows!
Comment: You need `EnterCriticalSection()`.
Comment: You might consider using the thread functionality in `C++11`, I'll bet there's a solution in there for you.
Comment: @Wug: I think platform is obvious from the ugly Windows-esqe `HANDLE` code.
Comment: Yeah, that and _beginthreadex (A windows API call) gave it away.  Wasn't sure if OP cared about cross-platform-itude or didn't realize that his code won't work on any other platform
Comment: http://www.codeproject.com/Articles/43994/The-Practical-Guide-to-Multithreading-Part-1
Answer: Since your main thread is UI, you can send a message to it.
#define WM_USER_EXECUTE_MY_CODE (WM_USER + 1000)

Your UI message loop should process the message:
// API code
// LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
// create message map yourself if you're using MFC

if (iMsg == WM_USER_EXECUTE_MY_CODE)
{
    // execute your code must run in main thread
}

And in your worker thread, send UI a message
// HWND hwnd = handle to main UI window
// if you need some parameters, send them through WPARAM or LPARAM
SendMessage(hwnd, WM_USER_EXECUTE_MY_CODE, 0, 0);

Comment: @Ajay I think it depends. If he wants to execute some other code after the call, he has to use SendMessage.
Comment: @darkheir Since your main thread is not UI, assume you're using a console app, your main thread must be waiting to execute the code. Either while(1) loop or WaitForSingleObject will do. Simply set a flag or call SetEvent.
Comment: Should be `PostMessage`, otherwise delay by UI thread will delay overall operation.
Comment: @Rango not the answer i was hoping ^^ I hoped that it was possible to send a message to a non UI thread whitout a waiting loop but it donesn't seem posible!
Answer: You should be able to wait for one or more threads with WaitForMultipleObjects.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
Example:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687055(v=vs.85).aspx
Comment: But don't wait on the thread itself (which waits for it to exit), wait on an event set by the thread (`CreateEvent`, `SetEvent`).
Comment: Yeah but i can't wait for the thread, my UI still need to be reactive!
Comment: You could just use a small timeout so the UI doesn't become unresponsive.  Other answer is better however.

C++ call method from the main Thread


Cloudfoundry: Same domain in two orgs

Question: Is it possible to use the same domain in two different orgs?
I get following error message while trying to add the domain to a second org
Answer: You can share your private domains with any other org by using this CLI command:
cf share-private-domain ORG DOMAIN

Cloudfoundry: Same domain in two orgs


NHibernate second level cache is automatically cleared by NHibernate in web service

Question: I use SysCache2 as the second-level cache provider for NHibernate.
Here is the test code:
<code>`ISession session = NHibernateHelper.GetSession();
Model.Task t1 = session.Get<Model.Task>("e84wqbarscj5");
richTextBox1.AppendText(t1.BuyerAccount.BuyerName);
session.Close();`
</code>
Running the test code for the first time, the console shows that NHibernate executed the sql query twice.
Running the test code for the second time, the console shows that NHibernate has not executed any SQL queries.
And I think it indicates that the second-level cache is working properly.
Next, I execute similar code in a web service, Here is the code:
<code>`AppServiceGetTaskResponse result = new AppServiceGetTaskResponse();
 ISession hSession = NHibernateHelper.GetSession();
 Model.Task task = hSession.Get<Model.Task>(request.TaskId);
 result.BuyerName = task.BuyerAccount.BuyerName;
 hSession.Close();
 retrun result;`
</code>
I use an Http client to access this web service for the first time, the console shows that NHibernate executed the sql query twice. This is fine.
I used the same client to access the web service for the second time, but this time the second-level cache did not work as expected. The console shows that NHibernate executed the sql query twice again.
I made a new attempt and modified the code as follows:
<code>`AppServiceGetTaskResponse result = new AppServiceGetTaskResponse();
 ISession hSession = NHibernateHelper.GetSession();
 Model.Task task = hSession.Get<Model.Task>(request.TaskId);
 result.BuyerName = task.BuyerAccount.BuyerName;
 hSession.Close();
if (result.BuyerName != "")
            {
                hSession = NHibernateHelper.GetSession();
                task = hSession.Get<Model.Task>(request.TaskId);
                result.BuyerName = task.BuyerAccount.BuyerName;
                hSession.Close();
            }
 retrun result;`
</code>
I used the same client to access the modified web service. This time the console showed that NHibernate executed 2 sql queries. The second-level cache seemed to work again.
Finally, I added debug log with log4net and found that NHibernate automatically cleared all the second-level caches. Because if the same code runs in a normal test program, no automatic cleanup will be performed, so I guess it is related to the thread management of web service or session content.
<code>`NHibernate.Impl.SessionFactoryImpl:  2020-02-28 13:17:01,185 DEBUG evicting second-level cache for: Model.BuyerAccount
NHibernate.Impl.SessionFactoryImpl:  2020-02-28 13:17:01,185 DEBUG evicting second-level cache for: Model.Buyer`
</code>
Answer: I solved the problem myself. In the web service, there is a method to write log is executed, it uses the method of executing native SQL: session.CreateSQLQuery("insert into ..."), which causes NHibernate to automatically perform an evict operation on the 2-level cache. I use the session.save() method instead, the problem is resolved.
But I don't understand the principle, can anyone help me answer it?
Comment: When you issue a DML command directly to the database, Nhibernate can no longer ensure cached data consistency. In this case nhibernate will throw away all cached data by considering it invalid. If you are making use of L2 cache, make sure not to use raw SQL queries for Insert/update/delete. You can use the session.CreateQuery instead which uses the HQL and can understand the changes to update cached data.


How to model time series with unevenly spaced observations?

Question: I have three time series of the following form:
$T = T_{2000}, T_{2004}, T_{2008}, …$
$U = U_{1998}, U_{1999}, U_{2000}, U_{2001}, U_{2002}, U_{2003}, …$
$V = V_{1998}, V_{1999}, V_{2000}, V_{2001}, V_{2002}, V_{2003}, …$
I would like to predict $T$ from $U + V$, but since the time series have unequal numbers of observations ($T$ has four times less data points: the series 'coincide' only every four years), I am unsure of how to go with it.
Any help (and software recommendations, preferably with R) would be very much appreciated!
Answer: The biggest mistake that people make with time series forecasting problems is look-ahead bias.
To avoid this bias, it's vital to make explicit a) the date at which we make predictions and b) the date for which we make predictions.
Our model should be capable of incorporating all information available at (or before) the date at which we make predictions.
So you want to make predictions for $T$ which occurs at 4 year intervals. But when do you want to make the predictions?

Do you make a prediction each time a new value of $U$ or $V$ comes in? So, in 2000 you make a 4 year ahead prediction, in 2001 you make a 3 year ahead prediction and so on?
Or do you just want to make predictions every 4 years? In which case your problem is about how to bake the historical values of $U$ and $V$ in to your features.
Or maybe you don't want to forecast the future at all and instead want to try and generate a same time 'nowcast' of $T$.

I suspect from your phrasing that you are looking at option 2.
In this case we can engineer features from $U$ and $V$ that include some history. As a few examples:

Exponentially weighted moving average
Rolling Average
Rolling Z-score
Rolling Standard Deviation
Min/Max values from window

The python package tsfresh has good documentation on feature engineering transforms.
Answer: If you want to use U & V as features what you can do is have rows equal to the number of T observations and since T has a frequency of 4 years hence have 8 features equal to the last 4 years (compared to the year you are predicting) observation of U & V each.
As an example to predict T(2004) use U(2000-2003) & V(2000-2003) as features.
This is just one such way. It might also be that your prediction of U(2008) is dependant on V(1998 ~ 2007). In such case, you might want to model using the past value of T as well since it might capture well the previous values of U & V ( for years >4 )
Comment: So I should just use lags of (T, U, V)? What kind of model is that? AR(x)?
Comment: You will have to check which model works, but Arima etc should work nicely. But I was talking about creating a dataset/features. It makes sense that to predict T(2004) you can only use U < 2004 & V < 2004.
Comment: Alright. I'll wait a bit for additional suggestions, but will start looking into ARIMA straight away.


Como determinar um tamanho fixo para galeria de imagens fancybox?

Question: Estou fazendo uma galeria de imagens com o plugin FancyBox.Estou fazendo a listagem das imagens com o PHP, só que tenho um problema.
Eu vou poder ter imagens com largura e alturas diferentes, então como vou sempre aplicar uma largura e altura fixa para todas as imagens, sem distorcer as imagens, e sem estourar?
Answer: Você precisa criar um elemento de tamanho fixo ao redor da imagem, e com um pouco de CSS você consegue o resultado que procura:

img.max-fit {
  max-width: 100%;
  max-height: 100%;
}

div.img-fit {
  float: left;
  margin: 5px;
  border: 1px solid black;
  width: 300px;
  height: 300px;
  overflow: hidden;
  background-color: #ccc;
  padding: 0;
  //  margin: 0;
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

Exemplo no jsfiddle:
http://jsfiddle.net/kn0yosfd/1/


Encapsular conexões TClientSocket em Multithreads

Question: Tenho um numero X variável de equipamentos eletrônicos (estações Meteorológicas) na minha rede local, cada equipamento fornece uma conexão ServerSocket com um IP e uma Porta específica, tenho uma aplicação desenvolvida em DELPHI XE5 que se conecta a todos esses equipamentos, minha aplicação sabe quais são os IPs e Portas destes equipamentos, pois estão cadastrados no banco de dados, ao abrir minha aplicação, crio dinamicamente uma conexão [TClientSocket (Array)] para cada um destes equipamentos, aos quais posteriormente troco uma série de informações, como uma conversa, pergunto a temperatura a todos os equipamentos e eles me respondem, ou posso pedir a temperatura pra um deles, a umidade pra outro, a velocidade do vento pra outro etc... através de OPERAÇÕES internas.
Hoje faço um laço FOR de todos os equipamentos conectados e a partir disto sei qual operação com o equipamento meu software está e então faço a conversa de forma aleatória com cada equipamento, mas isto é lento, pois conforme aumenta o numero de equipamentos, aumenta a lentidão do FOR. O que quero fazer é uma Thread para eliminar o FOR, gostaria de saber se isso é possível. Os eventos onConnect, OnRead, etc... do meu TClientScojet são atribuídos na criação do TClientSocket Array, portanto acabo tendo essa espera de um usar, depois o outro e não consigo atender todos os equipamentos ao mesmo tempo.
Gostaria de poder usar Thread pra isso e atender todos os equipamentos ao mesmo tempo, mas não domino o conceito e a utilização.
[ATUALIZADO]
Link do source completo, não postei aqui pois passa de mil linhas:
https://mega.co.nz/#!bAVBwTAb!fdzyS9ENPMWul3wC8GFkKATiJ7whKB7Xzgo5FUHlD6M
Hoje utilizo esta classe que criei estendida da TClientSocket:
type
  TTermoCenter = class(TClientSocket)
  private
    countSema: Thandle;
    access: TCriticalSection;
    ...
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Push(inObject: TPalavra; priority: Integer); virtual;
    function Pop(pResObject: pObject; timeout: Integer): Boolean;
  end;

Aqui está o constructor:
constructor TTermoCenter.Create(AOwner: TComponent);
var
  I: Integer;
begin
  inherited;
  access := TCriticalSection.Create;
  ...
end;

Aqui está o destructor:
destructor TTermoCenter.Destroy;
var
  I: Integer;
begin
  ...
  access.Free;
  closeHandle(countSema);
  inherited;
end;

declaração da variável:
var
  termocenters: array of TTermoCenter;

Ao criar o meu Form, defino o tamanho do meu Array
SetLength(termocenters, dm.sqlTermocenter.RecordCount);

E crio as minhas conexões baseada no que está no banco de dados:
    var
      SocketTmp: TTermoCenter;
  while not cds.Eof do
  begin
    SocketTmp := TTermoCenter.Create(nil);
    SocketTmp.name := 'cdsNome';
    SocketTmp.Port := 'cdsPorta';
    SocketTmp.ClientType := ctNonBlocking;
    SocketTmp.Host := 'cdsIP';
    // atribui eventos
    SocketTmp.OnRead := TCPRead;
    SocketTmp.OnConnect := TCPConnect;
    SocketTmp.OnDisconnect := TCPDisconnect;
    SocketTmp.OnError := TCPError;

    //Coloca no Array
    termocenters[I] := SocketTmp;
    try
      termocenters[I].Active := True;
      sleep(1000);
    except
      on E: Exception do
        frmMain.mmErros.Lines.Add(TimeToStr(now) + ' - ' + E.ClassName + ' CriaConexao : ' + E.Message);
        end;
      end;
    end;
  cds.Next;
end;
end;

Esse é um código bem resumido do que tenho hoje, gostaria de uma ajuda pra implementar Threads.
Comment: @AlexSchmitt O meu comentário anterior expõe a mecânica do StackOverflow. Você precisar deixar a pergunta mais específica. Veja que não sou o único a conhecer esta mecânica (óbvio e felizmente) de modo que sua pergunta foi suspensa pela comunidade. Sinta-se convidado a participar do StackOverflow sempre que achar válido trabalhar de acordo com a comunidade (a qual não trata indivíduos e sim perguntas e respostas).
Comment: Qual a versão do Delphi que você está utilizando, no XE7 existem muitos facilitadores para threads. Você deveria quebrar sua pergunta em várias perguntas específicas. "se alguém souber como posso melhorar este código, fico muito grato.", threading é um conceito complexo que envolve várias teorias e regras, não peça pelo código pronto, você deveria ir tentando e postando perguntas a cada demanda de dúvidas. Para começar [leia esses artigos](http://cc.embarcadero.com/item/14809). Nota: Está em inglês.
Comment: Mesmo com threads você ainda precisará de um for, acredito. No entanto as conexões serão feitas de forma paralela. Não conheço nada de Delphi, mas espero que você consiga boas respostas.
Comment: Pelo que entendi, dá pra identificar duas necessidades nesta pergunta: a) Conceito e utilização de threads em Delphi. b) Implementar neste sistema o uso threads para comunicação paralela com as estações meteorológicas. Para o item "a", recomendo este artigo: http://devutils.blogspot.com/2009/01/threads-conceito-e-exemplo.html. Para o item "b", recomendo tentar a implementação a partir da leitura do artigo e daí postar aqui as dificuldades encontradas. Faz sentido?
Comment: @Caffé faz todo o sentido, é isto mesmo que quero.
Comment: Segue o Source completo https://mega.co.nz/#!bAVBwTAb!fdzyS9ENPMWul3wC8GFkKATiJ7whKB7Xzgo5FUHlD6M
Answer: Vou concordar com o @PageNotFound, que sua questão está muito ampla e aguardando um código funcional.
Posso lhe dar uns passos para guiar. Segue um exemplo usando Generics, Annonymous Methods e um recurso de Thread anônimas:
A idéia é ter um pool de conexões e ter um método que cria uma Worker thread para cada conexão para realizar uma tarefa específica
interface

uses
  System.Generics.Collections, Datasnap.Win.SConnect;

type
  TPoolConexoes = class(TObjectList<TSocketConnection>)
  private
    procedure SeuMetodoQueUsaConexao(const aConexao: TSocketConnection);
  public
    function NewConnection: TSocketConnection;
    function ObterConexoesPorStatus(const aStatus: string): TPoolConexoes;

    procedure ExecutarSeuMetodoParaLista(const Conexoes: TPoolConexoes);
  end;

implementation

uses
  System.Classes;

{ TPoolConexoes }

procedure TPoolConexoes.ExecutarSeuMetodoParaLista(const Conexoes: TPoolConexoes);
var
  conexao: TSocketConnection;
  threadAtual: TThread;
begin
  for conexao in Conexoes do
  begin
    threadAtual := TThread.CreateAnonymousThread(
      procedure
      begin
        Self.SeuMetodoQueUsaConexao(conexao);
      end
    );
    threadAtual.FreeOnTerminate := True;
    threadAtual.Start;
  end;

end;

function TPoolConexoes.NewConnection: TSocketConnection;
var
  conexaoTemp: TSocketConnection;
begin
  conexaoTemp := TSocketConnection.Create(nil);
  Self.Add(conexaoTemp);
  Result := conexaoTemp;
end;

function TPoolConexoes.ObterConexoesPorStatus(const aStatus: string): TPoolConexoes;
begin
  //sua logica aqui
end;

procedure TPoolConexoes.SeuMetodoQueUsaConexao(const aConexao: TSocketConnection);
begin
  //usa a conexao para fazer algo
end;

end.

Você ainda pode colocar todas as thread criadas em uma ThreadList e gerenciar o fim delas
Ou pode estender a classe de thread para conter o código da execução ao invés de usar os anonimos e manter as threads em um pool que irá executando OnDemand
Tudo depende das suas necessidades
Comment: Obrigado amigo, segue o link do Source

https://mega.co.nz/#!bAVBwTAb!fdzyS9ENPMWul3wC8GFkKATiJ7whKB7Xzgo5FUHlD6M


Grade Marking Python Program, Not Expected Output

Question: Here are the rules to my assignment:
You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores.
Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called student_grades that should contain student names for keys and their grades for values. The final version of the student_grades dictionary will be checked.
DO NOT modify lines 1-7 to change the existing student_scores dictionary.
This is the scoring criteria:
Scores 91 - 100: Grade = "Outstanding"
Scores 81 - 90: Grade = "Exceeds Expectations"
Scores 71 - 80: Grade = "Acceptable"
Scores 70 or lower: Grade = "Fail"
Expected Output
'{'Harry': 'Exceeds Expectations', 'Ron': 'Acceptable', 'Hermione': 'Outstanding', 'Draco': 'Acceptable', 'Neville': 'Fail'}'

Here is my code:
student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99,
  "Draco": 74,
  "Neville": 62,
}
#  Don't change the code above

#TODO-1: Create an empty dictionary called "student_grades."

#TODO-2: Write your code below to append the grades to student_grades.
student_grades = {}
gradeslist = []
for student in student_scores:
    if student_scores[student] <= 100 and student_scores[student] >= 91:
        gradeslist.append("Outstanding")
    elif student_scores[student] <= 90 and student_scores[student] >= 81:
        gradeslist.append("Exceeds Expectations")
    elif student_scores[student] <= 80 and student_scores[student] >= 71:
        gradeslist.append("Acceptable")

    else:
        gradeslist.append("Fail")

for key in student_scores:
    for num in range(0, len(student_scores)-1):
        student_grades[key] = gradeslist[num]

#  Don't change the code below
print(student_grades)

OUTPUT
{'Harry': 'Acceptable', 'Ron': 'Acceptable', 'Hermione': 'Acceptable', 'Draco': 'Acceptable', 'Neville': 'Acceptable'}
Why Is This Happening?
Comment: So what is your question?
Comment: The Output: {'Harry': 'Acceptable', 'Ron': 'Acceptable', 'Hermione': 'Acceptable', 'Draco': 'Acceptable', 'Neville': 'Acceptable'}
Comment: hint: you do not need a temporary "list of grades". Just make a **dictionary** of student grades and fill it in in your main loop.
Comment: One of the first things you do during debugging is to put in `print()` calls at various points to see what the values of your various variables are. I suggest doing that to track what values are actually being calculated. Second, instead of doing `if student_scores[student] <= 100 and student_scores[student] >= 91`, use `if 91 <= student_scores[student] <= 100`.
Comment: @JavaApprentice2022 `gradeslist` is redundant. Update `student_grades` inside the first for-loop using the name and grade. The other for-loop isn't needed.
Answer: for key in student_scores:
    for num in range(0, len(student_scores)-1):
        student_grades[key] = gradeslist[num]

This loop sets every student to the first value in gradeslist, then sets every student to the second value in gradeslist, and so on.
As a side note, they all got "Acceptable" instead of "Fail" because the interval returned by range() includes the starting number but not the ending number, so range(0, len(student_scores)-1) produced values 0-3.


Add class that surrounds all tables (or any other node,field etc...) using preprocess template?

Question: I have been able to find information on adding classes to tables and other items in my pages, however, I cannot find any information on wrapping the entire table for example in a div through the preprocess function.
I added this for example:
function bootstrap_preprocess_views_view_table(&$vars) {
    $vars['classes_array'][] = 'table table-striped';
}

My tables are stripped which is what I was after, however, I would like to wrap the entire table itself in
{TABLE}
, but am not finding where / how to add the class to show before the table?
Adding a picture of where it could be added:
Comment: This post that helped out a little: http://drupal.stackexchange.com/questions/104960/how-to-add-wrapping-elements-classes-to-a-table-in-a-view. However, it is still not working due to the table-responsive being a couple divs up. Not sure why it worked for the OP there.
Answer: you can override views-view-table.tpl.php template to achieve this.
Like :

<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
   <?php if (!empty($title) || !empty($caption)) : ?>

<?php print $caption . $title; ?>

  <?php endif; ?>
  <?php if (!empty($header)) : ?>

        <?php foreach ($header as $field => $label): ?>
          <th <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
            <?php print $label; ?>

        <?php endforeach; ?>

  <?php endif; ?>

    <?php foreach ($rows as $row_count => $row): ?>
      <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
        <?php foreach ($row as $field => $content): ?>
          <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
            <?php print $content; ?>

        <?php endforeach; ?>

    <?php endforeach; ?>

Get a look for override views template here
For other tables Override theme_table and change its return statement Like:
return '
'.$output.'
';


All possible values of coordinate k such that triangle ABC is a right triangle?

Question: Determine all values of $k$ for which the points $A = (1,2),$ $B = (11,2),$ and $C = (k,6)$ form the vertices of a right-angled triangle.
Comment: Now, I remember, it's not the first time that you do not want to enter into contact: you are the author of "Area of Overlap between two rotated squares?" (https://math.stackexchange.com/q/2592345) for which many valuable answers had been given : not a single comment from you !
Comment: Are integer values of $k$ required, or any real values?
Comment: The raw question, without comments, without desire to enter into an exchange with us ... As you are not new on the site, you should know that we want askers to show that they have worked on the issue.
Answer: Hint:
If the right angle is at $A$, $k=1$.
If the right angle is at $B$, $k=11$.
If the right angle is at $C$, then $AC\perp BC$. We can find $k$ easily by considering the product of the slopes.
Answer: Hint:
a) If $\triangle ABC$ is riht-angled at $A$, then $AC$ is vertical, i.e. $k=1$.
b) If $\triangle ABC$ is riht-angled at $B$, then $BC$ is vertical, i.e. $k=11$.
c) If $\triangle ABC$ is riht-angled at $C$, then $m_{BC}m_{CA}=-1$.
Answer: we have $$AB^2=100,BC^2=(k-11)^2+4^2,AC^2=(k-1)^2+4^2$$ and solving the equation $$AB^2=AC^2+BC^2$$ for $k$ we get $$k_1=3$$ or $$k_2=9$$ can you proceed?
Answer: $\vec{AB}=(10,0)$ and we know that either $\vec{AC}=(k-1,4)$ or $\vec{BC}=(k-11,4)$ must be orthogonal to $\vec{AB}$, or that $\vec{AC}$ and $\vec{BC}$ are orthogonal.
$0=\langle(10,0),(k-1,4)\rangle=10(k-1)$ iff $k=1$ and
$0=\langle(10,0),(k-11,4)\rangle=10(k-11)$ iff $k=11$ and
$0=\langle(k-1,4),(k-11,4)\rangle=k^2-12k+11+16=(k-3)(k-9)=0$ iff $k=3$ or $k=9$.
So $k$ is either $1$, $3$, $9$ or $11$.
Answer: If the right angle is at $A$, then $k=1$. If the right angle is at $B$, then $k=11$. If the right angle is at $C$, then the product of the slope of $AC$ and $BC$, is $-1$, or, $$\frac{6-2}{k-1}\cdot\frac{6-2}{k-11}=-1$$
Sobe this quadratic in $k$ to get the values of $k$ for which the right angle is at $C$.


Distinct vs Identical

Question: In a bag containing 20 balls(6 red), (6 green), (8 purple)
We draw 5 balls, put them back in the bag, then draw 5 more.

In how many ways can this be done if the balls are considered
distinct?

My book doesn't describe distinct vs identical well but my assumption is that distinct would include both
{red1, red2, red3} and {red3, red2, red1}
where identical would not?

So my answer would disregard color and be: 20!/(20-5)!

So my question for this post would be am I understanding this correctly or is this completely wrong?
Answer: If each ball is distinct, think of the balls as having numbers on them. The order in which the five balls are drawn doesn't matter. So there are $\binom{20}{5}$ options for the first draw. Since we replace the balls, we have $\binom{20}{5}$ ways to draw the second set. The first draw is independent of the second draw, so by rule of product we have $\binom{20}{5} \cdot \binom{20}{5}$.
If the balls are identical (no numeric labels on the balls), we have the stars and bars problem. Since we are drawing five balls and there are at least six balls of each kind, the solution is $\binom{5 + 3 - 1}{5}$. If there were say, four red balls, the solution would require more analysis.
To see this, we have the equation: $x_{r} + x_{g} + x_{p} = 5$ s.t. $x_{r}, x_{g} \leq 6$ and $x_{p} \leq 8$. Clearly, the constraints don't matter here, since we will never be drawing six balls. Thus, we can directly apply the Stars and Bars theorem to get $\binom{5 + 3 - 1}{5}$ ways to choose a single draw. Notice with the equation I gave, we don't care about drawing a red first, then a green, then another red. We just care about the number of reds present or the number of greens present.
Since we have replacement after the first draw, this is the same quantity for the second draw. And so by rule of product, we have: $\binom{5 + 3 - 1}{5} \cdot \binom{5 + 3 - 1}{5}$ as our answer.

Distinct vs Identical


Rename Files but do not explicitly know the file extension

Question: So I have a csv file that has two columns, OrigFilename|NewFilename and I have a directory with over 1k files. The issue is, my list does not have file extension.  How would I go about renaming the file, to the new filename without explicitly defining a file extension but instead just use the extension that is in the original filename?
This is what I have but it requires the file extension. I'm having an issue of formulating a hash table to get the extension in there.
$Renames = Import-csv "C:\Users\admin\Desktop\pull\rename.csv" $TargetDir = "C:\Users\admin\Desktop\pull" $RenHash = @{} $Renames | ForEach-Object { $RenHash[$.OName]=$.NName } Get-ChildItem -Path $TargetDir -Recurse -Include $Renames.OName | Rename-Item -NewName {$RenHash[$_.Name]}
Comment: What tools do you have?  Can you write PowerShell, assuming you're on Windows? Any  programming languages you know?
Comment: This is what i have but it forces me to define the file ext.

$Renames = Import-csv "C:\Users\admin\Desktop\pull\rename.csv"
$TargetDir = "C:\Users\admin\Desktop\pull"

$RenHash = @{}
$Renames | ForEach-Object { $RenHash[$_.OName]=$_.NName }

Get-ChildItem -Path $TargetDir -Recurse -Include $Renames.OName |
    Rename-Item -NewName {$RenHash[$_.Name]}
Comment: Pardon, I was asking about your abilities as a programmer.  If you know PowerShell, (and are on a Windows computer), we can give an answer in PowerShell. If not, but you know C#, we can answer in C#, etc.
Comment: my bad, windows and PS is great!
Comment: Any assistance is greatly appreciated.
Answer: This works for me.   Note that I changed the header line in your csv from OrigFilename|NewFilename to OrigFilename,NewFilename so it too is comma-delimited like the rest of your file presumably is.
I didn't test recursing into folders, or files with the same name but different extensions.
$Renames = Import-csv ".\fromTo.csv"

$TargetDir = "files"

$Renames | ForEach-Object {
  $file = Get-ChildItem -Path $TargetDir -Recurse -Include ($_.OrigFilename + ".*")
  $ext = [System.IO.Path]::GetExtension($file)
  $newName = $_.NewFilename + $ext;
  Rename-Item  -Path $file -NewName $newName
}

Comment: Thanks...i really need to get on board with all the ps objects. reading what you developed makes so much sense...thanks!!!


Monitoring/Alerting On Log File Change In Windows

Question: Does anyone know of a simple tool that will email me every time a new change is added to a log file?  I have an issue that I'd like to be notified of right away, but the only way I'd know if by monitoring this file.
I've seen a few tools that do this, but they're more geared towards running interactively on the desktop and notifying you that way, as opposed to running as a service on a server.  I've also seen file integrity checkers that are part of a tripwire/IDS, but it's usually part of a bigger suite.
I'm sure I could just write this in powershell, but I imagine there already is a simple tool like this out there and I just haven't found it yet.
Edit: To clarify, I'm speaking about a txt file, not windows logs.
Comment: What do you need to monitor specifically? In many cases the event viewer can be setup to monitor & send emails without the need for 3rd party solutions.
Answer: Logstash can consume windows event logs, and can alert on them via a number of mechanisms (SMTP, XMPP, etc.)
http://logstash.net/docs/1.4.0/inputs/eventlog


How do I add attributes to a single menu's links?

Question: I want to add some BEM classes to a single menu's links. I cannot find a way to do this in Drupal's GUI so I assume this must be done programmatically.
How would you go about this exactly? I've no idea what file any function would even go on...
Answer: You might try the Menu Attributes module.  This looks like it will do what you want.
Answer: For drupal 8 try Menu Link Attributes or Link Attributes widget


Show How to Generate a Poisson Random Variable with Parameter $\lambda$ using Metropolis-Hastings

Question: Additionally: Use a simple symmetric random walk as the proposal distribution.
Source: "Introduction to Stochastic Processes with R" - Robert P. Dobrow, Chapter 5 Exercises: Question 5.6

I know this is typically done in software but I want to comprehend the method by hand. I feel very uncomfortable with my comprehension of Bayesian Statistics:
I have $u$ ~ $Uniform(0,1)$
My understanding is that the above is my prior and the likelihood is the density function I want to derive samples from.
But how do I create my acceptance function? My professor presented it as having a random walk starting at state $k=0$, and moving to $k=1$ if $u < \lambda$ and then moving left or right with probability $.5$ (he says just flip a coin. Basically if heads move right, if tails move left).
Then move to the proposal state with the following criteria:
Move to k-1 if,
$$u< \frac{\frac{e^{-\lambda}\lambda^{k-1}}{(k-1)!}}{\frac{e^{-\lambda}\lambda^{k}}{k!}} = \frac{\lambda}{k+1}$$
Similar procedure for moving to (k+1).
What confuses me is how to tie this into the the acceptance probability that is always taught when learning Metropolis-Hastings. Namely,
$$a(i,j) = \frac{\pi_{j} T_{ji}}{\pi_{i}T_{ij}}$$
Sorry if this question is messy. I've been spending so much time on this and am still struggling to wrap my mind around it. Thank you for your answer in advance! I appreciate all help!
Comment: The problem states "Use simple symmetric random walk as the proposal distribution." Does this mean $P_{01} = 1$ or $P_{00}=1-p$ and $P_{01}=1-p$?
Answer: Assume $T_{00}=1-p=1-T_{01}$, where $T$ is the transition matrix of the random walk Markov chain. Let $\pi_i=\frac{\lambda^i}{i!}e^{-\lambda}$ for $i=0,1,\ldots$. Assume WLOG that $X_0=0$ and define
$$
a(i,j) = \frac{\pi_j T_{ji}}{\pi_i T_{ij}} = \begin{cases}
1,& i=j=0;\\
\frac{ip}{\lambda(1-p)},& j=i-1\\
\frac{\lambda(1-p)}{(i+1)p},& j=i+1.
\end{cases}
$$
Let $U_{n+1}\sim \mathsf{Unif}(0,1)$ and set
$$
X_{n+1} = \begin{cases}
j,& U\leqslant a(i,j)\\
i,& U>a(i,j).
\end{cases}
$$
Then $\{X_n :n=0,1,\ldots\}$ is a reversible Markov chain with stationary distribution $\pi$, as desired. Here's some $\texttt{R}$ code I wrote to simulate this:
<code>lambda <- 2.5

p <- 0.45

N <- 10000

X <- rep(as.numeric(0),N)
a <- rep(as.numeric(0),N)

for(n in 1:N) {
  if(X[n] == 0) {
    X[n+1] <- X[n] + rbinom(1,1,p)
  }
  else {
    X[n+1] <- X[n] + 2 *(rbinom(1,1,p) - 0.5)
  }

  if(X[n+1] == X[n])
    a[n] <- 1
  else if(X[n+1] == X[n] - 1)
    a[n] <- p *X[n]/(lambda*(1-p))
  else
    a[n] <- lambda*(1-p)/(X[n+1]*p)

  if(a[n] < runif(1,0,1)) {
    X[n+1] <- X[n]
  }
}

plot(ecdf(X), lwd=2, col="blue")
lines(0:9, ppois(0:9,lambda), col="red", type="l", lwd=2, lty=3)
</code>


Problem with Invoking Octave commands from c#

Question: I am trying to use surf function of Octave to plot 3d data from my c# application.
I use Process.Start() to start Octave and Process.WriteLine() to send commands
The same method works fine to plot using gnuplot but it's not working with Octave
Process octavePro;
        StreamWriter octaveStWr;
        string octavepath = @"C:\Octave\Octave-188.8.131.52\mingw64\bin\octave-cli-5.1.0.exe";

    private void button1_Click(object sender, EventArgs e)
    {
        octavePro = new Process();
        octavePro.StartInfo.FileName = octavepath;
        octavePro.StartInfo.UseShellExecute = false;
        octavePro.StartInfo.RedirectStandardInput = true;
        octavePro.StartInfo.RedirectStandardOutput = true;
        octavePro.StartInfo.RedirectStandardError = true;
        octavePro.StartInfo.CreateNoWindow = false;
        octavePro.OutputDataReceived += new DataReceivedEventHandler(InterProcOutputHandler);
        octavePro.ErrorDataReceived += new DataReceivedEventHandler(InterProcOutputHandler);

            octavePro.Start();
            octaveStWr = octavePro.StandardInput;
            Thread.Sleep(100);
            octaveStWr.WriteLine("info");
            octaveStWr.WriteLine("surf([1 2 3; 2 3 4; 3 4 5])");
            octaveStWr.Flush();
        }

When I execute the two command "info" and "surf([1 2 3; 2 3 4; 3 4 5])" in Octave-CLI, I get application information and 3d plot for the data respectively.
But when I try to execute it from C# application, only a terminal window is started and nothing is displayed in the window.
Answer: You may need to increase the sleep time for the initialization of Octave. Depending on the duration of each command you may need add more sleeps. Also use waitfor to suspend the execution of Octave until the figure is closed.
octavePro.Start();
octaveStWr = octavePro.StandardInput;
octavePro.BeginOutputReadLine();
octavePro.BeginErrorReadLine();
Thread.Sleep(5000);
octaveStWr.WriteLine("info");
Thread.Sleep(1000);
octaveStWr.WriteLine("waitfor(surf([1 2 3; 2 3 4; 3 4 5]))");

Comment: thanks for informative answer
"waitfor" solved the problem.
but what if I need to update the plotting in realtime without closing the figure?
Comment: with timeout property of "waitfor" function, the min timeout is 1 sec. which limits the refresh rate.
Is there any work around to improve the refresh rate?
Comment: Sorry for late reply. You can use `uiwait`. Consider the following example : `octaveStWr.WriteLine("for i=1:10;imshow(rand(100),[]);drawnow;end;");octaveStWr.WriteLine("uiwait()");`


Terraform, ecs service creation fails when using a configured IAM policy

Question: Using Terraform, ecs service creation fails when using a configured IAM policy.
Error applying plan:

1 error(s) occurred:

* aws_ecs_service.beatthemarket_service: InvalidParameterException: Unable to assume role and validate the listeners configured on your load balancer.  Please verify the role being passed has the proper permissions.
    status code: 400, request id: ba3a3fb8-0972-11e6-a877-954fd57ba1a9

This seems to correspond with this issue.
But I can't seem to fix it, even after adding a policy. I also don't think this is a timing issue, as the role already exists , after trying to terraform apply several times.
So far I just have an IAM role, policy, an ELB, and ECS cluster, service and task definition. Do I need anything else, like an Autoscaling group, Launch configuration, Instance profile or Security group?
Is there anything obvious missing, that explains why the service can't accept the role I've configured? The role seems to have all the correct permissions.
resource "aws_iam_role_policy" "beatthemarket" {
  name = "beatthemarket"
  role = "${aws_iam_role.beatthemarket.id}"
  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "ec2:*",
        "ecs:*",
        "iam:*",
        "elasticloadbalancing:*"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}
EOF
}

Answer: Turns out I needed to set the service to ecs.amazonaws.com and not ec2.amazonaws.com in my aws_iam_role. I'd tried this before, but didn't specify sufficient in the aws_iam_role_policy . It's very much like this issue on the AWS forums.
resource "aws_iam_role" "beatthemarket" {
    name = "beatthemarket"
    assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ecs.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

For future referencing, hope this helps someone.


Find the area between the following curves and their asymptotes.

Question: The curve is given by the polar equation  $ r = a( \sec \theta + \cos \theta) $
At $\theta = \pi /2, r$ goes to infinity, so asymptotes should be at $\theta = \pi /2$
To find the area I integrated $2$ $ \frac{a^{2}(\sec \theta + \cos \theta)^{2}}{2} $ ($= r^{2}/2  \times 2$, since curve is symmetric about $x$ axis) with respect to $\theta$ from $0$ to infinity and got infinity.
But answer is given $5 \pi a^{2}/2$
Where did I go wrong$?$
Comment: You did not find the polar equation of the asymptote.
Comment: Why do you integrate $r^2$? Explain what is your area element
Comment: I think you want to integrate from 0 to $\pi/2$ (not to infinity).
Answer: We are given the curve
$$ r = a( \sec \theta + \cos \theta) \tag{1}$$
but we are not given the asymptote.
It is clearly a vertical asymptote of the form $x=$constant, but what is the constant?
So what is happening to $x=r\cos\theta$ as $\theta\to\frac{\pi}{2}$?
We can find this out by multiplying equation (1) by $\cos\theta$ to obtain
$$ r\cos\theta = a( 1 + \cos^2 \theta) $$
Since $\cos(\pi/2)=0$ we see that as $\theta\to\frac{\pi}{2}$, $r\cos\theta\to a$.
So the vertical asymptote of the curve is $x=a$.
In polar coordinates this is $r\cos\theta=a$
So $r=a\sec\theta$ is the polar equation of the asymptote of the function.
So the area between the function and its asymptote can be found by the following:
$$ \int_0^{\pi/2} a^2(\sec\theta+\cos\theta)^2-a^2\sec^2\theta\,d\theta $$
We shall see that $\dfrac{5\pi a^2}{2}$ is not the correct answer.

\begin{eqnarray}
  \int_0^{\pi/2} a^2(\sec\theta+\cos\theta)^2-a^2\sec^2\theta\,d\theta&=&
  a^2\int_0^{\pi/2}2+\cos^2\theta\,d\theta\\
  &=&a^2\int_0^{\pi/2}2+\frac{1+\cos2\theta}{2}\,d\theta\\
  &=&a^2\left[\frac{5}{2}\theta+\frac{1}{4}\sin(2\theta)\right]_0^{\pi/2}\\
  &=&\frac{5\pi a^2}{4}
  \end{eqnarray}
Comment: Since the curve is symmetric about x axis, so area should be multiplied by 2, I think.
Comment: Yes, it has been multiplied by two, cancelling the 2 in the denominator of the integrand.  $2\int \frac{f^2(\theta)}{2}\,d\theta=\int f^2(\theta)\,d\theta$.
Comment: Oh, yes I got it. Thanks.
Comment: 'It is clearly a vertical asymptote of the form =constant' , sir , i am new to polar equations and curve tracing ,how is the asymptote vertical ?
Comment: @HarshVardhanSingh Because $y=r\sin\theta=a(\tan\theta+\sin\theta\cos\theta)\to\infty$ as $\theta\to\dfrac{\pi}{2}$ whereas $x=r\cos\theta=a(1+\cos^2\theta)$ approaches a constant.
Answer: (1) calculating areas made by polar plots in polar coordinates is done with the help of a special integration formula.
(2) polar coordinates transformation (moving to another origin) is needed, because the area is not exactly measured from the origin like it's usually calculated as in the explanations. See this and this also.
Transform the polar equation ($-\frac{\pi}{2}<\theta < \frac{\pi}{2}$) $$r = a \cdot (\sec(\theta)+\cos(\theta)) $$ to the following equivalent parametric equation using $x=r \cdot \cos(\theta)$ and $y=r \cdot\sin(\theta)$ $$\begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} r \cdot \cos(\theta) \\ r \cdot \sin(\theta) \end{bmatrix} = \begin{bmatrix} (a\cdot (\sec(\theta)+\cos(\theta)) ) \cdot \cos(\theta) \\ (a\cdot (\sec(\theta)+\cos(\theta))) \cdot \sin(\theta) \end{bmatrix} = a \cdot \begin{bmatrix} 1+\cos^2(\theta) \\ \tan(\theta)+\cos(\theta)\sin(\theta) \end{bmatrix}$$
Now move the $x$-koordinates of the points on the curve by an amount of $a$ to the left. When $\theta = 0$ or when you're on the $x$-axis, you want that point on the curve lying on the $x$-axis to be at $x = a$ and not at $x = 2a$. So, you subract an $a$ from all the $x$-koordinates or you take $x-a$. The shifted curve by $a$ to the left is:
$$\begin{bmatrix} x \\ y \end{bmatrix} = a \cdot \begin{bmatrix} \cos^2(\theta) \\ \tan(\theta)+\cos(\theta)\sin(\theta) \end{bmatrix}$$
We could directly calculate the area for this parametric curve (Notice the change of the variables $x$ and $y$ for our purposes. This is like rotating the coordinate system or exchanging the roles of $x$ and $y$, because this given formula in these notes calculates the area between the parametric curve and the $x$-axis and we want to calculate the are between the parametric curve and the $y$-axis):
$$
\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} x(\theta)\frac{d y(\theta)}{d \theta} d\theta
=
a^2 \cdot \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\cos^2(\theta) \cos( 2 \theta)+\cos^2(\theta)\sec^2(\theta)  d\theta
=
\frac{5a^2\pi}{4}
$$


Transcendental terms

Question: What does it mean for two curves parametrised about 0 (say the graph of two functions of real variable) to 'differ only by transcendentally small terms'? How does this relates to their Taylor expansion at 0?
Answer: After some research in the direction of asymptotic series expansions, I think the meaning of transcendentally small is that it vanishes faster than any polynomial order. For example, for a power series expansion of the curve's equation, transcendentally small terms could be terms that vanish faster than any monomial involved in the power series representing it. Hence the two curves will have the same power series expansion, without being the same curve, since the 'transcendentally small terms' elude the description via power series, being described by the null power series themselves.

Transcendental terms


If $g(z)^3$ is analytic and $g(z)$ is continous, then $g(z)$ is analytic

Question: To be precise, $f(z)$ and $g(z)$ are complex-valued functions defined on a region $S$ of $\mathbb{C}$. My question is, if we know that $g(z)$ is continuous on $S$, $f(z) = g(z)^3$, and $f(z)$ is analytic on $S$, how do we show that $g(z)$ must be likewise analytic on $S$? And furthermore, does this extend to other powers, that is, the condition $f(z) = g(z)^3$ being replaced with $f(z) = g(z)^n$ for some integer $n$?
Comment: The answer in this post by J.Loreaux worth being mentioned: https://math.stackexchange.com/questions/188359/when-does-a-complex-function-have-a-square-root/188433
Answer: We need $n \neq 0$ of course, since $g^0$ is the constant, hence analytic, function $z \mapsto 1$, whatever $g$ is.
For $n \neq 0$, we can conclude that $g$ is analytic if $f$ is. If $f \equiv 0$, then clearly $n > 0$ and $g \equiv 0$. Otherwise, $f$ has only isolated zeros, and for $n < 0$ it can't have any. If $f(z)$ is nonzero on a small disk $D \subset S$, then there are $\lvert n\rvert$ holomorphic branches of $f^{1/n}$ on $D$. By continuity, $g$ must be one of those branches, hence $g$ is holomorphic on $D$. Thus we found that $g$ is holomorphic on $S\setminus f^{-1}(0)$. Since the zeros of $f$ are isolated, it follows that $g$ is holomorphic on $S$ by the Riemann removable singularity theorem.
Answer: Since in the case of complex functions analytic and holomorphic is equivalent (this is a major theorem of complex analysis) we can try to calculate $\dfrac{\partial g}{\partial\bar z}$.
We have $f(z)=h\circ g(z)$ where $h(z)=z^3$.

If we suppose $g$ at least $C^1(\mathbb R^2)$ then we can derivate
$\dfrac{\partial f}{\partial\bar z}=\bigg(\underbrace{\dfrac{\partial h}{\partial z}}_{3z^2}\circ g\bigg)\times\dfrac{\partial g}{\partial\bar z}+\bigg(\underbrace{\dfrac{\partial h}{\partial\bar z}}_{0}\circ g\bigg)\times\dfrac{\partial\bar g}{\partial\bar z}=3\,g^2\dfrac{\partial g}{\partial\bar z}=0$
And can conclude that $\dfrac{\partial g}{\partial\bar z}=0$ whenever $g(z)\neq 0$.
Thus $g$ is analytic at least on $S\setminus g^{-1}(0)$
Although the existence of such $g$ is not straightforward, this is greatly weakening the interest of this method, but somehow explains why $S\setminus g^{-1}(0)$ appears.
For more details on the existence of n-roots of $f$ see the post I linked in the general comments section.
Comment: A problem here is that a priori, we don't know that $\frac{\partial g}{\partial \overline{z}}$ exists. At least in the classical sense.
Comment: @DanielFischer Hmm, I see and agree. I'm adding restrictions to this answer.
Answer: $g$ is certainly analytic in $S\setminus\{0\}$. By continuity, the singularity at $0$ is removable, hence $g$ is analytic in all of $S$.
Comment: No, $g$ is analytic on $S$ minus the zero set of $g.$ At the points in the zero set, we can do what you mentioned.
Answer: $g$ is analytic in
$$
S\setminus g^{-1}(0),
$$
and continuous in $S$, and hence it is analytic in the whole of $S$ (removable singularities), since the elements of $g^{-1}(0)$ do not have an accumulation point in $S$.
Comment: I get the part about the removable singularities leading to $g$ being analytic on $S$, but I still don't get why $g$ has to be analytic on $S \setminus g^{-1}(0)$
Comment: @NgE-Jay $g^3=f$ shows that $g$ is bounded near each singularity...
Comment: But if we know $g(z)$ is merely continuous on $S$, how does being bounded around each singularity imply $g(z)$ analytic? I think zwim's comment above using Wirtinger derivatives has to be employed to show analyticity. Knowing the Cauchy-Riemann equations holds, I suppose we can then invoke the Looman–Menchoff theorem to assert that $g(z)$ is analytic around each singularity.


VIM with Syntastic: Why is VIM's JAVA syntax highlighting thrown off by `<` and `>` in a comment block?

Question: In VIM, when editing .java files, I'm seeing the syntax highlighter being thrown off by the < and > characters inside of comment blocks.
It seems to expect me to close the <characters with a >.
Here's an example:
/**
 *  `<` <-- this character causes a syntax error
 */

Using VIM with Syntastic.
Any idea what's going on?
Answer: Javadoc comments use html for formatting. < is the start of a tag and it never ends so it is invalid html. You need to use < instead.
Comment: or alternatively, use `/*` instead of `/**` if you're not writing JavaDoc


Determine which of two tkinter canvas items is above the other

Question: Is there a way to determine which item is topmost on the displaying order of a tkinter canvas given their respective id's?
Comment: I didn't check it but I think last one should be the topmost. I think it keep on list to draw from first to last - so last is topmost, and it may search the same list from first to last - so last is topmost.
Answer: You can use canvas.find_all() to get all the item IDs and according to the document: "The items are returned in stacking order, with the lowest item first".
Below is an example to find the topmost item in a check list:
check_ids = [1, 3, 5, 7]
all_ids = list(canvas.find_all())
# remove item IDs in all_ids that are not in check_ids
for x in all_ids[:]:
    if x not in check_ids:
        all_ids.remove(x)
# now all_ids contains only ID from check_ids sorted by stacking order
# so the last item ID is the topmost item in the list
topmost = all_ids[-1]
print(topmost)


Generating a particular element of $\mathrm{SL}_2(\Bbb{Z})$ from generators

Question: This should be easy, I hope.
$\mathrm{SL}_2(\mathbb Z) = \{ \begin{bmatrix} a & b \\ c & d \end{bmatrix} : a,b,c,d \in \mathbb Z, ad-bc=1\}$
A book I was reading said that the elements of $\mathrm{SL}_2(\mathbb Z)$ could be generated by:
$ \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix} $ and $ \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} $.
I have one element that I think should be in $\mathrm{SL}_2(\mathbb Z)$ that I can't quite figure out how to generate from these. That's this one:
$ \begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix} $
How do I form this matrix from the others?
Thanks.

Edit: In Diamond and Shurman's A First Course in Modular Forms $\mathrm{SL}_2(\mathbb Z)$ is called the modular group (on page 1). I am supposing that this is a group under matrix multiplication, since the additive matrix identity has determinant 0 and thus wouldn't be in the group.
Confirming with a second source that the matrices I've listed are generators for $\mathrm{SL}_2(\mathbb Z)$, here's some notes by Conrad that mention this fact immediately.
Answer: Well, let's look at what multiplying by each generator does.
We have that: $$Ae_1 = \begin{pmatrix} a & b \\ c & d \end{pmatrix}\begin{pmatrix} 1 & 1 \\ 0 & 1\end{pmatrix} = \begin{pmatrix}a & a+b \\ c & c+d\end{pmatrix}$$
We have that:
$$Ae_2 = \begin{pmatrix} a & b \\ c & d \end{pmatrix}\begin{pmatrix} 0 & -1 \\ 1 & 0 \end{pmatrix} = \begin{pmatrix}b & -a \\ d & -c\end{pmatrix}$$
These are the "moves" we have to work with.  Now, lets try to build your matrix.
It looks like we'll want to start with the first generator.  Just for fun, lets try applying $e_2$ first:
$$e_1e_2 = \begin{pmatrix}1 & -1 \\ 1 & 0\end{pmatrix}$$
Now, it's worth mentioning that $e_2^2 = -I$, where $I$ is the identity matrix.  As we weren't just trying to multiply by $-1$, it makes sense to try applying $e_1$ now:
$$e_1e_2e_1 = \begin{pmatrix} 1 & 0 \\ 1 & 1\end{pmatrix}$$
This is exactly what we wanted, so we're done.
Another way we could have worked with this is by computing $e_1^{-1}$ and $e_2^{-1}$, and tried "working backwards" from the matrix we want.
Comment: @ctesta01 note that Conrad's notes gives an algorithimic way to solve this.  That's how he proves those are the generators, given some generic matrix he shows how you can iteratively find the generators.
Comment: It was simple after all! Thanks a bunch!


How to type a function that transforms some properties of an input object

Question: Does anyone know how one would typ a transform function where only part of the keys are known/relevant and one of the known keys are optional? E.g.
const transform = <T extends BaseAkpiDto>(akpiDTO: T) => {
  const { startDate, periodData, ...akpiBase } = akpiDTO;
  const withMoments = {
    ...akpiBase,
    startDate: moment.utc(startDate),
  };

  if (!periodData) {
    return withMoments;
  }

  return {
    ...withMoments,
    lineData: akpiDtoToLineData(withMoments.startDate, periodData),
  };
};

interface BaseAkpiDto {
  startDate: string;
  endDate: string;
  periodData?: PeriodDto[];
}

const test: WithPeriodData = akpiDTOtoAkpiData({
  id: 1,
  name: 'my name',
  startDate: '2019',
  periodData: [] as PeriodDto[],
});

interface WithPeriodData {
  id: number;
  name: string;
  startDate: Moment;
  lineData: Period[];
}

I'm unable to get the return type to include a lineData property if (and only if) there is a lineData property on the input :(
Typescript complains to my testvariable with the following message:

Property 'lineData' is missing in type 'Pick<{ id: number; name:
  string; startDate: string; periodData: PeriodDto[];
  }, "id" | "name"> & { startDate: Moment; endDate: Moment; }' but
  required in type 'WithPeriodData'.
Comment: Can you remove all those unknown/moment types and add the invocation with the `test` variable, where that error happens?
Answer: Function transform has conditional behavior. Looking on the control flow it can return or object which contains lineData or not. Therefor you cannot assign the return which is a union IHaveLineData | IDoNotHaveLineData to IHaveLineData as the return is just wider type. Imagine you want to assign smth which is string | number to number, because of the same reason you can't.
To be sure you get the wanted structure you need to append additional control flow to ensure the type. So just:
// at this level test is infered as with or without lineData
const test= akpiDTOtoAkpiData({
  id: 1,
  name: 'my name',
  startDate: '2019',
  periodData: [] as PeriodDto[],
});

if ('lineData' in test) {
  // here test is precisely the type with lineData
}

Comment: I was hoping it could be solved with generics and conditional types that were added in 2.8, but it's probably not possible, like you say  :(


Continuous map from a connected open subset of the plane onto another one

Question: Let $\Omega_1, \Omega_2$ be two non empty open connected subsets of the plane. Is it always possible to find a continuous map $f$ from $\Omega_1$ onto $\Omega_2$?
Note: The origin of my question is this one: continuous-mapping-from-open-set-to-open-set.
Comment: Someone needs to answer this so I can go to sleep.
Comment: Gosh, good question. If they are simply connected, the answer is yes, because of [this](http://en.wikipedia.org/wiki/Riemann_mapping_theorem)..
Comment: @DavidMitra Oh I took the OP to mean open sets as in the title.
Comment: @Tim. Same for me Tim. I'm based in France... It's almost noon so I still have some time in front of me! What about you?
Comment: @David Mitra Subsets are supposed to be open. Do you in fact mean bounded?
Comment: Oh, I just looked at the post body.
Comment: I should be more precise. I modified the post body.
Comment: Might be overkill, but doesn't {the existence of space filling curves} + {the fact that every open set is a countable union of closed squares} give it to you?
Answer: As I said, this is probably overkill, but if we use space-filling curves, we can take for granted that there exists a continuous surjection $[0,1]\rightarrow [0,1] \times [0,1]$.
Now if $V \subset \mathbb{R}^2$ is open, connected, there exists a continuous surjection $V\rightarrow (0,1)$ (for instance, just project to the x-axis to get a disjoint union of open intervals, then choose one such interval $J$, take the identity on $J$ and send all the others into $J$)
Let $U\subset \mathbb{R}^n$ be open, connected, and write $$U:=\cup_{i=1}^\infty C_i$$ where $C_i$ are a countable collection of closed squares (of varying sizes).
We can define a surjective map $f_1:[1/2, 1)\rightarrow C_1$ and a path $\gamma :[1/3,1/2]\rightarrow  U$ with $\gamma(1/2)= f(1/2), \gamma (1/3)\in C_2$. Now define a surjective map $f_2: [1/4,1/3] \rightarrow C_2$. concatenating these maps gives a surjective map $[1/4,1)\rightarrow C_1\cup C_2$. Continuing in this way gives a surjection $(0,1) \rightarrow V$.
....right?
Actually it seems silly to use space filling curves because we collapsed space just to fill it again. You could replace $(0,1)$ with an open strip, which you think of as a divided into squares, mapping the first square to $C_1$, the next square to $\gamma$, the next square to $C_2$...
Comment: It seems to be OK.
Comment: I like the idea. One thing is not clear however. How do you ensure that your map from $(0,1)$ to $U$ is continuous? It is for sure continuous on each interval $(\frac{1}{n+1},\frac{1}{n})$. What about the continuity at points $\frac{1}{n}$?
Comment: So we have maps $[1/4,1/3]\rightarrow U, [1/3,1/2]\rightarrow U, [1/2,1]\rightarrow U$ which are all continuous and agree at 1/3 and 1/2. Then we can paste them together to get a continuous map.  I think this is called the "pasting lemma." Does that clarify?
Comment: It does. Great answer and idea. Thanks.


Theory behind testing whether $\mu \in \mathbb{Q}$ for $X \sim \mathcal{N}(\mu, \sigma^2)$

Question: Suppose that $X_i \stackrel{\mbox{i.i.d.}}{\sim} \mathcal{N} (\mu, \sigma^2)$, where $\sigma^2$ is known. Using this data, we wish to test whether $\mu \in \mathbb{Q}$, that is, whether the mean $\mu$ is a rational number.
It seems intuitively clear that we cannot do this, since any noise will be too much noise. I imagine that any test will have type II error rate $\beta = 0$ and type I error rate $\alpha = 1$ or vice versa. But, I don't understand how to make theoretical statements about this hypotheis testing problem. How does this problem fit into a more general framework that illustrates when testing is "difficult"?
Answer: Your intuition is correct: When you have a null set for the mean that is dense with respect to the total space, you won't be able differentiate the null and alternative sets with continuous data.  This is because, for any mean value in the alternative hypothesis, we can always get one that is "arbitrarily close" in the null set.  Hence, there should never be any evidence for the alternative hypothesis.
To get a formal demonstration of this result, you need to go through the motions of constructing this as a composite hypothesis test.  This is a bit tricky, since you have to make an argument for some test statistic, and there are some plausible objections here.

Formal construction of classical hypothesis test: For this test the hypotheses are:
$$\begin{equation} \begin{aligned}
H_0 &: \mu \in \mathbb{Q}, \\[4pt]
H_A &: \mu \notin \mathbb{Q}.
\end{aligned} \end{equation}$$
The first problem you run into is constructing a test statistic.  The likelihood ratio (LR) statistic for this problem is always equal to one, since the rationals are dense in the reals.  We have:
$$\sup_{\mu \in \mathbb{Q}} \sup_{\sigma >0} \prod_{i=1}^n \text{N}(x_i | \mu, \sigma^2) = \Big( \frac{n}{2 \pi \sum x_i^2} \Big)^{n/2} \exp \Big( - \frac{n}{2} \Big) = \sup_{\mu \notin \mathbb{Q}} \sup_{\sigma >0} \prod_{i=1}^n \text{N}(x_i | \mu, \sigma^2),$$
so that the ratio of these supremums is unity.  This means that the standard LR statistic fails to serve as a measure of evidence for the hypotheses, and so we need a custom test statistic.
Now, for these hypotheses, the ordinal ranking of evidence falls into only two categories: if the sample mean is rational (which occurs with probability zero), this is greater evidence for the null hypothesis; if the sample mean is irrational (which occurs with probability one), this is greater evidence for the alternative hypothesis.  Hence, the appropriate test statistic for the test is $T \equiv T(X_1, ..., X_n) \equiv \mathbb{I}(\bar{X} \notin \mathbb{Q})$, with higher values of this (indicator) test statistic constituting greater evidence for the alternative.
Since $\bar{X} \sim \text{N}(\mu, \sigma^2 /n)$ is continuous, we have $\mathbb{P}(T = 0 | \mu, \sigma) = \mathbb{P}(\bar{X} \in \mathbb{Q} | \mu, \sigma) = 0$ over all the parameter values (this follows from the fact that the rationals have Lebesgue measure zero).  This means that the test statistic has the same distribution regardless of the parameter values.
If we observe $\bar{x} \notin \mathbb{Q}$ (i.e., the sample mean is irrational) then the p-value for the test is:
$$p \equiv \mathbb{P}(T(\bar{X}) \geqslant t(\bar{x}) | H_0) = \mathbb{P}(T \geqslant 1 | \mu \in \mathbb{Q}) = 1.$$
If we observe $\bar{x} \in \mathbb{Q}$ (i.e., the sample mean is rational) then the p-value for the test is:
$$\begin{equation} \begin{aligned}
p \equiv \mathbb{P}(T(\bar{X}) \geqslant t(\bar{x}) | H_0) &= \mathbb{P}(T \geqslant 0 | \mu \in \mathbb{Q}) = 1.
\end{aligned} \end{equation}$$
So we see that even with a custom test statistic that tries to differentiate the hypotheses, we never get any evidence against the null.  This is intuitively reasonable, since for any mean value in the alternative hypothesis, we can always get one that is "arbitrarily close" in the null set.
Comment: Of course everything here is correct (+1)--but I would like to suggest the focus on the topology of the rationals and reals, and their Lebesgue measure, somewhat misses a more fundamental point (which you make but perhaps don't emphasize as much as you might). If, *e.g.*, the model were the set of Normal distributions with parameters $(\mu, \sigma^2(\mu))$ where $\sigma(\mu)=1$ for $\mu\in\mathbb{Q}$ and $\sigma(\mu)=2$ otherwise, you *could* test $H_0:\mu\in\mathbb{Q}.$ The more fundamental meaning of "dense" is in the topology on the model determined by log likelihood ratios.
Comment: Good point - my own discussion was just confined to the particular case at issue, but it would certainly be interesting to extend this to a broader discussion to those wider cases.


Big-O complexity of iterating over every substring

Question: What is the Big-O complexity of iterating over every possible non-empty substring of a string of length $N$?
The simple way to do the iteration over string $S$ is:
<code>for i in 1 .. N:
    for j in (i+1) .. N:
        S[i .. j]
</code>
Clearly this is more complex than $\mathcal{O}\left(N\right)$ but less complex than $\mathcal{O}\left(N^2\right)$, but I'm not sure how to understand the complexity of these nested loops.
Comment: Your inside loop do N-i iterations, so the total number of iterations is given by $$\sum_{i=0}^N N-i = \sum_{i=0}^N i = \frac{N(N+1)}{2}$$ This is a classical formula, and there exist similar formula (but more complex) for $\sum_{i=0}^{N} i^n$. Actually $\sum_{i=0}^{N} i^n$ is a n-th degree polynomial
Comment: You have $\frac{N(N+1)}{2}$ iterations
Comment: @Tryss: Thanks, would you be able to explain this a little? In fact, I actually need to add a third nested loop, which iterates j/2 times, so I'm not sure how to extrapolate from your answer to a more general solution.
Answer: $$
S = (1+ 1+ \ldots 1) + //\text {n times}\\
  (1+1+ \ldots 1) +  //\text{n-1 times} \\
  \ldots 1
$$
Hence $S = 1 + 2 + \ldots (n-1) +n = \frac{n(n+1)}{2}$


Pouring fractions of water from a vase to another (recurrence sequence)

Question: Let me state the problem in terms of vases and water, I think it's clearer. We have three vases $A$, $B$ and $C$, with $A$ containing a certain amount of water, so let's say $A=1$ and $B=C=0$ empty. The vase $A$ is connected to the vase $B$ and $B$ is connected to $C$. What I want to do is to pour water from $A$ to $C$, but I can do that in steps and at each step I can pour at most a fraction $\varepsilon$ of the water in a vase inside the next, and no more. So, after the first steps I'll have (I will call $A_n$, $B_n$ and $C_n$ the quantity of water at step $n$):
$$ A_1 = 1- \varepsilon \quad B_1 = \varepsilon \quad C_1 = 0$$
$$ A_2 = 1- 2 \varepsilon + \varepsilon ^2 \quad B_2 = 2\varepsilon - 2\varepsilon ^2 \quad C_2 = \varepsilon ^2$$
$$ A_3 = 1- 3 \varepsilon + 3 \varepsilon ^2 -\varepsilon ^3 \quad  B_3 = 3\varepsilon - 6 \varepsilon ^2 + 3\varepsilon ^3 \quad C_3 = 3 \varepsilon ^2 - 2 \varepsilon ^3$$
and it soon gets very complicated. Now, for two vases this is easy and after $N$ steps you are left in the first vase with $(1- \varepsilon) ^N$ water, and so there is $1 - (1- \varepsilon )^N \approx N \varepsilon$ in the second vase. In this case however, is there a formula or at least some known behavior?
P.S. I would actually be interested in the general case with $n$ vases, so to estimate how much water I can transport from the first vase to the last in a certain number of steps.
Comment: Can you clarify that between the results of steps 1 and 2, do you first pour out of $B$ then out of $A$? Or first out of $A$ then out of $B$?
Comment: You do it at tthe same time. I mean that when pouring from B to C, you don't have access to the water being poured in B from A
Comment: You will find with more than two vases $B_n=2(1-\varepsilon)B_{n-1}+(1-\varepsilon)^2B_{n-2}$ which is a solvable recurrence starting at $B_0=0,B_1= \varepsilon$
Answer: Suppose there are $M$ total vases connected to each other. The quantity of water in the vases $Q^{(1)},..., Q^{(M)}$ at time step $n$ obeys the recurrence relations
$$Q^{(1)}_n=(1-\epsilon)Q_{n-1}^{(1)}$$
$$Q^{(k)}_n=(1-\epsilon)Q_{n-1}^{(k)}+\epsilon Q_{n-1}^{(k-1)}~~,~~ 2\leq k\leq M-1$$
$$Q^{(M)}_n=Q_{n-1}^{(M)}+\epsilon Q^{(M-1)}_{n-1}$$
This is a linear system of equations and it can in principle be solved using matrix techniques; however the matrix does not have a complete eigenvector space and so its Jordan decomposition would be required to obtain results. Fortunately, this is not immediately necessary, as a solution can be constructed by solving for the quantity of water in the first vase and sequentially substituting in the other equations. We can ignore the last equation, since $Q^{(M)}_n=1-Q^{(1)}_n-...Q^{(M-1)}_n$.
Without delving too much into details, it can be shown that for $1\leq k\leq M-1$ the solution can be written as
$$Q_n^{(k)}=(1-\epsilon)^{n-k+1}\gamma_n^{(k)}$$
$$\gamma_n^{(k)}=\gamma_{n-1}^{(k)}+\epsilon\gamma_{n-1}^{(k-1)}$$
The latter set of recursive equations can be inductively shown to have an explicit solution:
$$\gamma_n^{(k)}=\epsilon^k{n\choose k}$$
Incidentally, the quantity of water in any of the first $M-1$ vases is the coefficient of the binomial expansion $[x^k](1-\epsilon)[(x\epsilon+(1-\epsilon))^n-1]$. Remarkably, the solution does not change its form as one increases the number of the vases considered: at any fixed time step the quantities $Q^{(1)}_n,..., Q^{(M-1)}_n$  are drawn from the coefficients of the binomial distribution and are padded by zeroes for $M-1>n$, as expected from the physics of the problem (the $k+1$-th vase stays empty until the $k$-th timestep).