picture viewer in c# .net

Question: Regarding .Net technology,What will be the basic element of a picture viewer(like Windows Picture and Fax Viewer)? Is it a user control inside a form, or is it something other components. Could you please give me an idea in the context of C#.Net
Comment: you can use `Picture` control simply to display images.
Comment: @Ummar: I would like to do 1. Zooming 2. Magnifier etc . Does Picture control support all these functionalities
Answer: You don't really get one that's bundled into .NET Framework (and that's probably a good thing, it's fairly large already).
If using WinForms, the nearest thing you do get is the PictureBox component, and the BackgroundImage property of some other components like Form and Panel. But you have to implement the rest of the functionality of an image viewer yourself.
WPF certainly has its own equivalents but I can't name them off the top of my head.
Answer: for making picture viewer is better to have PictureBox to show Pictures, ImageList   to hold list of images due to have more that one picture and also two buttons for next   pictur and previews picture.
a simple code which I suggest is as follow:
private void btnLoadImage_Click(object sender, EventArgs e)
    {
        imageList1.Images.Clear();
        if (openFDialogImage.ShowDialog() == DialogResult.OK)
        {
            for (int i = 0; i < openFDialogImage.FileNames.Length; i++)
            {

imageList1.Images.Add(Image.FromFile(openFDialogImage.FileNames[i]));
            }
            pictureBox1.Image = imageList1.Images[currentIndex];
        }
    }

    private void BtnForward_Click(object sender, EventArgs e)
    {
        if(currentIndex!=imageList1.Images.Count-1 && imageList1.Images.Count > 0)
        {
            pictureBox1.Image = imageList1.Images[currentIndex++];
        }

    }

    private void btnBack_Click(object sender, EventArgs e)
    {
        if (currentIndex!=0)
        {
            pictureBox1.Image = imageList1.Images[--currentIndex];
        }
    }

Thats all, :)

picture viewer in c# .net


Find the solutions of the equation $z^2+2z+1-i=0$ in the form$ z=p+iq$

Question: I had tried this so far :
let $z = x + iy$
Hence, $$(x + iy)^2 + 2 (x + iy) + 1 - i = 0$$
$$x^2 + 2xyi + - y^2 + 2x + 2iy + 1 - i = 0$$
$$x^2 - y^2 + 2x + 1 + 2xyi + 2iy - i = 0$$
Comment: I think this will be easier if we treat $z$ in its entirety as a complex variable. For example, the given equation is the same as $(z+1)^2 = i$ ... what are the square roots of $i$ in the complex numbers?
Answer: Gotta get used to the fact that complex numbers are actually numbers in their own right.
$z^2 +2z + 1-i=0$ will have solutions by the quadratic formula of
$z = \frac {-2 \pm \sqrt {4 - 4(1-i)}}2$
So factoring out the common factor $2$ we get $z = -1\pm i^{\frac 12}=$
$-1 \pm (\frac 1{\sqrt 2} + \frac 1{\sqrt 2}i) =$
$(-1\pm \frac 1{\sqrt 2}) + i(\pm \frac 1{\sqrt 2})$.
....
Although you could continue.
You must solve $x^2 - y^2 + 2x + 1=0$ and $2xy + 2y-1 = 0$.
So $y = x^2 +2x + 1$ so $y = (x+1)^2$ and $y = \pm(x+1)$.
But we also have $2xy + 2y - 1 = 0$ so $y(2x+2) = 1$ and $y = \frac 1{2(x+1)}$.
So we must solve $\pm (x+1) = \frac 1{2(x+1)}$ or
$\pm (x+1)^2 = \frac 12$ so $(x+1)^2 = \frac 12$ (and $y > 0$) and $x+1 =\pm \frac 1{\sqrt 2}$ and ... the rest falls out.
$x = -1 \pm \frac 1{\sqrt 2}$ and $y = \pm \frac 1{\sqrt 2}$.
(I actually wasn't expecting it to fall out so neatly.)
Answer: It's way easier to keep the complex variable whole
$$z^2+2z+1=(z+1)^2=i
\implies z = -1\pm\sqrt{i} = -1\pm\frac{1}{\sqrt{2}}\pm i\frac{1}{\sqrt{2}}$$
Comment: You shouldn't use the notation $\sqrt i$.   It is not defined as a function on $\mathbf C$.
Comment: @lonestudent: yes. I prefer to speak of the square roots of $i$ explicitly, it's less dangerous for beginners.
Comment: Personally, I write in plain language: '$i$ is a square root of $-1$' (the other being $-i$). If one uses the notation $\sqrt z$, you're not sure that $\sqrt{zz'}=\sqrt z\,\sqrt{z'}$ in all cases.
Comment: @Bernard what in the world are you talking about? All principal roots by default use the principal branch of log. This is well defined, perhaps what you mean is that it is not analytic on all of  $\Bbb{C}$. If I could downvote a comment for being unhelpful I would.
Comment: @Bernard you mean $\sqrt i$ is wrong notation. Do I understand right?
Comment: @Bernard it's because of attitudes like that students are afraid of ambiguities of complex powers in the first place. The notation here is not incorrect or unrigorous. I am of the camp to use notations such as $\sqrt{}$ or rational powers interchangeably because they don't mean anything different by themselves and anyone who believes they do is naive. Distinctions may be made by different authors for the purposes of illustrating different conventions, but I have seen authors call both the $\sqrt{}$ and power notation the principal and multiimage function because there is no consistency.
Comment: @Bernard It is possible to see this notation in YouTube math channels, Google images and web searches.  But I never knew it was wrong.. Thanks.
Comment: @lonestudent the take away is not that the notation is wrong, that is an incorrect conclusion. The point that Bernard was (hopefully) trying to make is that there is a principal and multibranched version of complex roots and we should know when we are using which. But it is a common misconception that this phenomenon is unique to complex numbers. We write $\sqrt{x}$ to mean the positive root only in the real case, and this is not any different from what we do in the complex case. However Bernard's initial comment about $\sqrt{z}$ not being a defined function on $\Bbb{C}$ is mostly wrong
Comment: @NinadMunshi Using radicals for the principal value is not wrong per se as long as the definition has been made clear. But it is not universal, and can be confusing especially for those unaccustomed to that convention. Just look at how many questions have been posted (usually about math softwares) $\text{"}\,$why is $\sqrt[3]{-1}$" not $-1\,?\,\text{"}$.
Comment: @dxiv if we use $\sqrt{x}$ to take the positive branch in the real case, then we can take $\sqrt{z}$ to mean the principal branch, always. Case closed. Convince me that these situations are different and I'll agree that ambiguity is warranted.
Comment: @Bernard  (sorry for English grammar) There is a sentence like this in my school book." To write $i=\sqrt {-1}$ is wrong. Because, $\sqrt {•}$ must use for only positive reals. So, we can write only $i^2=-1$". I want to post this question in MSE as a question for a long time, but I didn't do it because it might be not a good question. Would you like to say something? Thank you..
Comment: @NinadMunshi "*then we* ***can*** *take √z to mean the principal*". Right, but with emphasis on "*can*". It is not universal, and it helps for that convention to be spelled out when used. Ask random people what $\Re(\sqrt{4}+i\sqrt[3]{-8})$ is without providing additional context, and you'll probably receive different answers.
Comment: @lonestudent The radical symbol isn't useful in the complex world because there is no universally-good way to define principal root in the complex world, i.e., it is potentially ambiguous unless prefaced.
$$$$
E.g., does $\sqrt[3]{-1}$ equal $e^{i\frac\pi3}$ (choose the root with the smallest nonnegative argument) or $-1$ (choose the positive root if it exists; else the negative root; else the root with the smallest positive argument)?....
Comment: @dxiv ....A kookier example: $1$ has infinitely many positive $i^\text{th}$ roots: $e^{2k\pi}=\{\ldots,e^{-4\pi}, e^{-2\pi}, 1, e^{2\pi}, \dots\};$ here, both the above criteria fail to settle on a "principal root". $$$$ So, I studiously treat the radical symbol as having a nonnegative domain, and,  **in the complex world**, treat expressions like $1^\frac12$ and $i^\frac12$ as multi-valued (but this convention also isn't universal: many feel that, even in the complex world, $1^\frac12=1\neq\{-1,1\}$).
Answer: Along the line of what you were trying, it may be a bit easier (for this problem) to bring the "numerical" terms to one side of the equation, producing
$$ z^2 \ + \ 2z \ \ = \ \ (p^2 + 2p - q^2) \ + \ (2pq + 2q)·i \ \ =  \ \ -1 \ + \ i \ \ . $$
We can then set up the correspondence equations
$$ p^2  +  2p  - q^2 \ \ = \ \ -1 \ \ \ , \ \ \ 2·q·(p + 1) \ \ = \ \ 1 \ \ . $$
From the first of these, we obtain $ \ p^2  +  2p  + 1 \  =  \ ( p + 1 )^2 \
= \ q^2 \ \ . $  Squaring the second equation yields $ \ 4·q^2·(p + 1)^2 \ = \ 1 \ \ . $  Consequently, $$ \ 4·q^2·q^2 \ = \ 1 \ \Rightarrow \ \ q \ = \ \left(\frac14 \right)^{1/4} \ = \ \pm \frac{1}{\sqrt2} \ = \ \pm ( p + 1 ) \ \ . $$
It is evident, since the polynomial is quadratic, that two of the four possible combinations must be "spurious."  Our second correspondence equation requires that $ \ (p + 1) \ $ and $ \ q \ $ must have the same sign, so the two zeroes of the polynomial are $ \ z \ = \ \left(-1 \pm \frac{1}{\sqrt2} \right) \ \pm \ \left(\frac{1}{\sqrt2} \right)·i \ \ . $


How do I get my api-data to show up on my details list?

Question: I can list all my products in my API through a view page by making a ProductsController like this:
    public async Task<ActionResult> Index()
    {
        var http = new HttpClient();
        var products = await http.GetFromJsonAsync<List<Product>>("I won't write out my link so everyone can see it :P");

        return View(products);

after that I made a view page for the products like this.
@foreach (var item in Model)
{

@Html.DisplayFor(modelItem => item.SubCatergoryId)

                 item.ImageUrl)" class="card-img-top" alt="">

@Html.DisplayFor(modelItem => item.Name)

@Html.DisplayFor(modelItem => item.Description)

@Html.DisplayFor(modelItem => item.Price):-

                    Details

                   Lagerstatus

}

it worked perfect. But now I want to press the details button which takes me to another view (details page). This is the code for the details page:

                     model.ImageUrl)" class="card-img-top" alt="75\">

@Html.DisplayNameFor(model => model.Name)

@Html.DisplayNameFor(model => model.Description)

@Html.DisplayNameFor(model => model.Price):-

                        <button class="btn btn-outline-secondary">
                            Beställ

                        </button>

                       Lagerstatus

This is what I get: Details Page
this is my first time working with Asp.net and making my own API.
Answer: The @Html.DisplayNameFor shows the name of the property or the string defined in the display attribute for the property.
The @Html.DisplayFor shows the value of the field.
Change your code to:

                     model.ImageUrl)" class="card-img-top" alt="75\">

@Html.DisplayFor(model => model.Name)

@Html.DisplayFor(model => model.Description)

@Html.DisplayFor(model => model.Price):-

                        <button class="btn btn-outline-secondary">
                            Beställ

                        </button>

                       Lagerstatus

Note:
Be sure the value of model.ImageUrl should equal to /location/filename.extension. Be sure add single slash at the beginning and specific the file name.


Como Criar uma array a partir de trechos de texto de uma string?

Question: Alguém poderia me ajudar, com algum método, função ou o que for disponível, pra fazer com que uma string se torne uma array feita de pedaços da mesma string exemplo:
var string = "stackoverflow";
var array = [];
console.log(array) // ['stack'], ['over'], ['flow']

e/ou
var string = "gameoveragain";
var array = [];
console.log(array) // ['game'], ['over'], ['again']'

bem é isso que eu quero como nos exemplos, algo onde eu posso reutilizar, e que sempre encontra o trecho 'over' na string e a partir disso a string se torne uma array separada, no caso, ela pode ser uma array com 3 itens 2, 1 ou vários, se no caso sempre for encontrado especificamente 'over' dentro da string.
Answer: const split = function (string) {
    string = string.split(/(over)/);
    return string;
};

O método .split() vai separar uma string em substrings e retornar um array. O parâmetro que eu passo entre parêntesis é o parâmetro de separação da string, ou seja, o método irá dividir a string quande ele for encontrado.
No caso eu passei de parâmetro uma regex para poder capturar o grupo e adicioná-lo ao array de retorno.
Para aprender mais sobre regex, recomendo:
http://aprenda.vidageek.net/aprenda/regex
Para quem entende inglês melhor aula de regex do YouTube:
https://www.youtube.com/playlist?list=PLRqwX-V7Uu6YEypLuls7iidwHMdCM6o2w
Comment: Boa `+1`! Podes explicar como é que o split funciona neste caso com eregx? Assim a resposta fica mais completa.
Comment: Muito obrigado pela resposta e recomendações de links de estudos, realmente estou precisando aprender muito isso, o algorítimo é muito simples, eu só não entendi bem como que o split funciona com o regex, antes de fazer a pergunta aqui, eu já tentei fazer algo usando o split, mas não obtive sucesso, mas vou estudar seus links pra entender, muito obrigado!
Answer: Segue uma alternativa mais reaproveitável.

var _split= function (text, term) {
  var index = 0;
  var terms = [];
  text.replace(new RegExp(term, "gi"), function (term, i) {
    terms.push(text.substring(index, i));
    terms.push(term);
    index = i + term.length;
  });
  terms.push(text.substring(index));
  return terms;
}

var terms = _split("stackoverflowovergame", "over");
console.log(terms);
Comment: muito obrigado pela resposta!


get assets path in File to read multiple files

Question: I have multiple .epub file in assets, I want that all .epub file in listFile. In my old code i use external storage file path, for getting .epub files, like this
File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Files" );

File listFile[] = myFile.listFiles();
if (listFile != null && listFile.length > 0) {
    for (int i = 0; i < listFile.length; i++) {

        if (listFile[i].getName().endsWith(".epub")) {

            myNewBookModels = new NewBookModels();
            Log.i(TAG, "getEpubFilesFromFileManager: " + ".." + listFile[i].getName());

            myNewBookModels.setBookName(listFile[i].getName().toString());
            myNewBookModels.setBookPath(listFile[i].getPath().toString());
            myNewBookModels.setBitmap(bookLoaded(listFile[i].getName().toString()));
            arrayList.add(myNewBookModels);
        }
    }
}

but i want that .epub files from assets folder. How can i do this?
I also want this field from that .epub file
1) Name
2) Path
3) Bitmap (cover page Image)
It is compulsory for me. This can only possible in File but i want assets .epub file in File
Answer: You can access Asset folder using this path - "file:///android_asset/files"
OR
//Directory or File name
dirForm = "files";
private void listFiles(String dirFrom) {
        Resources res = getResources(); //if you are in an activity
        AssetManager am = res.getAssets();
        String fileList[] = am.list(dirFrom);

            if (fileList != null)
            {
                for ( int i = 0;i<fileList.length;i++)
                {
                     File file = new File(fileList[i]);
                     if ((file.getName()).endsWith(".epub")) {

                      Log.i(TAG, "getEpubFilesFromFileManager: " + ".." + file.getName() +"Path"+ file.getPath());
                     }
                }
            }
    }

Comment: In this `fileList[i].getName()` i did't get `getName()`, because fileList[] is string array
Comment: Do directly fileList[i].endsWith(".epub") and skip .getName().
Because fileList array contains file name.
Comment: but i want that name
Comment: You mean to say, you want file Name & file path?
Comment: Try updated Code now. You have to make File object from file name. Hope it works for you.
Comment: its working, but i want list of `File` first then Name, Path and Bitmap, because when i use your code every time Bitmap image is same for all
Answer: If your files are in asset folder then it will always be a fixed path. so you can give a hard coded path in string.
Comment: can you please explain in details.
Comment: I meant that when your files were in external storage then they may have variable path. In that case you need to get the path at runtime. But now when your files are in android's asset folder then it will always be fixed in all devices. So you don't need to get path at run time. You can just give a hard coded path. & a typical Android Studio project, you will have an app/ module, with a main/ sourceset (app/src/main/ off of the project root), and so your primary assets would go in app/src/main/assets/. and for names: String[] listOfFileName = getContext().getAssets().list("your/path");
Comment: String[] listOfFileName = getContext().getAssets().list("your/path/inside/asset");
Comment: What else you need? path and name is there and bitmap: you are already getting from name
Answer: You can Use AssetManager class & then you can Read files from Assets Folder.


How to solve this error? RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)

Question: This is WongKinYiu / PyTorch_YOLOv4 problem. I found many solutions of this problem in YOLOv7, and no solution in YOLOv4. Since, the community here is more active. Thus, I try to ask here also.
This is the link to WongKinYiu loss.py
Traceback (most recent call last):
File "/content/PyTorch_YOLOv4/train.py", line 537, in
train(hyp, opt, device, tb_writer, wandb)
File "/content/PyTorch_YOLOv4/train.py", line 288, in train
loss, loss_items = compute_loss(pred, targets.to(device), model) # loss scaled by batch_size
File "/content/PyTorch_YOLOv4/utils/loss.py", line 69, in compute_loss
tcls, tbox, indices, anchors = build_targets(p, targets, model) # targets
File "/content/PyTorch_YOLOv4/utils/loss.py", line 151, in build_targets
a, t = at[j], t.repeat(na, 1, 1)[j] # filter
RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)

Comment: What I can see in this error message is that when you call `compute_loss()` function you explicitly send targets to device (whatever the device is) but when you call `build_targets()` you don't do the same. So this is how they may end up on different devices.
Answer: The Github issue has a solution from MheadHero:

I have found a solution.
Modify your loss.py
add at = at.to(targets.device) above a, t = at[j], t.repeat(na, 1, 1)[j]  # filter
Then,
uncomment indices.append((b, a, gj, gi))  # image, anchor, grid indices and
comment indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1)))  # image, anchor, grid indices


Why does the inner rectangle overflow the outer rectangle in Vega spec

Question: This is the Vega spec, it is intended to contain two equally-sized groups in one row:
{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "autosize": "none",
  "config": {"group": {"stroke": "black"}},
  "signals": [
    {
      "name": "target_height",
      "value": 200},
    {
      "name": "target_width",
      "update": "5/4 * target_height"},
    {
      "name": "level_0_padding",
      "update": "1/16 * target_height"},
    {
      "name": "level_1_padding",
      "update": "1/2 * level_0_padding"},
    {
      "name": "level_0_height",
      "update": "target_height - 2*level_0_padding"},
    {
      "name": "level_0_width",
      "update": "target_width - 2*level_0_padding"},
    {
      "name": "level_1_width",
      "update": "1/2 * (level_0_width - level_0_padding)"},
    {
      "name": "level_1_height",
      "update": "level_0_height"}],
  "width": {"signal": "level_0_width"},
  "height": {"signal": "level_0_height"},
  "padding": {"signal": "level_0_padding"},
  "layout": {
    "padding": {"signal": "level_0_padding"},
    "align": "all",
    "center": true},
  "marks": [
    {
      "type": "group",
      "encode": {"update": {
        "width": {"signal": "level_1_width"},
        "height": {"signal": "level_1_height"},
        "padding": {"value": 0},
        "stroke": {"value": "red"},
        "strokeOpacity": {"value": 0.5}}}},
    {
      "type": "group",
      "encode": {"update": {
        "width": {"signal": "level_1_width"},
        "height": {"signal": "level_1_height"},
        "padding": {"value": 0},
        "stroke": {"value": "red"},
        "strokeOpacity": {"value": 0.5}}}}]}

For some reason, however, the second group seems to overflow the global plot space:

It seems that the overflow is always about a few pixels wide, independently of the values of target_width, target_height or level_0_padding.
Open the Chart in the Vega Editor
Note that the issue remains if the signal update expressions are rewritten like in the following example, to exclude user floating-point error as the cause of the issue:
  "signals": [
    {
      "name": "target_height",
      "value": 200},
    {
      "name": "target_width",
      "update": "5/4 * target_height"},
    {
      "name": "level_0_padding",
      "update": "1/16 * target_height"},
    {
      "name": "level_1_padding",
      "update": "1/32 * target_height"},
    {
      "name": "level_0_height",
      "update": "7/8 * target_height"},
    {
      "name": "level_0_width",
      "update": "9/8 * target_height"},
    {
      "name": "level_1_width",
      "update": "17/32 * target_height"},
    {
      "name": "level_1_height",
      "update": "level_0_height"}],

In fact, the overflow happens even if all of the signals have integer values.
The same issue, but with a column instead of a row

Open the Chart in the Vega Editor
With a more complex layout
Trying to do the same thing, but with a slightly more complicated layout results in accumulated overflows and, even worse, the two red boxes/groups are misaligned:

Open the Chart in the Vega Editor
After playing around with this example, I conclude that the misalignment is actually a separate issue, as it can be fixed by specifying "align": "none" instead of "align": "each" or "align": "all"
Answer: You need "bounds": "flush".

{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "autosize": "none",
  "config": {"group": {"stroke": "black"}},
  "signals": [

    {"name": "level_0_padding", "value": 16},
    {"name": "level_1_padding", "update": "1/2 * level_0_padding"},
    {"name": "level_0_height", "update": "168"},
    {"name": "level_0_width", "update": "168"},
    {
      "name": "level_1_width",
      "update": "1/2 * (level_0_width - level_0_padding)"
    },
    {"name": "level_1_height", "update": "level_0_height"}
  ],
  "width": {"signal": "168"},
  "height": {"signal": "168"},
  "padding": {"signal": "30"},
  "layout": {"padding": {"signal": "level_0_padding"}, "bounds": "flush"},
  "marks": [
    {
      "type": "group",
      "encode": {
        "update": {
          "width": {"signal": "level_1_width"},
          "height": {"signal": "level_1_height"},
          "padding": {"value": 0},
          "stroke": {"value": "red"},
          "strokeOpacity": {"value": 0.5}
        }
      }
    },
    {
      "type": "group",
      "encode": {
        "update": {
          "width": {"signal": "level_1_width"},
          "height": {"signal": "level_1_height"},
          "padding": {"value": 0},
          "stroke": {"value": "red"},
          "strokeOpacity": {"value": 0.5}
        }
      }
    }
  ]
}


Why can't I make cross origin requests to an API hosted in IIS?

Question: I have an ASP.NET WebApi application running locally using IISExpress that allows me to accept requests from any domain. I am doing this using a DelegatingHandler similar to the one provided one this blob post.
Locally this runs perfectly however after uploading to an Azure Website, I get the typical 'Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.' under Chrome.
I've tried to debug this by adding trace statements into the Handler with no output and it seems like SendAsync is never being executed, almost as if IIS is responding to the OPTIONS request instead of passing it on to my application.
Has anyone come across anything similar going from development to production?
Answer: IIS (including the one in your Azure web site) has a default OPTIONS handler. You will need to remove it in Web.config. It answers the OPTIONS call before your message handler has an opportunity to respond.
<configuration>
  ...
  <system.webServer>
    <handlers>
      <remove name="OPTIONSVerbHandler" />
      ...
    </handlers>
  </system.webServer>
</configuration>

Comment: And it would appear that IISExpress does not.
Comment: Yes, that's why you did not face this issue until you deployed in IIS. Same behavior can be seen in local IIS server as well.
Comment: This doesn't seem to fix the problem on Azure Websites running PHP. IIS still responds before the request is actually passed to the PHP code.


What does it mean for the continuum function to be eventually constant below k?

Question: I am following a Thomas Jech's "Set Theory" and in Chapter 5 have come across the following:

We take the Continuum Function to be $2^k$, without assuming the GCH: Generalized Continuum Hypothesim
Corollary 5.17
If $k$ is a singular cardinal and if the continuum function is eventually constant bellow $k$, with value $\lambda $, then $2^k$.

I am having some trouble understanding exactly what Jech means when he says "if the continuum function is eventually constant"? I am sorry I cannot offer much more into the discussion, since I am simply stuck on the wording.
Answer: If $\kappa$ is an infinite cardinal, then
"The continuum function is eventually constant below $\kappa,$ with value $\lambda\!"$
means
"There exists $\gamma\lt\kappa$ such that for all $\delta,$ if $\gamma \lt \delta \lt \kappa,$ then $2^\delta=\lambda.\!"$
Answer: You've misread it: it says if the continuum function is eventually constant below $\kappa$, with value $\lambda$. This means that there is a $\mu$ such that $\operatorname{cf}\kappa\le\mu<\kappa$, and $2^\nu=2^\mu=\lambda$ for $\mu\le\nu<\kappa$. This can be abbreviated the way Jech does in the first sentence of the proof: there is a $\mu$ such that $\operatorname{cf}\kappa\le\mu<\kappa$ and $2^{<\kappa}=2^\mu=\lambda$.
Comment: Urg tired eyes on the check, sorry about that.
Comment: Ah ok, I assume that the only time where the continuum function is NOT constant would be for regular cardinals where there does not exist such a cardinal between $k$ and its cofinality $cf(k)$?
Also, meta type question here as I am new; since this question was very closed and unlikely to help anyone but myself, would you recommend deleting?
Comment: @Max: You could still have, for instance, $2^\kappa=2^{(\kappa^+)}=\kappa^{++}$, where $\kappa^+$ is certainly regular. Or the continuum function could be nowhere constant, as happens with $\mathsf{GCH}$. \\ No, there's no reason to delete; you never know when something might be useful to someone.


MySQL Selecting from One table into Another Based on ID

Question: I'm having a problem with MySQL
I have two tables, I want to store Val1 from Table 2 into Val2 in Table 1
Table1
ID-----Val1-----Val2
1------A--------NULL
2------B--------NULL
3------C--------NULL
4------D--------NULL
5------E--------NULL

Table2
ID-----Val1
1------aaa
2------bbb
3------ccc
4------ddd
5------eee

So that Table1 now looks like
Table1
ID-----Val1-----Val2
1------A--------aaa
2------B--------bbb
3------C--------ccc
4------D--------ddd
5------E--------eee

Right now, I have
INSERT INTO Table1(Val2) SELECT Val1 FROM Table2 WHERE Table1.ID=Table2.ID;

Any help is appreciated!
Answer: You can use either a subquery (SQLize):
UPDATE Table1
SET Val2 = ( SELECT Val1 FROM Table2 WHERE Table1.ID = Table2.ID )
WHERE Val2 IS NULL

or a multi-table update (SQLize):
UPDATE Table1, Table2
SET Table1.Val2 = Table2.Val1
WHERE Table1.ID = Table2.ID AND Table1.Val2 IS NULL

or the same with an explicit JOIN (SQLize):
UPDATE Table1 JOIN Table2 ON Table1.ID = Table2.ID
SET Table1.Val2 = Table2.Val1
WHERE Table1.Val2 IS NULL

(I assume you only want to update the rows in Table1 for which Val2 is NULL.  If you'd rather overwrite the values for all rows with matching IDs in Table2, just remove the WHERE Table1.Val2 IS NULL condition.)
Answer: update table1
inner join table2 on table1.id = table2.id
set table1.val2 = table2.val1


For a single rack is there a good reason to use an enterprise switch over a more simple option?

Question: We putting up a rack of 12 (maybe 24-30 later) servers (moving off AWS) and we have only a modest level of networking skill on our team (an out of date CCNA admin).
In looking at two possible switches, I wonder if there's a reason we'd go with the recommended FastIron enterprise level switch rather than the seemingly easier to configure DLink switch listed below.
D-Link DGS-1210-48 Web Smart 10/100/1000Mbps Gigabit Switch With 4 Combo SFP Slots
  vs.
FastIron GS 648P
The D-Link switch appears to have all of the necessary features to support our need (VLAN support, trunking, the basics), and it has a remote management web-based UI, where the FastIron, I believe, only has console access (we don't have a KVM as all the servers & firewall also have an IP based management console).
Any reason to fear going with the D-Link option in this case?
Answer: It really depends on your network requirements and load.  For example, for my most recent project I selected expensive, high-end switches because our SAN requires jumbo frames, flow-control, and large packet buffers.  Most low-end switches can't provide all of those features or not all at once.
Many low-end switches do not have adequate backplane speeds, so you cannot make full use of each port in both directions at once.
Many low-end switches are not manufactured as robustly (cheap fans, cheap power supplies, etc.) so they are, in general, more likely to fail.
So... Do you need to be able to read/write at Gb speeds on a majority of the ports at once?  Do you have specialized network requirements?  Is reliability extremely important?  If so, then you want the FastIron.  If not, the D-Link will probably be fine for a while.
Comment: Great point on the backplain, we're running a hadoop cluster, so transfering gigabits at a time between boxes is a major desire. But the specs say that it's got a 96GBit backplain, meaning full duplex at 1Gbit, so I presume it's ok. The spec sheets seem to just show that most of the differences are things we won't use, except that we can trunk fewer ports together on the Dlink
Comment: It may be outside of your budget but since you're running hadoop what about using dedicated fiber optic connectivity for that? Separate from the ethernet network.
Comment: I calculated that the disks aren't likely to saturate the 1Gbit copper port we've got it wired with now, so I'm not overly concerned about a single being underutilized. We do have the option of aggregating 2 nics if we really want to beef up throughput.
Comment: Not sure this answer has any merit. I use a low end netgear switch in the rack - that is 48x1gbit port, 4x10gbit SFP+ and all the features you mentioned. Budget was ridiculously low compared to stuff like cisco. THere is a miggle ground here.
Answer: This is not easy to answer. It depends on your budget and how critical it is to be online 24/7.
If your budget is very limited but still you still have strict uptime requirements (somewhat mutually exclusive, you get what you pay for) you could get two of the cheaper switches (and 2 firewalls (could be linux servers) etc.) and implement a load balancing solution using something like haproxy.
On the other hand it pays off to go with sufficiently robust hardware from the start. Cisco switches will just work for decades, can be expanded, have redundancy etc.
If you go with the cheap switch don't expect it to do much more with it than vlans (personally I'd avoid vlans if at all possible). Cheap means it's not gonna be very good at much beyond being a plain switch. With regards to cheap perhaps also take a look at dell switches.


Integrate $\int \ln(x^2 +1)\ dx$

Question: $$\int \ln(x^2 +1)\ dx$$
I done it using integration by parts where
$\int u\ dv = uv - \int v\ du$
Let $u$ = $\ln(x^2 +1)$
$du = \frac{2x}{x^2+1} dx $
Let $dv = dx$ so $v=x$
$\int \ln(x^2 +1)\ dx = x \ln (x^2 +1) - \int \frac{2x^2}{x^2+1} $
I integrate $2\int \frac{x^2}{x^2+1} $ separately using substitution.
Let $u$ = $x^2 + 1$ -> $dx= \frac{1}{2x} du $
substitute $u$ back into it I get a simplified $\int \frac{x}{x^2 + 1} dx$
I used substitution again and got $ \frac{1}{2} \int \frac{1}{u} du$
When I sub it back into the original question, this is my final answer,
$x\ln(x^2 +1) + \frac{1}{2} \ln(x^2 +1) + C$
However, this answer is wrong,
The answer is, $x\ln(x^2 +1) - 2x + 2\tan^{-1} (x) + C $
I believe my integration of  $2\int \frac{x^2}{x^2+1} $ is wrong. Where did I went wrong ?
Answer: Your integration by parts in the beginning is correct. Truly :
$${\displaystyle\int}\ln\left(x^2+1\right)\,\mathrm{d}x =x\ln\left(x^2+1\right)-{\displaystyle\int}\dfrac{2x^2}{x^2+1}\,\mathrm{d}x$$
Now, handling the second integral, first of all let's factor out the constant and write $x^2$ as $x^2 + 1 - 1$ to split it up :
$${\displaystyle\int}\dfrac{2x^2}{x^2+1}\,\mathrm{d}x =\class{steps-node}{\cssId{steps-node-1}{2}}{\displaystyle\int}\dfrac{x^2}{x^2+1}\,\mathrm{d}x ={\displaystyle\int}\left(\dfrac{\class{steps-node}{\cssId{steps-node-4}{x^2+1}}}{x^2+1}-\dfrac{\class{steps-node}{\cssId{steps-node-5}{1}}}{x^2+1}\right)\mathrm{d}x $$
$$=$$
$$={\displaystyle\int}\left(1-\dfrac{1}{x^2+1}\right)\mathrm{d}x ={\displaystyle\int}1\,\mathrm{d}x-{\displaystyle\int}\dfrac{1}{x^2+1}\,\mathrm{d}x =2x-2\arctan\left(x\right)$$
The integral is now solved and we yield the result :
$${\displaystyle\int}\ln\left(x^2+1\right)\,\mathrm{d}x=x\ln\left(x^2+1\right)+2\arctan\left(x\right)-2x + C$$
Comment: Why can't I use substitution twice to solve the second integral
Comment: @user59439 The expression you yield via the other substitution is mistaken. You replaced the differential by the one you found but the expression remained unchanged. You still need to express the $x$ parts in therms of the $u$ you substituted. This is why you got a mixed result.
Answer: $2\int \frac{x^2}{x^2+1} $
Does not equal the expression with just an x in the numerator after the substitution .
You can add subtract 1 in numerator to integrate  $2\int \frac{x^2}{x^2+1} $
This is wrong :- $2\int \frac{x^2}{x^2+1} $
This is what you get after applying by-parts :- $2\int \frac{x^2}{x^2+1} dx $
Since differential of x is $dx$ .
In by parts formula we have differential of $u $ not it's differenciation.
Comment: The $\mathrm{d}x$ is not important as long as it's clear what you are intagrating with respect to.

Integrate $\int \ln(x^2 +1)\ dx$


Which player scored the most points in one game in each season?

Question: I would like to see a statistic showing which player has scored the most points in one basketball game every season. I know Wilt Chamberlain holds the general record, but it would be nice to see who came close and who had the best scoring game in each season.
Comment: http://www.basketball-reference.com/ probably has the info you're looking for.
Comment: Are you [Peter Noble](https://en.wikipedia.org/wiki/Peter_Noble), the former British football player? (It would be a nice coincidence to have the same person here as a user and mentioned in one of the answers.)
Comment: This wouldn't be too difficult to do via Wax's link... but it's a matter of either someone else doing repetitive/dull lookups for each season, or you :P
Answer: Since the 1963-1964 season as of the 2016-2017 NBA season:

2018-2019: James Harden (61 - 01/23/2019, 03/22/2019)
2017-2018: James Harden (60 - 01/30/2018)
2016-2017: Devin Booker (70 - 03/24/2017)
2015-2016: Kobe Bryant (60 - 04/13/2016)
2014-2015: Kyrie Irving (57 - 03/12/2015)
2013-2014: Carmelo Anthony (62 - 01/24/2014)
2012-2013: Stephen Curry (54 - 02/27/2013)
2011-2012: Deron Williams (57 - 03/04/2012)
2010-2011: LeBron James (51 - 02/03/2011)
2009-2010: Brandon Jennings (55 - 11/14/2009)
2008-2009: Kobe Bryant (61 - 02/02/2009)
2007-2008: Kobe Bryant (53 - 03/28/2008)
2006-2007: Kobe Bryant (65 - 03/16/2007)
2005-2006: Kobe Bryant (81 - 01/22/2006)
2004-2005: Allen Iverson (60 - 02/12/2005)
2003-2004: Tracy McGrady (62 - 03/10/2004)
2002-2003: Kobe Bryant (55 - 03/28/2003)
2001-2002: Allen Iverson (58 - 01/15/2002)
2000-2001: Jerry Stackhouse (57 - 04/03/2001)
1999-2000: Shaquille O'Neal (61 - 03/06/2000)
1998-1999: Grant Hill (46 - 02/08/1999), Allen Iverson (46 - 02/12/1999), Antonio McDyess (46 - 02/28/1999)
1997-1998: Karl Malone (56 - 04/07/1998)
1996-1997: Michael Jordan (51 - 01/21/1997)
1995-1996: Michael Jordan (53 - 03/07/1996)
1994-1995: Glen Rice (56 - 04/15/1995)
1993-1994: David Robinson (71 - 04/24/1994)
1992-1993: Michael Jordan (64 - 01/16/1993)
1991-1992: Dominique Wilkins (52 - 12/07/1991)
1990-1991: Michael Adams (54 - 03/23/1991)
1989-1990: Michael Jordan (69 - 03/28/1990)
1988-1989: Michael Jordan (53 - 01/21/1989)
1987-1988: Michael Jordan (59 - 04/03/1988)
1986-1987: Michael Jordan (61 - 03/04/1987, 04/16/1987)
1985-1986: Dominique Wilkins (57 - 04/10/1986)
1984-1985: Bernard King (60 - 12/25/1984), Larry Bird (60 - 03/12/1985)
1983-1984: Purvis Short (57 - 01/07/1984)
1982-1983: Adrian Dantley (57 - 12/04/1982)
1981-1982: Moses Malone (53 - 02/02/1982), Adrian Dantley (53 - 04/10/1982)
1980-1981: Adrian Dantley (55 - 02/06/1981)
1979-1980: George Gervin (55 - 01/23/1980)
1978-1979: George Gervin (52 - 01/11/1979)
1977-1978: David Thompson (73 - 04/09/1978)
1976-1977: Pete Maravich (68 - 02/25/1977)
1975-1976: Bob McAdoo (52 - 03/17/1976)
1974-1975: Rick Barry (55 - 01/23/1975)
1973-1974: Rick Barry (64 - 03/26/1974)
1972-1973: Phil Chenier (53 - 12/06/1972)
1971-1972: Chet Walker (56 - 02/06/1972)
1970-1971: Kareem Abdul-Jabbar (53 - 11/04/1970)
1969-1970: Lou Hudson (57 - 11/10/1969)
1968-1969: Wilt Chamberlain (66 - 02/09/1969)
1967-1968: Wilt Chamberlain (68 - 12/16/1967)
1966-1967: Wilt Chamberlain (58 - 02/13/1967)
1965-1966: Wilt Chamberlain (65 - 02/07/1966)
1964-1965: Wilt Chamberlain (63 - 11/26/1964)
1963-1964: Wilt Chamberlain (59 - 12/06/1963, 01/28/1964, 02/11/1964)
Comment: @JeopardyTempest Agreed...and since the season is not yet over, it makes little sense to update this answer before the end of the season (which is in roughly two weeks - last season, Kobe Bryant scored 60 in the last game of the season). Thanks for the edit, Deez.
Comment: We should probably aim to update this no more than once per year.


Enable clean urls drupal 7.56 / nginx - check failed

Question: I have an issue with the clean urls check. When I test there is an error in the Nginx log:
2017/10/06 09:49:01 [error] 468#468: *199 open()
"/usr/share/nginx/html/drupal-7/admin/config/search/clean-urls/check" failed
 (2: No such file or directory), client: 192.168.1.254, server: localhost,
 request: "GET /drupal-7/admin/config/search/clean-urls/check HTTP/1.0",
 host: "localhost".

I don't know if it is a nginx problem or a Drupal problem.
update : i change some things in the nginx.conf now i have an error in the log of nginx :
2017/10/14 21:55:08 [error] 4804#4804: *1 directory index of "/usr/share/nginx/html/drupal-7/" is forbidden, client: 192.168.1.254, server: localhost, request: "GET /drupal-7/?q=admin/config/search/clean-urls HTTP/1.1", host: "localhost".
Here is my nginx.conf :
http {
include       mime.types;
default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;
# set client body size to 200M #
client_max_body_size 200M;

server {
    listen 443 ssl http2;
    server_name toniozz75.fr;
    root /usr/share/nginx/html;
    index index.html index.htm;

location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ \.(php|html|htm)$ {
         root           /usr/share/nginx/html;
         fastcgi_pass   unix:/run/php-fpm/php-fpm.sock;
         fastcgi_index  index.php;
         try_files $uri $uri/ /index.php?$args;
         include        fastcgi.conf;
    }

Answer: You are missing some configuration for clean URLs. Try adding this snippet above the location @rewrite snippet.
 location / {
    try_files $uri /index.php?$query_string; # For Drupal >= 7
 }


Django rest auth email instead of username

Question: I have a django project in which I am using Django-rest-auth to do authentication. I want to use email with password to authenticate the user and not the username+password.
I have following settings in my settings.py but it didn't do anything for me:
REST_SESSION_LOGIN = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'EMAIL'
ACCOUNT_EMAIL_VERIFICATION = 'optional'

How can I achieve it?
Comment: 1. Do you get any errors? 2. Do you have a custom user model? 3. Did you try the following settings? http://django-allauth.readthedocs.org/en/latest/advanced.html#custom-user-models
Answer: Following setting worked:
#This is required otherwise it asks for email server
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# ACCOUNT_EMAIL_REQUIRED = True
# AUTHENTICATION_METHOD = 'EMAIL'
# ACCOUNT_EMAIL_VERIFICATION = 'optional'

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

#Following is added to enable registration with email instead of username
AUTHENTICATION_BACKENDS = (
 # Needed to login by username in Django admin, regardless of `allauth`
 "django.contrib.auth.backends.ModelBackend",

 # `allauth` specific authentication methods, such as login by e-mail
 "allauth.account.auth_backends.AuthenticationBackend",
)

Answer: I'm using this package too, and by call this config it worked for me:
ACCOUNT_AUTHENTICATION_METHOD = 'email'

Be careful about this config, this config belongs to django-allauth, see this:
class AuthenticationMethod:
    USERNAME = 'username'
    EMAIL = 'email'
    USERNAME_EMAIL = 'username_email'

The above class is the settings which is in allauth, so you should write 'EMAIL' in lower case.


Simple rails button question

Question: Very noob question here.
I am trying to make a digg-like website and when they click a button I want a counter to go up, just like in digg. So I did:
 <%=button_to("vote", :action => "vote")%>

and then in my controller I made a action:
def vote
  @article = Article.find(params[:id])
  @article.votes = @article.votes + 1
  respond_to do |format|
    format.html { redirect_to(@article.company) }
  end
end

When I do that you I get the error:
No route matches {:action=>"agree", :controller=>"companies"}

What should I do?
Comment: the routes.rb and the file names for controller and views would help here.
Answer: In a terminal type "rake routes", then look at your routes to find what path you need to use to vote for an article.
Then use
<%= button_to "Vote", vote_path(:id => article.id) %>
Just change the "vote_path" to the path in your rake routes output.
If it's not already in your rake routes file, put something like this in
match "vote/:id" => "controler_name#vote", :as => :vote

Comment: Good answer Solomon!

@GabeJacobs, you should read up on what routes are for. Any routing error implies that you either haven't specified the route yet or are using it incorrectly in your code. Info about your view and controller along with your route would us to help more.
Answer: Take a look at http://guides.rubyonrails.org/routing.html#adding-more-restful-actions
Comment: so I did "resources :companies do
      get 'agree'
  end" and I still get the same error

Simple rails button question


finding a value for $\sum_{n=2}^\infty\frac{\zeta(n)}{n!}$

Question: I have been trying to find the sum:
$$S=\sum_{n=2}^\infty\frac{\zeta(n)}{n!}$$
And I can't find if anyone else has posted about this. Interestingly wolfram alpha claims it converges for $n=0,1$ as well which cannot be correct. I think maybe there is some way of solving this by changing the order of summation:
$$S=\sum_{n=2}^\infty\frac 1{n!}\sum_{k=1}^\infty\frac{1}{k^n}$$
but I am struggling to justify this move, also trying to find:
$$\sum_{n=2}^\infty\frac{1}{k^n}$$
seems to be a geometric series so can I just do it like so, or will the bounds of the summation have changed? Thanks

From the advice of answers I have:
$$\sum_{n=2}^\infty\frac{(1/k)^n}{n!}=\sum_{n=0}^\infty\frac{(1/k)^n}{n!}-\frac1k-1=e^{1/k}-\frac1k-1$$
so we now have:
$$S=\sum_{k=1}^\infty e^{1/k}-\left(1+\frac1k\right)$$
Comment: $\sum_{k=1}^\infty \frac1{k^n}$ is not geometric but $\sum_{n=1}^\infty \frac1{k^n}$ is.
Comment: Expanding $\zeta(n)$ into its series representation and switching the order of summation before summing, you find that your sum is equal to $\sum_{k\ge 1} e^{1/k}-1-1/k.$ It converges because the summand is $\frac{1}{2k^2} +\mathcal{O}\left(\frac{1}{k^3}\right)$ as $k\to\infty$, but I am not sure if there is a way to evaluate it in closed-form.
Comment: You can change the order of summation btw. This follows because $S$ is convergent and the convergence is absolute.
Answer: It's a positive-term series, so rearrangements are fine (Baby Rudin, Ch.8, #3).
However, you won't get the $\frac1{n!}$ out of a series in $n$, so you'll have $\sum_{n=2}^\infty \frac{(1/k)^n}{n!}$. Not a geometric series, but still one that you should recognize ...
Answer: At the bottom of this page from Wolfram Mathworld on the Riemann zeta function, it is stated that the constant you define - which amounts to equation $(133)$ of the article and which I'll call $C_1$ here - does not have a closed form. Similar constants, like
\begin{align*} C_{2} &:= \sum_{n=1}^{\infty} \frac{\zeta(2n)}{n!} \\
& \approx 2.407446554790328514709486656223022725582266, \text{ and} \\  C_{3} &:= \sum_{n=1}^{\infty} \frac{\zeta(2n)}{(2n)!} \\
&\approx 0.869001991962908998811054805561395688892494\end{align*}
which are defined in equations $(134)$ and $(137)$, don't have a closed form either.
In the following MSE question I ask for conjectured closed forms of such constants. As of September 2, 2022, no serious answers have been given yet.
Answer: Well, here is an approximate value of $S$.
Observe that as $n$ gets bigger $\zeta(n)$ tends to $1$ moreover $\zeta(n)$ is decreasing sequence.  So for large $n$ we can consider $\zeta(n)$ to be approximately equal to $1$.
So
$$
S \approx \sum_{n=2}^{N} \frac{\zeta(n)}{n!} + \sum_{n = N+1}^{\infty} \frac{1}{n!} \approx e - 2 + \sum_{n = 2}^{N} \frac{\zeta(n) - 1}{n!}
$$
Actually $\zeta(n)$ quickly converge to $1$ as $n$ becomes bigger. For example $\zeta(6) = \pi^6/945 \approx  1.017... $ and  $\zeta(8) = \pi^8/9450 \approx $1.004...
So depending on the need of accuracy you need to choose $N$ and can calculate the value of $S$.
Bonus thing : We have an exact expression for zeta function at even positive integers given by
$$
\zeta(2n) = (-1)^{n-1}\frac{(2\pi)^{2n}B_{2n}}{2(2n)!}
$$
where $B_n$ are Bernoulli's number. I leave it to you use this if you need more exact expression even though we do not know have any closed expression at odd integers.


Audio latency in live bands

Question: In computer music one usually says that the audio latency of the system should ideally be less than 10ms…
On the other hand, as the speed of sound is around 340 m/s in the air it means that whenever you are away of more than 4m from an audio source, you perceive the sound emitted by this source with a latency which is greater than 10ms. Does it means that someone performing should be this close to his amplifier? Also, when several musicians are performing together (let's say a march band, which farthest musicians are way farther than that) I guess there is a kind of "closest neighbor synchronization" so that the whole band is in synced, but still…
(Obviously,this does not apply for amplified bands as the speed of sound in cable is close to the speed of light, or when a director a synchronizing everybody by visual signals, they go at the speed of light too…).
Are we overthinking this latency problem when doing computer music?
(Not much of a real question, but this has puzzled me for quite a long time…)
Comment: @CarlWitthoft by that I refer to the amount of time between the action on the instrument and the reception of the sound at the ear. Not even talking about recording, but just to have the feeling that the instrument is not sloppy (see https://musicproductiontips.net/audio-latency-optimize-your-buffer-size/ )
Comment: Sound from Guitar to Amplifier doesn't go as Sound but as Electromagnetic pulses (Pulses or Audio-forms depends on the type of input - Analog and Digital). In other words Speed of sound in Wire = Lights speed. So latency in Computer music is not caused by 340m/s but your Computer hardware.
Comment: @RishiNandha_M Yes, I agree. I am just comparing this value with the latency you can expect for *air vehiculated sound* in a live environment. I did not talk about the speed of sound in the paragraph on computer music...
Comment: @CarlWitthoft 60 / 120 / 16 = 0.125s, a bit more than 2ms :D
Comment: @moonwave99  dammit I calculated bp**s**   :-(  which will teach me to type without thinking
Answer: If you ever have a chance to play a very large pipe organ, give it a try. You will have difficulty playing until you get used to the latency of several tenths of a second.
The 10ms figure was determined about 50 years ago when a new keyboard design was invented. In this design, currently used for computer keyboards and most music keyboards, the keys are scanned one-by-one. But if it took 100 ms or more to scan all the keys, the timing could sound off by any amount from zero to 100 ms and the performer lost a sense of "feel" of the keyboard. When the cycle was made faster so that it took only 10 ms, none of the performers had this problem.
It's likely that the variance in the latency is more of a problem than the latency. If every note is late by exactly 100 ms, as when you are far away from your guitar amplifier, you quickly adjust. Organ pipes are at varying distances from the organist.
How large groups of performers stay in sync is a very interesting question. I don't know if it's been studied with marching bands, but it has been studied in basketball fans.
In 1995 Cherrill P. Heaton determined that when a basketball player's shot goes into the basket without touching the rim or the backboard, the crowd chants "Air Ball!" always in unison, and always on the notes F for Air and D for Ball. His study was published in the journal Popular Music And Society. Here is a link to a newspaper article about it:
https://www.latimes.com/archives/la-xpm-1995-09-24-mn-49383-story.html
Comment: i've been in large marching bands, and yes the sections farthest from the home-crowd side of the field are taught to "lead" the beat so there sound will be in sync with the closest portion of the band from the point of view of the audience.
Comment: I played piano-and-organ duets in a church with the piano up front and the organ in the gallery in the back, maybe 40 feet apart. It worked fine, But I have seen performances of pieces in very large churches, for instance the Berlioz Te Deum, where the organist had to anticipate the beat. It sounded OK in some places in the seats; not quite so OK in others.
Comment: Thanks for your answer! I guess the orchestra is working a bit like your basketball example: as everybody is following the same "object" (the ball or the director) and as the speed of light is so big, everyone is synced with that object… But without director I still wonder…
Answer: When you stop to realize a rock and roll or country music stage is often 40, 50 or 60 feet across the front of the stage, you might expect that latency between performers might become a real problem, but when every instrument is miked up or D.I.ed into the sound system and mixed the resulting sound has no noticeable latency between instruments because everything is close miked, blended together and presented back to the performers in a monitor system of one sort or another. The same process happens for the audience and the only latency problem for the audience happens as the audience member is situated further away from the speaker arrays and the sound arrives later at their seating area. Even so,  the instruments have already been blended into one main sound picture so the latency between instruments is rarely problematic. The room acoustics are where most of the problems really occur.
Comment: Yes, obviously I am expecting this kind of problems when the sound is traveling a great path in the air: for big acoustic bands (or for instance of the monitors are too far away)...

Audio latency in live bands


Can't access value of dropdown modified by Ajax

Question: I have two dropdown fields, #2 is modified by Ajax based on #1 selection. When I try to access #2 value in the submit handler, I get an empty result. I've checked this against the docs and examples and I can't see what am I doing wrong here?
The code:
function admin_select_meeting_type_form($form, &$form_state) {
  $meet_types = get_meeting_types();
  $form['meet_types']=array(
    '#type' => 'select',
    '#title' => t('Select meeting type:'),
        '#options' => $meet_types,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'ajax_select_meeting_type_callback',
      'wrapper' => 'meetlist-div',
      'effect' => 'slide',
    ),
  );
  $form['meet'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );
  return $form;
}

function admin_select_meeting_type_form_submit($form, &$form_state) {
    drupal_set_message('You selected:' . $form_state['values']['meet']);
}

// Implement ajax update of meeting select field
function ajax_select_meeting_type_callback($form, $form_state) {
     if ($form['meet_types']['#value']) {
        $dispmeet = array(); // truncated for brevity, my array processing is done here
        $form['meet'] = array(
           '#type' => 'select',
           '#prefix' => '
',
           '#suffix' => '
',
           '#title' => t('Select meeting:'),
           '#values' => array_keys($dispmeet),
           '#options' => $dispmeet,
           '#required' => TRUE,
        );
        return $form['meet'];
     }
}

Answer: You shouldn't build the form element in your callback.  You want something like this:
function admin_select_meeting_type_form($form, &$form_state) {
  $meet_types = drupal_map_assoc(array('conference' => 'conference', 'event' => 'event'));
  $form['meet_types']=array(
    '#type' => 'select',
    '#title' => t('Select meeting type:'),
    '#options' => $meet_types,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'ajax_select_meeting_type_callback',
      'wrapper' => 'meetlist-div',
      'effect' => 'slide',
      'method' => 'replace'
    ),
  );
  $form['meet_container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (!empty($form_state['values']['meet_types'])) {
    $form['meet_container']['meet'] = array(
      '#type' => 'select',
      '#title' => t('Select meeting:'),
      '#options' => drupal_map_assoc(array('test', 'test2')),
      '#required' => TRUE,
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );

  return $form;
}

function admin_select_meeting_type_form_submit($form, &$form_state) {
    print_r($form_state['values']);
    die();
}

// Implement ajax update of meeting select field
function ajax_select_meeting_type_callback($form, &$form_state) {
  if ($form['meet_types']['#value']) {
    return $form['meet_container'];
  }
}

Comment: Thanks Chris! Works great, I just added a minor note on where I added the processing for ['meet'] #options once the first pulldown was selected.


I can't fetch anything else than '1' to my PDO query

Question: Here is my PDO request :
$query = db_select('review_ratings_table')
   ->fields('review_ratings_table',array('review_nid'))
   ->condition('loc_id', $loc_id, 'LIKE')
   ->condition('user_id', $user_id, 'LIKE')
   ->condition('valid', '1', '=')
   ->execute();
while($record = $query->fetchAssoc()) {
 drupal_set_message('
test '.print_r($record).'
');
}

I have tried many ways to get the result of this request (fetchAll, fetchField, fetchAssoc ...) and I keep printing "1" instead of the review_nid or anything else.
Thanks for you help.
Will
=> Hi,
If I use dvm($query) I get that :

DatabaseStatementBase::__set_state(array(
     'dbh' =>
    DatabaseConnection_mysql::__set_state(array(
       'needsCleanup' => false,
       'target' => 'default',
       'key' => 'default',
       'logger' => NULL,
       'transactionLayers' =>
      array (
        'drupal_transaction' => 'drupal_transaction',
      ),
       'driverClasses' =>
      array (
        'SelectQuery' => 'SelectQuery',
        'DatabaseTransaction' => 'DatabaseTransaction',
      ),
       'statementClass' => 'DatabaseStatementBase',
       'transactionSupport' => true,
       'transactionalDDLSupport' => false,
       'temporaryNameIndex' => 0,
       'connectionOptions' =>
      array (
        'database' => '*******',
        'username' => '*******',
        'password' => '*******',
        'host' => 'localhost',
        'port' => '3306',
        'driver' => 'mysql',
        'prefix' =>
        array (
          'default' => '',
        ),
      ),
       'schema' => NULL,
       'prefixes' =>
      array (
        'default' => '',
      ),
       'prefixSearch' =>
      array (
        0 => '{',
        1 => '}',
      ),
       'prefixReplace' =>
      array (
        0 => '',
        1 => '',
      ),
    )),
     'queryString' => 'SELECT review_ratings_table.review_nid AS review_nid
  FROM
  review_ratings_table review_ratings_table
  WHERE  (loc_id LIKE :db_condition_placeholder_0 ESCAPE \'\\\') AND (user_id = :db_condition_placeholder_1) AND (valid = :db_condition_placeholder_2) ',
  ))

and

Error message
  Recoverable fatal error: Object of class DatabaseStatementBase could not be converted to string in review_ratings_table_node_presave() (line 52 of C:\Bitnami\drupal-7\apps\drupal\htdocs\sites\all\modules\custom\review_ratings_table\review_ratings_table.module).

and
dvm($query->fetchAssoc()); gives me that

array(
    'review_nid' => '2',
  )

Which is what I want but I don't know how to access it.
Thanks
Comment: What's in `$loc_id` and `$user_id`, and why are you using `LIKE` for (what I assume is) a numeric field? It'd be a good idea to try your query in raw SQL first to make sure that logic is sound
Comment: Hi Clive, $loc_id is a string an $user_id an integer. I have tried with a raw SQL and I got the same result unfortunately. I have also tried without any conditions and it was the same. Thanks
Comment: what are the results of `dvm($query);` and  `dvm($query->fetchAssoc());`? If it doesn't show anything then try with `var_dump()` also...
Comment: Hi  Jhilke Dai I have added the result of dvm($query); into my original question. I don't know why but var_dump gives me an empty result. thanks
Comment: Following your latest edit, ``$result = $query->fetchAssoc(); return $result[0]['review_nid'];``
Comment: Hi Ben, it would seem logical but I have already tried and it's not working. thanks
Comment: See my answer below
Comment: $result = $query->fetchAssoc(); return $result['review_nid']; thanks this was the solution sorry for the belated answer.
Answer: With drupal_set_message('
test '.print_r($record).'
'); you're putting the return value of print_r into a string, not printing the contents of $record.
You can acccess the value you need with:
$result = $query->fetchAssoc();

// make sure we found something
if (empty($result) || empty($result[0]['review_nid'])) {
  dpm("No result");
}

// load the noad we found
$node = node_load($nid)
dpm($node);

Comment: Hi Ben, what do you mean by "do something with the nid"? I would need be able to display at least for testing purpose. thanks
Comment: Added more code above but, really, as long as you use `print_r` correctly in your original code you're good to go.


Python - checking if a word from a list is a substring of another string

Question: def find_word_list(query, word_dict):
    for word in word_dict:
        if word in query:
            print("true")
        else:
            print("false")
    return

If I call the function as follows, it would just print an empty list.
query1 = ["donaldtrump"]
dict1 = ["donald", "trump"]

find_word_list(query1, dict1)

The result I expected:
true
true

Here's what I actually got
false
false

both 'donald' and 'trump' are the substrings of a given query, 'donaldtrump'. How should I fix the code?
Answer: I just figured out myself. The problem was, that the query1 variable is a list type, so it was ["donaldtrump"] not "donaldtrump".
After changing the variable type to string, it now works as I expected.
Comment: Well.. stackoverflow isn't a debug service, but since you serviced yourself I don't know what to do now.. have an upvote AND a downvote lol


Specific user role can't log in

Question: I'm having a very strange problem:
Most user roles can login without a problem (administrators, clients, etc...).
But users with the 'registered user' role can not login through the form. The login form does not respond. In the log messages the failed login attempts are not logged.
The only way the users (with role 'registered user') can login is through the request new password link.
So the user clicks on the link, receives an email with a login link, and when they click on the link in the email they are logged in. So than they can edit their account and even change the password.
However, when they log out again and try to login with the new password it does not work anymore, the form does not respond again.
The only way that user can get logged in again is through the request new password procedure.
Anyone have any idea what could be causing this?
I suspect it has something to do with some kind of permissions.
Some of the modules i installed who could maybe give a conflict:
Logintoboggan, Registration role
Any help would be greatly appreciated.
Greetings
Answer: Thanks for the help.
I did try to login with an email and username, same results for both.
But very strangely everything works now...
And i have no idea what i did to fix it.
Last thing i did was update every module and the Drupal Core.
And today the login form works again as it should...
I would love to give more information for future people experiencing this problem but frankly i have no clue what solved it.
Thanks again for all the help!
Greetings
Answer: Try to use below module :

Password Reset

The password_reset module allows for passwords to be reset without
  involving e-mail addresses through the use of security questions. This
  module would typically be used on sites that do not require users to
  enter their e-mail addresses or prefer not having to deal with spam
  folder issues etc.

Simple Password Reset

This modules simplifies the password reset process.
Without this module enabled, core Drupal prompts the user to log in
  via a one-time login form. After clicking "Log in", the user is
  brought to their profile edit form where at long last they can change
  their password.

Password Reset Landing Page (PRLP)

The "PRLP" module enhances the original password reset landing page by
  letting a user set their new password at the same time they "log in"
  using the one-time-login link. It can also show a username and email
  address field. The password entry field can be configured to be
  mandatory. Other entry fields can be hidden through configuration and
  the page the user is taken to after login can be configured.
Comment: Hello

Thank you for you're answer. But i think i may have not been clear enough in my question.
I editted it a bit to make it a bit clearer.
Cause i don't immediately see how these modules could help me out?

Greetings
Comment: Means in your site there is a registration form. After submission of form OTP send to the user email id & after click on OTP they can login successfully. But after logout users have facing issue in login with there existing password. Am I right ?
Comment: Yes, that's exactly it. The same goes for users who have an account already for a long time. They can't login through the login form. Only through the link you receive when you request new password. And this happens only for a certain role (registered users). All the other roles don't show this problem.
Comment: First Try to check "registered users" roles permission. Also check "Rules". I think this can happen due to some "Rules" for that role.
Answer: I had a similar issue and was kind of user error.  As on our other Drupal installations I had it set to except both Username and Emails ; and on the site with an issue only Username.  So the answer in this case was to make sure users where using their Usernames and not Emails ! *Some* Users Experiencing Login Failures
I hope this helps

Specific user role can't log in


Does Google Maps in android app works in UK

Question: I have created android application that uses Google Maps, ans it works fine here in Palestine(Middle east). When someone try it on UK either on the emulator or on the real device it doesn't show any map!
What is the possible problem ?
Comment: Have you checked logcat for errors?
Answer: Your UK tester doesn't have an Internet connection, or is using a different APK than the one you tested (and therefore you might have a problem with your signing key and Maps API key), or is testing using a device that does not legitimately have Google Maps on it, or something along those lines.
Comment: Yes the problem was in the Map key !


Como mapear uma Lista para outra Lista?

Question: Como posso mapear uma lista de um tipo para outra lista de outro tipo ?
Estou recebendo uma lista de objeto do tipo
public List<DetalheViagem> DetalheViagems { get; set; }

E preciso passar os valores para outra lista do tipo.
public List<DetalheViagemDto> Viagens { get; set; }

Tem alguma forma de fazer isso sem ser em loop?
passagemAprovadaEdiDto.Viagens = new System.Collections.Generic.List<DetalheViagemDto>()
{
   // Incluir a lista de objeto em vez de fazer um a um ...
   new DetalheViagemDto()
   {

   }
};

Comment: `DetalheViagemDto` herda de `DetalheViagem` ou só existem propriedades em comum?
Comment: Só propriedades, mas nem todas estão com o mesmo nome, por exemplos, tenho IdViagem em um e no outro só Id ...
Answer: Utilize o Select na lista, ele projeta um novo tipo a partir do tipo atual.
Exemplo:
List<DetalheViagemDto> viagens = detalheViagens.Select(t =>
                                 new DetalheViagemDto
                                 {
                                   Prop1 = t.Prop1,
                                   Prop2 = t.Prop2,
                                   /*Etc...*/
                                 }).Tolist();

Como mapear uma Lista para outra Lista?


Laurent Series Difficulty

Question: Hello all at StackExchange,
I'm having some trouble understanding computing the Laurent series for different domains.
Here's my approach to finding the Laurent series for $\dfrac{3}{(z+1)(z-2)}$ for the following domains.
1) $|z| < 1$
2) $ 1 < |z| < 2$
3) $|z| > 2$
So, using partial fraction decomposition, I obtain $\dfrac{1}{z-2} - \dfrac{1}{z+1}$.
The idea is to obtain series for both fractions, which is understandable (Taylor series and power series of complex functions is understood), but I am not understanding $\bf{why}$ the fractions become modified as follows (the algebra is understood, not the idea).
1) We change $\dfrac{1}{z-2} = -\dfrac{1}{2}\left[\dfrac{1}{1-\frac{z}{2}}\right]$ and leave $\dfrac{1}{z+1} = \dfrac{1}{z-(-1)}$.
2) We still have $\dfrac{1}{z-2} = -\dfrac{1}{2}\left[\dfrac{1}{1-\frac{z}{2}}\right]$ but instead $\dfrac{1}{z+1} = \dfrac{1}{z}\left[\dfrac{1}{1+\frac{1}{z}}\right]$.
3) We change $\dfrac{1}{z-2} = \dfrac{1}{z}\left[\dfrac{1}{1-\frac{2}{z}}\right]$ but keep  $\dfrac{1}{z+1} = \dfrac{1}{z}\left[\dfrac{1}{1+\frac{1}{z}}\right]$.
Do the fractions change because of analyticity in the domains, and in particular, why do we factor a term of $\dfrac{1}{z}$ for some of them? Much help would be appreciated, and regards.
Comment: I believe for part 1) you should have: $\dfrac{1}{1-(-z)}$ because the sum of the geometric series needs to be of the form shown by blf below, where the $1$ in the denominator is positive.
Answer: I think that the reason is that you need to use the identity $$\frac{1}{1-w} = \sum_{n=0}^\infty w^n$$ which holds only for $|w| < 1$. Notice that if $|z|<1$, then $\frac{1}{z+1} = \sum_{n=0}^\infty (-z)^n$ is valid, but not for $|z| > 1$. That's why in the other two cases, you need to write it as $$\frac{1}{z} \cdot \frac{1}{1+\frac 1 z} = \frac{1}{z} \sum_{n=0}^\infty \left(-\frac 1 z\right)^{n}$$
in order to use the identity, since now $\left|\frac 1z\right| < 1$.
I might be mistaken, so please correct me if you find a mistake in what I have said.
Comment: This is the reason that I learned in class. After factoring $1/z$ then the geometric series will converge only for $|1/z|<1$ which can be rearranged to give $1<|z|$
Answer: I think blf gave the answer you probably want. But I'll add some extra reasoning:
For 1) with the factored fractions you've given, the corresponding geometric series you find for $-\frac{1}{2}\left[\frac{1}{1-\frac{z}{2}}\right]$ will be valid in $|z|<2$ and the series for $\frac{1}{1-(-z)}$ will be valid in $|z|<1$ so together they are both valid in the smaller of the two circles (which is your domain $|z|<1$).
For 2) you have your series representation for $\frac{1}{z-2}$ is already valid inside $|z|<2$ but the series for $\frac{1}{z+1}$ that you found in part 1) is only valid for $|z|<1$ and you need it valid in $|z|>1$ so that is the series that you will need to alter.
For 3) your series for $\frac{1}{z+1}$ from part 2) will be valid in $|z|>1$ so it can be left alone. But the series representation for $\frac{1}{z-2}$ is still only valid inside the circle $|z|<2$ so you will need to alter it to make it valid in $|z|>2$ so that they will be both be valid in the larger of the two circles which is your domain $|z|>2$.

Laurent Series Difficulty


How can I bind to a sub-property of a specific item in a List?

Question: How can I create a binding to a sub-property of a specific element in a list?
I've created a class that exposes an IList property:
    public IList<VideoChannel> VideoChannels {
        get {
            const int NumVideoChannels = 4;

            return (new List<VideoChannel>(NumVideoChannels) {

                new VideoChannel("Channel 1") {
                    VideoActive = !_rawData[Main][0x04].BitIsSet(0),
                    OutOfRange = !_rawData[Main][0x05].BitIsSet(0) },

                new VideoChannel("Channel 2") {
                    VideoActive = !_rawData[Main][0x04].BitIsSet(1),
                    OutOfRange = !_rawData[Main][0x05].BitIsSet(1) },

                new VideoChannel("Channel 3") {
                    VideoActive = !_rawData[Main][0x04].BitIsSet(2),
                    OutOfRange = !_rawData[Main][0x05].BitIsSet(2) },

                new VideoChannel("Channel 4") {
                    VideoActive = !_rawData[Main][0x04].BitIsSet(3),
                    OutOfRange = !_rawData[Main][0x05].BitIsSet(3) },

            }).AsReadOnly();
        }
        set { ;}
    }

I've also created an 'LED' UserControl with a single boolean property ('LedOn') that determines the colour of the led.
I want to create 8 'LED' controls, each of which is bound to a specific 'VideoActive' or 'OutOfRange' property in the IList above.
This doesn't seem to work:
        ledVideoActiveChannel1.DataBindings.Add("LedOn", _myDevice, "VideoChannels[0].VideoActive");

        ledOutOfRangeChannel1.DataBindings.Add("LedOn", _myDevice, "VideoChannels[0].OutOfRange");

The error is "Child list for field VideoChannels[0] cannot be created."
I'm relatively new to C# and OOP in general, so forgive me if this is a trivial question.
Thanks!
Comment: WinForms, WPF or ASP.NET? They all use C#, UserControls and DataBinding.
Answer: How about this:
ledVideoActiveChannel1.DataBindings.Add("LedOn", _myDevice.VideoChannels[0], "VideoActive");
ledOutOfRangeChannel1.DataBindings.Add("LedOn", _myDevice.VideoChannels[0], "OutOfRange");

That, and make sure your VideoChannel class implements INotifyPropertyChanged.
Comment: I've already implemented INotifyPropertyChanged on VideoChannel.  Your suggestion using '_myDevice.VideoChannels[0]' seems to compile just fine, however updates don't seem to propagate.  Could it be because _myDevice is returning a NEW List on each 'get' request?
Answer: that would be a magical "magic string" ;-)
You can create separate property like so:
public bool OutOfRange
{
  get{ return VideoChannels[0].OutOfRange; }
}

Then
ledOutOfRangeChannel1.DataBindings.Add("LedOn", _myDevice, "OutOfRange");

You would want to add null checking also...
Comment: Yes, this was my first approach and worked just fine.
'_myDevice' is made up of a number of other similar properties as well (SerialDataChannels, VideoChannels, BackplaneChannels, etc.).

I felt like exposing a couple of ILists was a cleaner approach - one List for each collection of channels vs. 50-odd individual properties.


Is there a git repository for Drupal releases only?

Question: Having cloned drupal from the git repository using
git clone --branch 7.x http://git.drupal.org/project/drupal.git

I noticed that I'm actually running 7.9-dev when what I want to be running is the most recent stable. Is there a git repository or branch that I can pull from to run the most recent stable release? I've seen references to git.drupal.org/project-stable/drupal.git around the net, but that doesn't seem to be a valid repository anymore.
Answer: Drupal releases are marked with a corresponding "tag" within the repository. When you clone a git repository, you get all the tags and branches along with it. Running the following command from within the repository will checkout the version 7.8 tag:
git checkout 7.8

To list the available tags, type git tag. To list all available branches, type git branch -a.
Comment: I didn't even think to look at the tags. (facepalm)


Why does $ \lim_{x \rightarrow \pi }\frac{\sin(mx)}{\sin(nx)}=\left ( -1 \right )^{m-n}\;\frac{m}{n}$, for positive naturals $m$ and $n$?

Question: Encountered this in a sample university admission exam.
$$
\lim_{x \rightarrow \pi } \frac{\sin(mx)}{\sin(nx)} \quad n,m\in \mathbb N_{> 0}
$$
What surprised me was that the answare sheet suggested that the limit was equal to:
$$
\left ( -1 \right )^{m-n}\;\frac{m}{n}
$$
Graphing the function made it clear for me that this is the correct answer, but i cannot understand why.
Comment: The sine function is zero at integer multiples of $\pi$ so you get $\frac{0}{0}$ which is indeterminate. Using L'Hospital's rule gives the result.
Comment: Can you use Taylor expansions to solve this?
Comment: It will be clear if you graph both $\sin(mx)$ and $\sin(nx)$ near $x = \pi$. You will notice that $\sin(mx)$ looks almost like $(-1)^mm(x - \pi)$ near $x = \pi$, while $\cos(mx)$ looks almost like $(-1)^nn(x - \pi)$. Try to explain these by taking derivatives.
Answer: You can substitute $x=y+\pi$, so you get
$$
\lim_{y\to0}\frac{\sin(my+m\pi)}{\sin(ny+n\pi)}
$$
Since $\sin(\alpha+k\pi)=(-1)^k\sin\alpha$, you get
$$
\lim_{y\to0}\frac{(-1)^m\sin(my)}{my}\frac{ny}{(-1)^n\sin(ny)}\frac{m}{n}
$$
and you can apply the basic limit
$$
\lim_{x\to0}\frac{\sin x}{x}=1
$$
so you get
$$
(-1)^m(-1)^{-n}\frac{m}{n}=(-1)^{m-n}\frac{m}{n}
$$
Comment: @TymaGaidash You get $(-1)^{m-n}m/n$, don't you?
Comment: What is the complete, or more complete, answer?


Retrieve Excel Workbook Connection Properties

Question: I am attempting to grab the "Command Text" from the Connection Property window in an Excel file using python. However, I cannot find the object that contains this information. In the below picture I would like to retrieve the highlighted EXEC sp_FooBar as a string:

I am able to retrieve the Connection names with:
import odbc
import win32com.client
file = r'PATH_TO_FILE'
xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.workbooks.open(file)
for x in wb.connections:
    print(x)

But I'm not sure how to use the <COMObject <unknown>> object further to grab the command text. I'm thinking win32com may have something, but can't seem to crack the code.
Comment: Complete shot in the dark here, but is it possible that `commandtext` is a property of `connections`? Perhaps `.connections.oledbconnection.commandtext`?
Answer: You can get the CommandText property from a OLEDBConnectioninstance like this:
import odbc
import win32com.client

file = r'PATH_TO_FILE'
xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.workbooks.open(file)
for x in wb.Connections:
    print(x.OLEDBConnection.CommandText)
xl.Application.Quit()

Comment: this is amazing. Do you have any links to documentation on the OLEDBConnection instance? I want to know *how* you solved this, as I'm sure I'll have future needs similar to this question
Comment: The documentation that exists is the one from [MSDN](https://learn.microsoft.com/en-us/office/vba/api/overview/excel/object-model). You can find all the references there.
Comment: Your solutions work well with the xlsx files, but I am unable to open the xlsm file, the code just spins indenfinitely. Is there a way to see the connections in the xlsm? Thanks.


From where can I get a library for c which will help me to write a C program to decrypt through 3DES in CBC mode?

Question: I want to write a simple program where I can call the functions from a library and pass them the encrypted data as input and get the output as the decrypted data.
Which C library would be suitable for this.
Answer: OpenSSL will probably be your best bet. It's available on most systems, and has functions for doing triple-DES (e.g. DES_ede3_cbc_encrypt). See the des(3) man page for more information.
Most Linux distributions will have a development package for openssl which contains the header files for the library. On Debian-based distros (like Ubuntu), do sudo apt-get install openssl-dev. Alternatively, you can download the library source and compile it yourself.
Comment: I visited this site sometime back but there is no option to download the library file over there.
Comment: The function which they have told that does the encryption is
void DES_ncbc_encrypt(const unsigned char *input, unsigned char *output,long length, DES_key_schedule *schedule, DES_cblock *ivec,int enc);
I wanted to see what are the data types of these parameters so that I can pass suitable values. But not able to get the library file.
Comment: Updated answer to include download info. The data types would be defined in `openssl/des.h`, which can be found in your Include path (`/usr/include/` on my Ubuntu system).
Comment: I got the function named DES_ncbc_encrypt in des.h but how do I pass suitable values to the parameters untill I know what datatypes are used in parameter. In des.h only function declaration is there not the definition. So what value should I pass in the parameters while passing the values. theparameters which I have doubt about are DES_key_schedule *schedule,DES_cblock *ivec,int enc


Plots in R involving two categorical variables

Question: I have data containing
v1<-sample(c( "A", "B","C","D"),100,replace=T)

v2<-sample(c(0,1),100,replace=T)

dta<-data.frame(cbind(v1,v2))

Both v1, v2 are factor variables. I want to know what kinds of graphs there exist to explore their relationship. Can I get a heat map, can it be done in R?
Answer: You can just use the heatmap function on a contingency table and skip the dendrograms (parameters Colv and Rowv).
heatmap(table(v1,v2), Colv=NA, Rowv=NA, scale='none')

Comment: can you please elaborate it , I need to interpret it
Comment: Well, I just used your code to generate v1 and v2. Make yourself familiar with the table function and play with heatmaps parameters: Colv, Rowv and scale.


How to solve $\sin78^\circ-\sin66^\circ-\sin42^\circ+\sin6^\circ$

Question: Question:
$ \sin78^\circ-\sin66^\circ-\sin42^\circ+\sin6° $
I have partially solved this:-
$$ \sin78^\circ-\sin42^\circ +\sin6^\circ-\sin66^\circ $$
$$ 2\cos\left(\frac{78^\circ+42^\circ}{2}\right) \sin\left(\frac{78^\circ-42^\circ}{2}\right) + 2\cos\left(\frac{6^\circ+66^\circ}{2}\right)\sin\left(\frac{6^\circ-66^\circ}{2}\right) $$
$$ 2\cos(60^\circ)\sin(18^\circ) + 2\cos(36^\circ)\sin(-30^\circ) $$
$$ 2\frac{1}{2}\sin(18^\circ) - 2\cos(36^\circ)\cdot\frac{1}{2} $$
$$ \sin(18^\circ) - \cos(36^\circ) $$
At this point I had to use a calculator. Does anyone know a way to solve it without a calculator.Thanks in advance.
Comment: @ajotatxe ^{\circ}.
Comment: @ajotatxe ° = Alt + 248 (use your numpad for 248)
Comment: @user2838619, please, please, please for the sake of love don't do that when you have Latex available. :-(
Comment: @Michael Hardy: how do you write the symbol for degrees?
Comment: @ajotatxe : See my latest edit to the question. ${}\qquad{}$
Comment: @ZainPatel : The braces aren't actually necessary.  One can write ^\circ.  Braces are needed for superscripts only when the supercript contains more than one item, as in $x^{35}$ (with two digits in the superscript). ${}\qquad{}$
Comment: @MichaelHardy, Ah, I figured that \circ would count as 4 items, each letter being counted as one item in the same way that each digit was in 35, thanks for that! :-)
Comment: Result is readily available from https://math.stackexchange.com/questions/827540/proving-trigonometric-equation-cos36-circ-cos72-circ-1-2?noredirect=1&lq=1
Answer: Angles that are multple of $18$ degrees occur in the regular pentagon with its diagonals and their trigonometric ratios are related to the golden ratio.
To find them, take an isosceles triangle with angles $A=36$ and $B=C=72$ degrees. Draw the bisector of $B$ that intersects $AC$ in a point $D$. Note that the triangles $ABC$ and $BCD$ are similar. Now let $1=AB$, $x=AD$. Note now that $ABD$ is also isosceles, and $AD=BD=BC=x$. The mentioned similarity yields
$$\frac1x=\frac x{1-x}$$
which is precisely the equation that defines the golden ratio.
To find $\cos 36^\circ$ draw the altitude of the triangle $ABD$ from $D$, that bisects the side $AB$. Then
$$\cos 36^\circ=\frac{1/2}{x}$$
Now, with the classical trigonometric identities, you can easily find closed expressions for the sine and the cosine of $18$, $36$, $54$ and $72$ degrees. For the angle of $18$ degrees, don't use half-angle formulae, but
$$\sin 18^\circ=\sin(90^\circ-72^\circ)=\cos 72^\circ=\cos^2 36^\circ-\sin^2 36^\circ$$
Remark: Perhaps you are wandering what that pentagon had to do with all of this. If you choose a vertex $A$ of a regular pentagon and draw the two diagonals $AB$ and $AC$ from it, the triangle $ABC$ is similar to the one we have just used.
Answer: There is not fast but strightforward way. $18^\circ = \pi/10$; let $s=\sin{(\pi/10)}$ so, we should evaluate
$$
a=\sin\frac\pi{10}-\cos\frac{\pi}{5}=2s^2 + s - 1.
$$
We may express $\sin5x$ in terms of $\sin x$:
$$
\sin5x=16\sin^5 x - 20\sin^3 x + 5\sin x
$$
(i.e. from $\sin5x=\sin(4x + x), \sin4x=2\sin2x\cos2x$, or by de Moivre). For $x=\frac{\pi}{10}$ we have $\sin5x=1$:
$$
16s^5 - 20s^3 + 5s -1 =0,
$$
or
$$
(s-1)(-1+2s+4s^2)^2 = 0;
$$
So,
$$
4s^2 + 2s - 1= 0=2a+1 \Longrightarrow a = -\frac12
$$
is answer.
Comment: @user2468338 Since the quintic $16s^5-20s^3+5s-1$ is a polynomial with integer coefficients, we may use the [rational root test](https://en.wikipedia.org/wiki/Rational_root_theorem) to quickly determine that any rational roots must be powers of $\frac12$ up to $\frac{1}{16}$. Plugging $s=\frac{1}{2^n}$ we see that $s=1$ is the only rational root. After that, there are standard methods for factoring quartics.
Comment: Could you explain how  $ \sin\frac\pi{10}-\cos\frac{\pi}{5} $ is equal to $ 2s^2 + s - 1 $.
Comment: @user2468338 $\cos 2x = 1 - 2\sin^2 x$
Comment: How did you factor $ 16s^5 - 20s^3 + 5s - 1 $
Comment: @user2468338, actually, with Maple's help))) But $s=1$ is a root, and you should to factor $16s^4+16s^3-4s^2-4s+1$
Answer: You have done your question already. Note that  $sin18^\circ=\frac{\sqrt{5}-1}{4}$ and  $cos36^\circ=\frac{\sqrt{5}+1}{4}$.If you had done mulitiple angles in trigonometry you can easily calculate these.
For $sin18^\circ$ let, $A=18^\circ$. Then $5A=90^\circ$
$2A=90^\circ-3A$
$Sin2A=cos3A$. Use $Sin2A=2sinAcosA$ and $Cos3A=4cos^3A-3CosA.$
Answer: $\sin(5\cdot78^\circ)=\sin(360^\circ+30^\circ)=\sin30^\circ$
$\sin\{5(-66^\circ)\}=\sin(-360^\circ+30^\circ)=\sin30^\circ$
If $\sin5x=\sin30^\circ\implies5x=n180^\circ+(-1)^n30^\circ$ where $n$ is any integer
$\implies x=n72^\circ+6^\circ$ where $n\equiv-2,-1,0,1,2\pmod5$
Again, $\sin5x=16\sin^5x-20\sin^3x+5\sin x$
So, the roots of $\displaystyle16\sin^5x-20\sin^3x+5\sin x=\dfrac12$ are $\sin\left(n72^\circ+6^\circ\right)$ where $n\equiv-2,-1,0,1,2\pmod5$
Using Vieta's formula, $\displaystyle\sum_{n=-2}^2\sin\left(n72^\circ+6^\circ\right)=0$
$n=-2\implies$ $-2\cdot72^\circ+6^\circ=-138^\circ\implies\sin(-138^\circ)=-\sin(138^\circ)=-\sin(180^\circ-42^\circ)=-\sin42^\circ$
$n=-1\implies$ $-1\cdot72^\circ+6^\circ=-66^\circ\implies\sin(-66^\circ)=-\sin66^\circ$
$n=0\implies ?$
$n=1\implies ?$
and $n=2\implies\sin\left(2\cdot72^\circ+6^\circ\right)=\sin150^\circ=\dfrac12$
Do you see the destination?
Answer: As $\sin(-A)=-\sin A,\sin(180^\circ-B)=\sin B$
$S=\sin78^\circ-\sin66^\circ-\sin42^\circ+\sin6^\circ $
$=\sin(-138^\circ)+\sin(-66^\circ)+\sin6°+\sin78^\circ $
Observe that the angles are in Arithmetic Progression with common difference $=72^\circ$
Using How can we sum up $\sin$ and $\cos$ series when the angles are in arithmetic progression?
and Werner Formula: $2\sin A\sin B=\cos(A-B)-\cos(A+B),$
and finally Prosthaphaeresis Formula, $\cos C+\cos D=2\cos\dfrac{C+D}2\cos\dfrac{C-D}2$
$2\sin36^\circ\cdot S=-2\cos54^\circ\cos60^\circ\implies S=-\dfrac12$


importance sampling from posterior distribution in R

Question: Today I read that Importance Sampling can be used to draw posterior distribution samples just like Rejection Sampling. However, my understanding of Importance Sampling is that its main purpose is to just compute expectations (ie. integrals) that would otherwise be hard to compute. How can Importance Sampling be used to draw posterior distribution samples from a Bayesian Model?
I only know the posterior positive ratio up to some constant, i.e., a constant term in the normalisation.
Answer: The boundary between estimating expectations and producing simulations is rather vague in the sense that, once given an importance sampling sample
$$(x_1,\omega_1),\ldots,(x_T,\omega_T)\qquad\omega_t=f(x_t)/g(x_t)$$
estimating $\mathbb E_f[h(X)]$ by $$\frac{1}{T}\,\sum_{t=1}^T \omega_t h(x_t)$$ and estimating the cdf $F(\cdot)$ by$$\hat F(x)=\frac{1}{T}\,\sum_{t=1}^T\omega_t \Bbb I_{x\le x_t}$$ is of the same nature. Simulating from $\hat F$ is easily done by inversion and is also the concept at the basis of weighted bootstrap.
In the case where the density $f$ is not properly normalised, as in most Bayesian settings, renormalising the $\omega_t$'s by their sum is also a converging approximation.
$\qquad\qquad$
The field of particle filters and sequential Monte Carlo (SMC) is taking advantage of this principle to handle sequential targets and state-space models. As in the illustrations above and below:
$\qquad\qquad$
Answer: by using IS(importance sampling) you can calculate a expectation of posterior, that is enough to take prior as Importance distribution. to generate random sample from posterior, you should re-sampling from sample that generated from prior. you should use, SIR (sampling importance resampling).
SIR is a extended of IS that by using it you can draw sample from a posterior distribution
SIR
to generate $m$ sample from the posterior distribution,
$\pi(\theta|X) \propto f(x|\theta) \pi(\theta)$, follow this step:
step 1: draw $k$ i.i.d sample from $\pi(\theta)$,(k>m)
$\{\theta_i \}_{i=1}^{k} \overset{i.i.d}{\sim} \pi(\theta)$
step 2
appoint weight
\begin{array}{c|cccc}
\theta & \theta_1 &  \theta_2  & \cdots  &  \theta_k \\ \hline \\
w & w_1=\frac{p(x|\theta_1)}{\sum_{i=1}^{m} p(x|\theta_i)}
       & w_2= \frac{p(x|\theta_2)}{\sum_{i=1}^{m} p(x|\theta_i)}
       &  \cdots
       & w_k=\frac{p(x|\theta_m)}{\sum_{i=1}^{m} p(x|\theta_i)}
\end{array}
now by sampling $\{\theta_i \}_{i=1}^{m}$ (without replacement) form
$\{\theta_i \}_{i=1}^{k}$  with probability $\{w_i \}_{i=1}^{k}$ , you can obtain random sample from posterior.


Solving the recurrence $T(n) = 3T\left(\frac{n}{3}\right) + n\log_2 n$

Question:
I've seen plenty of discussion regarding solving recurrences like this with the master theorem, but I need to solve it via back substitution. Was doing pretty good until I got stuck in the summation part.
Assumptions are that $n$ is a power of $3$ so $n = 3^k$ and hence $k = \log_3(n)$. Also $T(1) = 1$.
After substituting $3$ functions to recognize the pattern I found this general form for the recurrence:

And then I followed with:

However this is the part where I got stuck:

I have absolutely no idea of how to resolve that sum, I tried applying logarithm properties to get a difference instead of division and then make two separated and simplier sums, but I still couldn't find or figure out if I can use any summation identities.
Comment: Note that $$\sum_{i=0}^{k-1}\log_3\left(\frac n{3^i}\right)=\sum_{i=0}^{k-1}(\log_3 n-i)=k\log_3n-\sum_{i=0}^{k-1}i$$ hence $$\sum_{i=0}^{k-1}\log_3\left(\frac n{3^i}\right)=k\log_3n-\frac{k(k-1)}2$$
Comment: Because $\log_3n$ does not depend on $i$. And because there are $k$ terms in the sum. For every number $c$ independent of $i$, $$\sum_{i=0}^{k-1}c=c\,k$$
Comment: Why are you able to take *log3(n)* out of the summation without writing it in sigma notation again? Where does the *k* multiplying that come from? D:
Comment: that means *log3(n)* could be treated as a constant? or does "constant" in this case just means not dependant on the sum index?
Comment: Either one you prefer.
Comment: also I just noticed it is log2(n/3^i) and not log3 ):
Comment: Trivial changes, similar result.
Answer: I will redo the work from begginning also using $\lg x=\log_2 x$ as binary logarithm.
First I will iterate the first term, then later combine it with the sum which the second term gave:$$T(n)=3T\left(\frac{n}{3}\right)+n\lg n$$
$$3T\left(\frac{n}{3}\right)=3\left(3T\left(\frac{n}{3^2}\right)+\frac{n}{3}\lg\frac{n}{3}\right)=3^2T\left(\frac{n}{3^2}\right)+n\lg\frac{n}{3}$$
$$3^2T\left(\frac{n}{3^2}\right)=3^2\left(3T\left(\frac{n}{3^3}\right)+\frac{n}{3^2}\lg\frac{n}{3^2}\right)=3^3T\left(\frac{n}{3^3}\right)+n\lg\frac{n}{3^2}$$
$$\dots$$
$$3^{k-1}T\left(\frac{n}{3^{k-1}}\right)=3^kT\left(\frac{n}{3^k}\right)+n\lg\frac{n}{3^{k-1}}$$
The recursion ends when we hit $T(1)$, thus we can take $k$ from there:
$$T\left(\frac{n}{3^k}\right)=T(1)\Rightarrow n=3^k\Rightarrow k=\log_3n$$
$$\Rightarrow T(n)=3^k \cdot \underbrace{T(1)}_{=1}+n\lg n +n\lg\frac{n}{3}+\dots+n\lg\frac{n}{3^{k-1}}$$
$$=\underbrace{3^{\log_3 n}}_{=n} \cdot 1 +\sum_{i=0}^{k-1}n \lg\frac{n}{3^{i}}=n+n\sum_{i=0}^{k-1}\left(\lg n-\lg3^{i}\right),\quad \quad a^{\log_a b}=b^{\log_a a}$$
$$=n+n\lg n \sum_{i=0}^{k-1}1-n\sum_{i=0}^{k-1}i \cdot \lg 3, \quad \quad \lg a^b = b\lg a$$
$$=n+n\lg n \cdot k -n\lg 3 \cdot \frac{(k-1)k}{2}$$
$$=n+n\lg n \cdot \frac{\lg n}{\lg 3}-\frac{\lg 3}{2}n\left(\frac{\lg n}{\lg 3}-1\right)\frac{\lg n}{\lg 3},\quad \quad k=\log_3 n =\frac{\lg n}{\lg 3}$$
$$=n+\frac{1}{\lg 3} n\lg^2 n -\frac12 \frac{1}{\lg 3}n\lg^2 n+\frac12 n\lg n$$
$$\boxed{T(n)=n+\frac1{2\log_2 3} n\log_2^2 n +\frac12 n\log_2 n}$$
Comment: I tried to follow from where I got stuck, but I got a slightly different result. Could you check my edit at the end of my question and check if I missed something? I think you missed multiplying by *lg3* in one of the denominators, but it could be my mistake too
Comment: Excellent thank you very much, it took me a while to follow your proceedure, but I understand everything now (:
Comment: @MikeKatz45 Yes, I forgot to multiply there by the red factor: $$\frac{\lg 3}{2}n\left(\frac{\lg n}{\lg 3}-1\right)\frac{\lg n}{\color{red}{\lg 3}}$$
Also note that  you have a minus sign when you mutiply by $1$, thus the last term will have a plus.
Answer: Considering from $T(n)-3T(\frac n3)=n\log_2 n$
$$
\mathcal{T}(\log_3 n)-3\mathcal{T}(\log_3(\frac n3))=n\log_2 n
$$
or
$$
\mathcal{T}(\log_3 n)-3\mathcal{T}(\log_3 n -1))=n\log_2 n
$$
then making $z = \log_3 n$ we have the linear difference equation
$$
\mathcal{T}(z)-3\mathcal{T}(z -1)=3^z\log_2 3^z = z 3^z\log_2 3
$$
The solution can be represented as
$$
\mathcal{T} = \mathcal{T}_h+ \mathcal{T}_p
$$
such that
$$
\mathcal{T}_h(z)-3\mathcal{T}_h(z -1)=0\\
\mathcal{T}_p(z)-3\mathcal{T}_p(z -1)=z 3^z\log_2 3
$$
but
$$
\mathcal{T}_h(z) = C 3^{z-1}
$$
now substituting $\mathcal{T}_p(z) = C(z) 3^{z-1}$ into the particular equation (variation of constants as with DE's) we obtain
$$
C(z)-C(z-1) = z^2 3^{2-z}\log_2 3
$$
and then
$$
C(z) = \frac 12 3^{3-z}\left(3^z-z-\frac{z^2}{3}-1\right)\log_2 3
$$
and finally
$$
\mathcal{T} = C 3^{z-1}+\left( \frac 12 3^{3-z}\left(3^z-z-\frac{z^2}{3}-1\right)\log_2 3\right)3^{z-1}
$$
etc.


How to replace text in many nodes?

Question: We're upgrading from Bootstrap 2 to 3. Now I need to replace CSS classes in the body fields of many nodes. This needs to be done in at least 5 sites. What is a good way to replace text in all nodes of a site?
Ideally I'd do it with something like drush replace old_str new_str. Found one thing from 2009 that didn't work at all and then I found drush sar, which didn't do the job either.
Answer: The Drush Search and Replace plugin may be of some use

This drush plugin performs a text search & replace on all content and content revisions in all text fields and all custom blocks on a Drupal site.
It does this directly in the database, not by loading, editing and then saving entities, so it is very fast. This also means you should clear the Drupal caches after you run this command.

Hopefully it goes without saying you should give this a dry run before applying it to a live site, how well it works will depend on exactly what data you have in the fields.
Comment: I ran into `sar` but it doesn't work. I'll add a bug report on d.o if nothing better pops up.
Comment: It should work for trivial examples like 'row-fluid' => 'row', but obviously it's not going to work for 'span*' => 'col-md-*' and the more complex examples, as those can't be fixed with a simple string replace anyway. A regular expression would be prohibitively complex, so the only real option for those cases is to parse the HTML and loop through the nodes, checking the attributes as you go, changing what needs it, then exporting back to HTML before saving. I'd be surprised if there's a ready-made solution for that, it's a very specific use-case
Comment: That's exactly what I tried, `drush sar row-fluid row`. Didn't work.
No need for ready-made Bootstrap upgrade solution but I'll be happy to put the script I'll make somewhere in a gist.
Comment: Ah ok, that probably is a bug then

How to replace text in many nodes?


Stability of VAR(1)

Question: Consider VAR(1) process
$$y_t = A_1y_{t-1} + u_t.$$
I am looking for a reference or proof that if all entries in $A_1$ are less than one in modulus then $y_t$ is stable. I am sure that last semester a professor told that, but I can't find a reference.

Edit1:
In response to @Jarle Tufto answer, I believe that this is a sufficient condition. To support my argument I did a simulation in R where I simulate 20 different series (100 steps ahead) for the case when entries in $A_1$ are uniformly distributed between $0$ and $1$. All series converge to zero.

The R code
n <- 20 #fix the number of series
I = diag(n)
A <- matrix(runif(n^2), ncol = n, nrow = n) #Create matrix A with 0 < a_ij < 1
y = matrix(0, nrow = n, ncol = 100) #create vector of predictions (100 steps ahead)
y[, 1] = rnorm(n) #set initial values
for (i in 2:ncol(y)) {
    y[, i] = A^(i-1)%*%y[, i-1]
}
require(ggplot2)
require(reshape2)
y_m <- melt(y)
ggplot() +
  geom_line(data = y_m, aes(x = X2, y = value, color = factor(X1))) +
  xlab('Step') + ylab('Value')

Edit 2:
Here is the result for the case when all entries of $A$ are $0.9$. In the previous code I changed
A <- matrix(runif(n^2), ncol = n, nrow = n)
to
A <- matrix(0.9, ncol = n, nrow = n)
Still have convergence, though the shape looks strange.
Comment: VAR is an acronym, so there is no need to format it as a formula. Good question, though.
Comment: That was just good (or maybe bad) luck. It is not a sufficient condition.  Try $A$ with all entries equal to .9 and it will not be stationary!
Comment: @JarleTufto please see my second edit.
Comment: I don't understand your simulation code.  Inside your for-loop you do 'y[, i] = A^(i-1)%*%y[, i-1]'.  Why do you raise all elements of A to the $(i-1)$ power?  And you need to add the white noise term $u_t$.
Comment: @JarleTufto oops, agree. Indeed, you are right, this is not a sufficient condition. Forgot that `^` should be replaced by `%^%` in `R` (with loading `expm` package).
Answer: A VAR(1) process is stationary if the largest eigenvalue of $A$ has modulus smaller than 1, see Wei 2006, ch. 16.  The condition you refer to is neither a necessary or sufficient condition for stationarity.
Answer: I think your simulations are just luck. Take this example:
$$
\begin{bmatrix}
0.8 & 0.2 \\
0.4 & 0.6
\end{bmatrix}
$$
All entries are less than 1 but the matrix has 1 as an eigenvalue. So it is not stationary. Any starting point other than (0,0) that is less than one in the two entries will eventually converge to (2/3 , 1/3). And if they are higher than 1, it will diverge.
Take a look at the definition of markov matrices.

Stability of VAR(1)